PK ~\ >minipass-sized/package.jsonnu[{ "_id": "minipass-sized@1.0.3", "_inBundle": true, "_location": "/npm/minipass-sized", "_phantomChildren": { "yallist": "4.0.0" }, "_requiredBy": [ "/npm/minipass-fetch" ], "author": { "name": "Isaac Z. Schlueter", "email": "i@izs.me", "url": "https://izs.me" }, "bugs": { "url": "https://github.com/isaacs/minipass-sized/issues" }, "dependencies": { "minipass": "^3.0.0" }, "description": "A Minipass stream that raises an error if you get a different number of bytes than expected", "devDependencies": { "tap": "^14.6.4" }, "directories": { "test": "test" }, "engines": { "node": ">=8" }, "homepage": "https://github.com/isaacs/minipass-sized#readme", "keywords": [ "minipass", "size", "length" ], "license": "ISC", "main": "index.js", "name": "minipass-sized", "repository": { "type": "git", "url": "git+https://github.com/isaacs/minipass-sized.git" }, "scripts": { "postpublish": "git push origin --follow-tags", "postversion": "npm publish", "preversion": "npm test", "snap": "tap", "test": "tap" }, "tap": { "check-coverage": true }, "version": "1.0.3" } PK ~\>Qi1minipass-sized/node_modules/minipass/package.jsonnu[{ "_id": "minipass@3.3.6", "_inBundle": true, "_location": "/npm/minipass-sized/minipass", "_phantomChildren": {}, "_requiredBy": [ "/npm/minipass-sized" ], "author": { "name": "Isaac Z. Schlueter", "email": "i@izs.me", "url": "http://blog.izs.me/" }, "bugs": { "url": "https://github.com/isaacs/minipass/issues" }, "dependencies": { "yallist": "^4.0.0" }, "description": "minimal implementation of a PassThrough stream", "devDependencies": { "@types/node": "^17.0.41", "end-of-stream": "^1.4.0", "prettier": "^2.6.2", "tap": "^16.2.0", "through2": "^2.0.3", "ts-node": "^10.8.1", "typescript": "^4.7.3" }, "engines": { "node": ">=8" }, "files": [ "index.d.ts", "index.js" ], "homepage": "https://github.com/isaacs/minipass#readme", "keywords": [ "passthrough", "stream" ], "license": "ISC", "main": "index.js", "name": "minipass", "prettier": { "semi": false, "printWidth": 80, "tabWidth": 2, "useTabs": false, "singleQuote": true, "jsxSingleQuote": false, "bracketSameLine": true, "arrowParens": "avoid", "endOfLine": "lf" }, "repository": { "type": "git", "url": "git+https://github.com/isaacs/minipass.git" }, "scripts": { "postpublish": "git push origin --follow-tags", "postversion": "npm publish", "preversion": "npm test", "test": "tap" }, "tap": { "check-coverage": true }, "types": "index.d.ts", "version": "3.3.6" } PK ~\,minipass-sized/node_modules/minipass/LICENSEnu[The ISC License Copyright (c) 2017-2022 npm, Inc., Isaac Z. Schlueter, and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\-@@-minipass-sized/node_modules/minipass/index.jsnu['use strict' const proc = typeof process === 'object' && process ? process : { stdout: null, stderr: null, } const EE = require('events') const Stream = require('stream') const SD = require('string_decoder').StringDecoder const EOF = Symbol('EOF') const MAYBE_EMIT_END = Symbol('maybeEmitEnd') const EMITTED_END = Symbol('emittedEnd') const EMITTING_END = Symbol('emittingEnd') const EMITTED_ERROR = Symbol('emittedError') const CLOSED = Symbol('closed') const READ = Symbol('read') const FLUSH = Symbol('flush') const FLUSHCHUNK = Symbol('flushChunk') const ENCODING = Symbol('encoding') const DECODER = Symbol('decoder') const FLOWING = Symbol('flowing') const PAUSED = Symbol('paused') const RESUME = Symbol('resume') const BUFFERLENGTH = Symbol('bufferLength') const BUFFERPUSH = Symbol('bufferPush') const BUFFERSHIFT = Symbol('bufferShift') const OBJECTMODE = Symbol('objectMode') const DESTROYED = Symbol('destroyed') const EMITDATA = Symbol('emitData') const EMITEND = Symbol('emitEnd') const EMITEND2 = Symbol('emitEnd2') const ASYNC = Symbol('async') const defer = fn => Promise.resolve().then(fn) // TODO remove when Node v8 support drops const doIter = global._MP_NO_ITERATOR_SYMBOLS_ !== '1' const ASYNCITERATOR = doIter && Symbol.asyncIterator || Symbol('asyncIterator not implemented') const ITERATOR = doIter && Symbol.iterator || Symbol('iterator not implemented') // events that mean 'the stream is over' // these are treated specially, and re-emitted // if they are listened for after emitting. const isEndish = ev => ev === 'end' || ev === 'finish' || ev === 'prefinish' const isArrayBuffer = b => b instanceof ArrayBuffer || typeof b === 'object' && b.constructor && b.constructor.name === 'ArrayBuffer' && b.byteLength >= 0 const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b) class Pipe { constructor (src, dest, opts) { this.src = src this.dest = dest this.opts = opts this.ondrain = () => src[RESUME]() dest.on('drain', this.ondrain) } unpipe () { this.dest.removeListener('drain', this.ondrain) } // istanbul ignore next - only here for the prototype proxyErrors () {} end () { this.unpipe() if (this.opts.end) this.dest.end() } } class PipeProxyErrors extends Pipe { unpipe () { this.src.removeListener('error', this.proxyErrors) super.unpipe() } constructor (src, dest, opts) { super(src, dest, opts) this.proxyErrors = er => dest.emit('error', er) src.on('error', this.proxyErrors) } } module.exports = class Minipass extends Stream { constructor (options) { super() this[FLOWING] = false // whether we're explicitly paused this[PAUSED] = false this.pipes = [] this.buffer = [] this[OBJECTMODE] = options && options.objectMode || false if (this[OBJECTMODE]) this[ENCODING] = null else this[ENCODING] = options && options.encoding || null if (this[ENCODING] === 'buffer') this[ENCODING] = null this[ASYNC] = options && !!options.async || false this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null this[EOF] = false this[EMITTED_END] = false this[EMITTING_END] = false this[CLOSED] = false this[EMITTED_ERROR] = null this.writable = true this.readable = true this[BUFFERLENGTH] = 0 this[DESTROYED] = false } get bufferLength () { return this[BUFFERLENGTH] } get encoding () { return this[ENCODING] } set encoding (enc) { if (this[OBJECTMODE]) throw new Error('cannot set encoding in objectMode') if (this[ENCODING] && enc !== this[ENCODING] && (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH])) throw new Error('cannot change encoding') if (this[ENCODING] !== enc) { this[DECODER] = enc ? new SD(enc) : null if (this.buffer.length) this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk)) } this[ENCODING] = enc } setEncoding (enc) { this.encoding = enc } get objectMode () { return this[OBJECTMODE] } set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om } get ['async'] () { return this[ASYNC] } set ['async'] (a) { this[ASYNC] = this[ASYNC] || !!a } write (chunk, encoding, cb) { if (this[EOF]) throw new Error('write after end') if (this[DESTROYED]) { this.emit('error', Object.assign( new Error('Cannot call write after a stream was destroyed'), { code: 'ERR_STREAM_DESTROYED' } )) return true } if (typeof encoding === 'function') cb = encoding, encoding = 'utf8' if (!encoding) encoding = 'utf8' const fn = this[ASYNC] ? defer : f => f() // convert array buffers and typed array views into buffers // at some point in the future, we may want to do the opposite! // leave strings and buffers as-is // anything else switches us into object mode if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { if (isArrayBufferView(chunk)) chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) else if (isArrayBuffer(chunk)) chunk = Buffer.from(chunk) else if (typeof chunk !== 'string') // use the setter so we throw if we have encoding set this.objectMode = true } // handle object mode up front, since it's simpler // this yields better performance, fewer checks later. if (this[OBJECTMODE]) { /* istanbul ignore if - maybe impossible? */ if (this.flowing && this[BUFFERLENGTH] !== 0) this[FLUSH](true) if (this.flowing) this.emit('data', chunk) else this[BUFFERPUSH](chunk) if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } // at this point the chunk is a buffer or string // don't buffer it up or send it to the decoder if (!chunk.length) { if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } // fast-path writing strings of same encoding to a stream with // an empty buffer, skipping the buffer/decoder dance if (typeof chunk === 'string' && // unless it is a string already ready for us to use !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) { chunk = Buffer.from(chunk, encoding) } if (Buffer.isBuffer(chunk) && this[ENCODING]) chunk = this[DECODER].write(chunk) // Note: flushing CAN potentially switch us into not-flowing mode if (this.flowing && this[BUFFERLENGTH] !== 0) this[FLUSH](true) if (this.flowing) this.emit('data', chunk) else this[BUFFERPUSH](chunk) if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } read (n) { if (this[DESTROYED]) return null if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) { this[MAYBE_EMIT_END]() return null } if (this[OBJECTMODE]) n = null if (this.buffer.length > 1 && !this[OBJECTMODE]) { if (this.encoding) this.buffer = [this.buffer.join('')] else this.buffer = [Buffer.concat(this.buffer, this[BUFFERLENGTH])] } const ret = this[READ](n || null, this.buffer[0]) this[MAYBE_EMIT_END]() return ret } [READ] (n, chunk) { if (n === chunk.length || n === null) this[BUFFERSHIFT]() else { this.buffer[0] = chunk.slice(n) chunk = chunk.slice(0, n) this[BUFFERLENGTH] -= n } this.emit('data', chunk) if (!this.buffer.length && !this[EOF]) this.emit('drain') return chunk } end (chunk, encoding, cb) { if (typeof chunk === 'function') cb = chunk, chunk = null if (typeof encoding === 'function') cb = encoding, encoding = 'utf8' if (chunk) this.write(chunk, encoding) if (cb) this.once('end', cb) this[EOF] = true this.writable = false // if we haven't written anything, then go ahead and emit, // even if we're not reading. // we'll re-emit if a new 'end' listener is added anyway. // This makes MP more suitable to write-only use cases. if (this.flowing || !this[PAUSED]) this[MAYBE_EMIT_END]() return this } // don't let the internal resume be overwritten [RESUME] () { if (this[DESTROYED]) return this[PAUSED] = false this[FLOWING] = true this.emit('resume') if (this.buffer.length) this[FLUSH]() else if (this[EOF]) this[MAYBE_EMIT_END]() else this.emit('drain') } resume () { return this[RESUME]() } pause () { this[FLOWING] = false this[PAUSED] = true } get destroyed () { return this[DESTROYED] } get flowing () { return this[FLOWING] } get paused () { return this[PAUSED] } [BUFFERPUSH] (chunk) { if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1 else this[BUFFERLENGTH] += chunk.length this.buffer.push(chunk) } [BUFFERSHIFT] () { if (this.buffer.length) { if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1 else this[BUFFERLENGTH] -= this.buffer[0].length } return this.buffer.shift() } [FLUSH] (noDrain) { do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]())) if (!noDrain && !this.buffer.length && !this[EOF]) this.emit('drain') } [FLUSHCHUNK] (chunk) { return chunk ? (this.emit('data', chunk), this.flowing) : false } pipe (dest, opts) { if (this[DESTROYED]) return const ended = this[EMITTED_END] opts = opts || {} if (dest === proc.stdout || dest === proc.stderr) opts.end = false else opts.end = opts.end !== false opts.proxyErrors = !!opts.proxyErrors // piping an ended stream ends immediately if (ended) { if (opts.end) dest.end() } else { this.pipes.push(!opts.proxyErrors ? new Pipe(this, dest, opts) : new PipeProxyErrors(this, dest, opts)) if (this[ASYNC]) defer(() => this[RESUME]()) else this[RESUME]() } return dest } unpipe (dest) { const p = this.pipes.find(p => p.dest === dest) if (p) { this.pipes.splice(this.pipes.indexOf(p), 1) p.unpipe() } } addListener (ev, fn) { return this.on(ev, fn) } on (ev, fn) { const ret = super.on(ev, fn) if (ev === 'data' && !this.pipes.length && !this.flowing) this[RESUME]() else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) super.emit('readable') else if (isEndish(ev) && this[EMITTED_END]) { super.emit(ev) this.removeAllListeners(ev) } else if (ev === 'error' && this[EMITTED_ERROR]) { if (this[ASYNC]) defer(() => fn.call(this, this[EMITTED_ERROR])) else fn.call(this, this[EMITTED_ERROR]) } return ret } get emittedEnd () { return this[EMITTED_END] } [MAYBE_EMIT_END] () { if (!this[EMITTING_END] && !this[EMITTED_END] && !this[DESTROYED] && this.buffer.length === 0 && this[EOF]) { this[EMITTING_END] = true this.emit('end') this.emit('prefinish') this.emit('finish') if (this[CLOSED]) this.emit('close') this[EMITTING_END] = false } } emit (ev, data, ...extra) { // error and close are only events allowed after calling destroy() if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED]) return else if (ev === 'data') { return !data ? false : this[ASYNC] ? defer(() => this[EMITDATA](data)) : this[EMITDATA](data) } else if (ev === 'end') { return this[EMITEND]() } else if (ev === 'close') { this[CLOSED] = true // don't emit close before 'end' and 'finish' if (!this[EMITTED_END] && !this[DESTROYED]) return const ret = super.emit('close') this.removeAllListeners('close') return ret } else if (ev === 'error') { this[EMITTED_ERROR] = data const ret = super.emit('error', data) this[MAYBE_EMIT_END]() return ret } else if (ev === 'resume') { const ret = super.emit('resume') this[MAYBE_EMIT_END]() return ret } else if (ev === 'finish' || ev === 'prefinish') { const ret = super.emit(ev) this.removeAllListeners(ev) return ret } // Some other unknown event const ret = super.emit(ev, data, ...extra) this[MAYBE_EMIT_END]() return ret } [EMITDATA] (data) { for (const p of this.pipes) { if (p.dest.write(data) === false) this.pause() } const ret = super.emit('data', data) this[MAYBE_EMIT_END]() return ret } [EMITEND] () { if (this[EMITTED_END]) return this[EMITTED_END] = true this.readable = false if (this[ASYNC]) defer(() => this[EMITEND2]()) else this[EMITEND2]() } [EMITEND2] () { if (this[DECODER]) { const data = this[DECODER].end() if (data) { for (const p of this.pipes) { p.dest.write(data) } super.emit('data', data) } } for (const p of this.pipes) { p.end() } const ret = super.emit('end') this.removeAllListeners('end') return ret } // const all = await stream.collect() collect () { const buf = [] if (!this[OBJECTMODE]) buf.dataLength = 0 // set the promise first, in case an error is raised // by triggering the flow here. const p = this.promise() this.on('data', c => { buf.push(c) if (!this[OBJECTMODE]) buf.dataLength += c.length }) return p.then(() => buf) } // const data = await stream.concat() concat () { return this[OBJECTMODE] ? Promise.reject(new Error('cannot concat in objectMode')) : this.collect().then(buf => this[OBJECTMODE] ? Promise.reject(new Error('cannot concat in objectMode')) : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength)) } // stream.promise().then(() => done, er => emitted error) promise () { return new Promise((resolve, reject) => { this.on(DESTROYED, () => reject(new Error('stream destroyed'))) this.on('error', er => reject(er)) this.on('end', () => resolve()) }) } // for await (let chunk of stream) [ASYNCITERATOR] () { const next = () => { const res = this.read() if (res !== null) return Promise.resolve({ done: false, value: res }) if (this[EOF]) return Promise.resolve({ done: true }) let resolve = null let reject = null const onerr = er => { this.removeListener('data', ondata) this.removeListener('end', onend) reject(er) } const ondata = value => { this.removeListener('error', onerr) this.removeListener('end', onend) this.pause() resolve({ value: value, done: !!this[EOF] }) } const onend = () => { this.removeListener('error', onerr) this.removeListener('data', ondata) resolve({ done: true }) } const ondestroy = () => onerr(new Error('stream destroyed')) return new Promise((res, rej) => { reject = rej resolve = res this.once(DESTROYED, ondestroy) this.once('error', onerr) this.once('end', onend) this.once('data', ondata) }) } return { next } } // for (let chunk of stream) [ITERATOR] () { const next = () => { const value = this.read() const done = value === null return { value, done } } return { next } } destroy (er) { if (this[DESTROYED]) { if (er) this.emit('error', er) else this.emit(DESTROYED) return this } this[DESTROYED] = true // throw away all buffered data, it's never coming out this.buffer.length = 0 this[BUFFERLENGTH] = 0 if (typeof this.close === 'function' && !this[CLOSED]) this.close() if (er) this.emit('error', er) else // if no error to emit, still reject pending promises this.emit(DESTROYED) return this } static isStream (s) { return !!s && (s instanceof Minipass || s instanceof Stream || s instanceof EE && ( typeof s.pipe === 'function' || // readable (typeof s.write === 'function' && typeof s.end === 'function') // writable )) } } PK ~\(minipass-sized/test/basic.jsnu[const t = require('tap') const MPS = require('../') t.test('ok if size checks out', t => { const mps = new MPS({ size: 4 }) mps.write(Buffer.from('a').toString('hex'), 'hex') mps.write(Buffer.from('sd')) mps.end('f') return mps.concat().then(data => t.equal(data.toString(), 'asdf')) }) t.test('error if size exceeded', t => { const mps = new MPS({ size: 1 }) mps.on('error', er => { t.match(er, { message: 'Bad data size: expected 1 bytes, but got 4', found: 4, expect: 1, code: 'EBADSIZE', name: 'SizeError', }) t.end() }) mps.write('asdf') }) t.test('error if size is not met', t => { const mps = new MPS({ size: 999 }) t.throws(() => mps.end(), { message: 'Bad data size: expected 999 bytes, but got 0', found: 0, name: 'SizeError', expect: 999, code: 'EBADSIZE', }) t.end() }) t.test('error if non-string/buffer is written', t => { const mps = new MPS({size:1}) mps.on('error', er => { t.match(er, { message: 'MinipassSized streams only work with string and buffer data' }) t.end() }) mps.write({some:'object'}) }) t.test('projectiles', t => { t.throws(() => new MPS(), { message: 'invalid expected size: undefined' }, 'size is required') t.throws(() => new MPS({size: true}), { message: 'invalid expected size: true' }, 'size must be number') t.throws(() => new MPS({size: NaN}), { message: 'invalid expected size: NaN' }, 'size must not be NaN') t.throws(() => new MPS({size:1.2}), { message: 'invalid expected size: 1.2' }, 'size must be integer') t.throws(() => new MPS({size: Infinity}), { message: 'invalid expected size: Infinity' }, 'size must be finite') t.throws(() => new MPS({size: -1}), { message: 'invalid expected size: -1' }, 'size must be positive') t.throws(() => new MPS({objectMode: true}), { message: 'MinipassSized streams only work with string and buffer data' }, 'no objectMode') t.throws(() => new MPS({size: Number.MAX_SAFE_INTEGER + 1000000}), { message: 'invalid expected size: 9007199255740992' }) t.end() }) t.test('exports SizeError class', t => { t.isa(MPS.SizeError, 'function') t.isa(MPS.SizeError.prototype, Error) t.end() }) PK ~\aGWminipass-sized/LICENSEnu[The ISC License Copyright (c) Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\SZ+minipass-sized/index.jsnu[const Minipass = require('minipass') class SizeError extends Error { constructor (found, expect) { super(`Bad data size: expected ${expect} bytes, but got ${found}`) this.expect = expect this.found = found this.code = 'EBADSIZE' Error.captureStackTrace(this, this.constructor) } get name () { return 'SizeError' } } class MinipassSized extends Minipass { constructor (options = {}) { super(options) if (options.objectMode) throw new TypeError(`${ this.constructor.name } streams only work with string and buffer data`) this.found = 0 this.expect = options.size if (typeof this.expect !== 'number' || this.expect > Number.MAX_SAFE_INTEGER || isNaN(this.expect) || this.expect < 0 || !isFinite(this.expect) || this.expect !== Math.floor(this.expect)) throw new Error('invalid expected size: ' + this.expect) } write (chunk, encoding, cb) { const buffer = Buffer.isBuffer(chunk) ? chunk : typeof chunk === 'string' ? Buffer.from(chunk, typeof encoding === 'string' ? encoding : 'utf8') : chunk if (!Buffer.isBuffer(buffer)) { this.emit('error', new TypeError(`${ this.constructor.name } streams only work with string and buffer data`)) return false } this.found += buffer.length if (this.found > this.expect) this.emit('error', new SizeError(this.found, this.expect)) return super.write(chunk, encoding, cb) } emit (ev, ...data) { if (ev === 'end') { if (this.found !== this.expect) this.emit('error', new SizeError(this.found, this.expect)) } return super.emit(ev, ...data) } } MinipassSized.SizeError = SizeError module.exports = MinipassSized PK ~\rrpromise-inflight/package.jsonnu[{ "_id": "promise-inflight@1.0.1", "_inBundle": true, "_location": "/npm/promise-inflight", "_phantomChildren": {}, "_requiredBy": [ "/npm/@npmcli/git" ], "author": { "name": "Rebecca Turner", "email": "me@re-becca.org", "url": "http://re-becca.org/" }, "bugs": { "url": "https://github.com/iarna/promise-inflight/issues" }, "description": "One promise for multiple requests in flight to avoid async duplication", "devDependencies": {}, "files": [ "inflight.js" ], "homepage": "https://github.com/iarna/promise-inflight#readme", "keywords": [], "license": "ISC", "main": "inflight.js", "name": "promise-inflight", "repository": { "type": "git", "url": "git+https://github.com/iarna/promise-inflight.git" }, "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "version": "1.0.1" } PK ~\(promise-inflight/LICENSEnu[Copyright (c) 2017, Rebecca Turner Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\JJpromise-inflight/inflight.jsnu['use strict' module.exports = inflight let Bluebird try { Bluebird = require('bluebird') } catch (_) { Bluebird = Promise } const active = {} inflight.active = active function inflight (unique, doFly) { return Bluebird.all([unique, doFly]).then(function (args) { const unique = args[0] const doFly = args[1] if (Array.isArray(unique)) { return Bluebird.all(unique).then(function (uniqueArr) { return _inflight(uniqueArr.join(''), doFly) }) } else { return _inflight(unique, doFly) } }) function _inflight (unique, doFly) { if (!active[unique]) { active[unique] = (new Bluebird(function (resolve) { return resolve(doFly()) })) active[unique].then(cleanup, cleanup) function cleanup() { delete active[unique] } } return active[unique] } } PK ~\{Zcmd-shim/package.jsonnu[{ "_id": "cmd-shim@6.0.3", "_inBundle": true, "_location": "/npm/cmd-shim", "_phantomChildren": {}, "_requiredBy": [ "/npm/bin-links" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/cmd-shim/issues" }, "description": "Used in npm for command line application support", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.22.0", "tap": "^16.0.1" }, "engines": { "node": "^14.17.0 || ^16.13.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/cmd-shim#readme", "license": "ISC", "main": "lib/index.js", "name": "cmd-shim", "repository": { "type": "git", "url": "git+https://github.com/npm/cmd-shim.git" }, "scripts": { "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "before": "test/00-setup.js", "after": "test/zz-cleanup.js", "check-coverage": true, "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.22.0", "publish": true }, "version": "6.0.3" } PK ~\rcmd-shim/lib/index.jsnu[// On windows, create a .cmd file. // Read the #! in the file to see what it uses. The vast majority // of the time, this will be either: // "#!/usr/bin/env " // or: // "#! " // // Write a binroot/pkg.bin + ".cmd" file that has this line in it: // @ %dp0% %* const { chmod, mkdir, readFile, stat, unlink, writeFile, } = require('fs/promises') const { dirname, relative } = require('path') const toBatchSyntax = require('./to-batch-syntax') // linting disabled because this regex is really long // eslint-disable-next-line max-len const shebangExpr = /^#!\s*(?:\/usr\/bin\/env\s+(?:-S\s+)?((?:[^ \t=]+=[^ \t=]+\s+)*))?([^ \t]+)(.*)$/ const cmdShimIfExists = (from, to) => stat(from).then(() => cmdShim(from, to), () => {}) // Try to unlink, but ignore errors. // Any problems will surface later. const rm = path => unlink(path).catch(() => {}) const cmdShim = (from, to) => stat(from).then(() => cmdShim_(from, to)) const cmdShim_ = (from, to) => Promise.all([ rm(to), rm(to + '.cmd'), rm(to + '.ps1'), ]).then(() => writeShim(from, to)) const writeShim = (from, to) => // make a cmd file and a sh script // First, check if the bin is a #! of some sort. // If not, then assume it's something that'll be compiled, or some other // sort of script, and just call it directly. mkdir(dirname(to), { recursive: true }) .then(() => readFile(from, 'utf8')) .then(data => { const firstLine = data.trim().split(/\r*\n/)[0] const shebang = firstLine.match(shebangExpr) if (!shebang) { return writeShim_(from, to) } const vars = shebang[1] || '' const prog = shebang[2] const args = shebang[3] || '' return writeShim_(from, to, prog, args, vars) }, () => writeShim_(from, to)) const writeShim_ = (from, to, prog, args, variables) => { let shTarget = relative(dirname(to), from) let target = shTarget.split('/').join('\\') let longProg let shProg = prog && prog.split('\\').join('/') let shLongProg let pwshProg = shProg && `"${shProg}$exe"` let pwshLongProg shTarget = shTarget.split('\\').join('/') args = args || '' variables = variables || '' if (!prog) { prog = `"%dp0%\\${target}"` shProg = `"$basedir/${shTarget}"` pwshProg = shProg args = '' target = '' shTarget = '' } else { longProg = `"%dp0%\\${prog}.exe"` shLongProg = `"$basedir/${prog}"` pwshLongProg = `"$basedir/${prog}$exe"` target = `"%dp0%\\${target}"` shTarget = `"$basedir/${shTarget}"` } // Subroutine trick to fix https://github.com/npm/cmd-shim/issues/10 // and https://github.com/npm/cli/issues/969 const head = '@ECHO off\r\n' + 'GOTO start\r\n' + ':find_dp0\r\n' + 'SET dp0=%~dp0\r\n' + 'EXIT /b\r\n' + ':start\r\n' + 'SETLOCAL\r\n' + 'CALL :find_dp0\r\n' let cmd if (longProg) { shLongProg = shLongProg.trim() args = args.trim() const variablesBatch = toBatchSyntax.convertToSetCommands(variables) cmd = head + variablesBatch + '\r\n' + `IF EXIST ${longProg} (\r\n` + ` SET "_prog=${longProg.replace(/(^")|("$)/g, '')}"\r\n` + ') ELSE (\r\n' + ` SET "_prog=${prog.replace(/(^")|("$)/g, '')}"\r\n` + ' SET PATHEXT=%PATHEXT:;.JS;=;%\r\n' + ')\r\n' + '\r\n' // prevent "Terminate Batch Job? (Y/n)" message // https://github.com/npm/cli/issues/969#issuecomment-737496588 + 'endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & ' + `"%_prog%" ${args} ${target} %*\r\n` } else { cmd = `${head}${prog} ${args} ${target} %*\r\n` } // #!/bin/sh // basedir=`dirname "$0"` // // case `uname` in // *CYGWIN*|*MINGW*|*MSYS*) // if command -v cygpath > /dev/null 2>&1; then // basedir=`cygpath -w "$basedir"` // fi // ;; // esac // // if [ -x "$basedir/node.exe" ]; then // exec "$basedir/node.exe" "$basedir/node_modules/npm/bin/npm-cli.js" "$@" // else // exec node "$basedir/node_modules/npm/bin/npm-cli.js" "$@" // fi let sh = '#!/bin/sh\n' sh = sh + `basedir=$(dirname "$(echo "$0" | sed -e 's,\\\\,/,g')")\n` + '\n' + 'case `uname` in\n' + ' *CYGWIN*|*MINGW*|*MSYS*)\n' + ' if command -v cygpath > /dev/null 2>&1; then\n' + ' basedir=`cygpath -w "$basedir"`\n' + ' fi\n' + ' ;;\n' + 'esac\n' + '\n' if (shLongProg) { sh = sh + `if [ -x ${shLongProg} ]; then\n` + ` exec ${variables}${shLongProg} ${args} ${shTarget} "$@"\n` + 'else \n' + ` exec ${variables}${shProg} ${args} ${shTarget} "$@"\n` + 'fi\n' } else { sh = sh + `exec ${shProg} ${args} ${shTarget} "$@"\n` } // #!/usr/bin/env pwsh // $basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent // // $ret=0 // $exe = "" // if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { // # Fix case when both the Windows and Linux builds of Node // # are installed in the same directory // $exe = ".exe" // } // if (Test-Path "$basedir/node") { // # Suport pipeline input // if ($MyInvocation.ExpectingInput) { // input | & "$basedir/node$exe" "$basedir/node_modules/npm/bin/npm-cli.js" $args // } else { // & "$basedir/node$exe" "$basedir/node_modules/npm/bin/npm-cli.js" $args // } // $ret=$LASTEXITCODE // } else { // # Support pipeline input // if ($MyInvocation.ExpectingInput) { // $input | & "node$exe" "$basedir/node_modules/npm/bin/npm-cli.js" $args // } else { // & "node$exe" "$basedir/node_modules/npm/bin/npm-cli.js" $args // } // $ret=$LASTEXITCODE // } // exit $ret let pwsh = '#!/usr/bin/env pwsh\n' + '$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent\n' + '\n' + '$exe=""\n' + 'if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {\n' + ' # Fix case when both the Windows and Linux builds of Node\n' + ' # are installed in the same directory\n' + ' $exe=".exe"\n' + '}\n' if (shLongProg) { pwsh = pwsh + '$ret=0\n' + `if (Test-Path ${pwshLongProg}) {\n` + ' # Support pipeline input\n' + ' if ($MyInvocation.ExpectingInput) {\n' + ` $input | & ${pwshLongProg} ${args} ${shTarget} $args\n` + ' } else {\n' + ` & ${pwshLongProg} ${args} ${shTarget} $args\n` + ' }\n' + ' $ret=$LASTEXITCODE\n' + '} else {\n' + ' # Support pipeline input\n' + ' if ($MyInvocation.ExpectingInput) {\n' + ` $input | & ${pwshProg} ${args} ${shTarget} $args\n` + ' } else {\n' + ` & ${pwshProg} ${args} ${shTarget} $args\n` + ' }\n' + ' $ret=$LASTEXITCODE\n' + '}\n' + 'exit $ret\n' } else { pwsh = pwsh + '# Support pipeline input\n' + 'if ($MyInvocation.ExpectingInput) {\n' + ` $input | & ${pwshProg} ${args} ${shTarget} $args\n` + '} else {\n' + ` & ${pwshProg} ${args} ${shTarget} $args\n` + '}\n' + 'exit $LASTEXITCODE\n' } return Promise.all([ writeFile(to + '.ps1', pwsh, 'utf8'), writeFile(to + '.cmd', cmd, 'utf8'), writeFile(to, sh, 'utf8'), ]).then(() => chmodShim(to)) } const chmodShim = to => Promise.all([ chmod(to, 0o755), chmod(to + '.cmd', 0o755), chmod(to + '.ps1', 0o755), ]) module.exports = cmdShim cmdShim.ifExists = cmdShimIfExists PK ~\(cmd-shim/lib/to-batch-syntax.jsnu[exports.replaceDollarWithPercentPair = replaceDollarWithPercentPair exports.convertToSetCommand = convertToSetCommand exports.convertToSetCommands = convertToSetCommands function convertToSetCommand (key, value) { var line = '' key = key || '' key = key.trim() value = value || '' value = value.trim() if (key && value && value.length > 0) { line = '@SET ' + key + '=' + replaceDollarWithPercentPair(value) + '\r\n' } return line } function extractVariableValuePairs (declarations) { var pairs = {} declarations.map(function (declaration) { var split = declaration.split('=') pairs[split[0]] = split[1] }) return pairs } function convertToSetCommands (variableString) { var variableValuePairs = extractVariableValuePairs(variableString.split(' ')) var variableDeclarationsAsBatch = '' Object.keys(variableValuePairs).forEach(function (key) { variableDeclarationsAsBatch += convertToSetCommand(key, variableValuePairs[key]) }) return variableDeclarationsAsBatch } function replaceDollarWithPercentPair (value) { var dollarExpressions = /\$\{?([^$@#?\- \t{}:]+)\}?/g var result = '' var startIndex = 0 do { var match = dollarExpressions.exec(value) if (match) { var betweenMatches = value.substring(startIndex, match.index) || '' result += betweenMatches + '%' + match[1] + '%' startIndex = dollarExpressions.lastIndex } } while (dollarExpressions.lastIndex > 0) result += value.slice(startIndex) return result } PK ~\!cmd-shim/LICENSEnu[The ISC License Copyright (c) npm, Inc. and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\""/(/(emoji-regex/text.jsnu["use strict"; module.exports = function () { // https://mths.be/emoji return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u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uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F?|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; }; PK ~\߻q8emoji-regex/package.jsonnu[{ "_id": "emoji-regex@8.0.0", "_inBundle": true, "_location": "/npm/emoji-regex", "_phantomChildren": {}, "_requiredBy": [ "/npm/string-width", "/npm/string-width-cjs" ], "author": { "name": "Mathias Bynens", "url": "https://mathiasbynens.be/" }, "bugs": { "url": "https://github.com/mathiasbynens/emoji-regex/issues" }, "description": "A regular expression to match all Emoji-only symbols as per the Unicode Standard.", "devDependencies": { "@babel/cli": "^7.2.3", "@babel/core": "^7.3.4", "@babel/plugin-proposal-unicode-property-regex": "^7.2.0", "@babel/preset-env": "^7.3.4", "mocha": "^6.0.2", "regexgen": "^1.3.0", "unicode-12.0.0": "^0.7.9" }, "files": [ "LICENSE-MIT.txt", "index.js", "index.d.ts", "text.js", "es2015/index.js", "es2015/text.js" ], "homepage": "https://mths.be/emoji-regex", "keywords": [ "unicode", "regex", "regexp", "regular expressions", "code points", "symbols", "characters", "emoji" ], "license": "MIT", "main": "index.js", "name": "emoji-regex", "repository": { "type": "git", "url": "git+https://github.com/mathiasbynens/emoji-regex.git" }, "scripts": { "build": "rm -rf -- es2015; babel src -d .; NODE_ENV=es2015 babel src -d ./es2015; node script/inject-sequences.js", "test": "mocha", "test:watch": "npm run test -- --watch" }, "types": "index.d.ts", "version": "8.0.0" } PK ~\C".(.(emoji-regex/index.jsnu["use strict"; module.exports = function () { // https://mths.be/emoji return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?: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\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; }; PK ~\ڌC55emoji-regex/LICENSE-MIT.txtnu[Copyright Mathias Bynens Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\a+a+emoji-regex/es2015/text.jsnu["use strict"; module.exports = () => { // https://mths.be/emoji return /\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0065}\u{E006E}\u{E0067}|\u{E0073}\u{E0063}\u{E0074}|\u{E0077}\u{E006C}\u{E0073})\u{E007F}|\u{1F468}(?:\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}\u{1F3FB}|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FE}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u2695\u2696\u2708]\uFE0F|[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|(?:\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708])\uFE0F|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|[\u{1F3FB}-\u{1F3FF}])|(?:\u{1F9D1}\u{1F3FB}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F469})\u{1F3FB}|\u{1F9D1}(?:\u{1F3FF}\u200D\u{1F91D}\u200D\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]|\u200D\u{1F91D}\u200D\u{1F9D1})|(?:\u{1F9D1}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FF}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FE}]|(?:\u{1F9D1}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}\u{1F3FC}]|\u{1F469}(?:\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FB}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FC}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|(?:\u{1F9D1}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}-\u{1F3FD}]|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F469}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}]\uFE0F|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D6}-\u{1F9DD}](?:[\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\u{1F3F4}\u200D\u2620)\uFE0F|\u{1F469}\u200D\u{1F467}\u200D[\u{1F466}\u{1F467}]|\u{1F3F3}\uFE0F\u200D\u{1F308}|\u{1F415}\u200D\u{1F9BA}|\u{1F469}\u200D\u{1F466}|\u{1F469}\u200D\u{1F467}|\u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1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]|[\u261D\u270A-\u270D\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F470}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F4AA}\u{1F574}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F936}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}-\u{1F9D5}][\u{1F3FB}-\u{1F3FF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F393}\u{1F3A0}-\u{1F3CA}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F4}\u{1F3F8}-\u{1F43E}\u{1F440}\u{1F442}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F57A}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5FB}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CC}\u{1F6D0}-\u{1F6D2}\u{1F6D5}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]|[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299\u{1F004}\u{1F0CF}\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F321}\u{1F324}-\u{1F393}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}-\u{1F3F0}\u{1F3F3}-\u{1F3F5}\u{1F3F7}-\u{1F4FD}\u{1F4FF}-\u{1F53D}\u{1F549}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F56F}\u{1F570}\u{1F573}-\u{1F57A}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F590}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CB}-\u{1F6D2}\u{1F6D5}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6EB}\u{1F6EC}\u{1F6F0}\u{1F6F3}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]\uFE0F?|[\u261D\u26F9\u270A-\u270D\u{1F385}\u{1F3C2}-\u{1F3C4}\u{1F3C7}\u{1F3CA}-\u{1F3CC}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}-\u{1F478}\u{1F47C}\u{1F481}-\u{1F483}\u{1F485}-\u{1F487}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F574}\u{1F575}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F645}-\u{1F647}\u{1F64B}-\u{1F64F}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91F}\u{1F926}\u{1F930}-\u{1F939}\u{1F93C}-\u{1F93E}\u{1F9B5}\u{1F9B6}\u{1F9B8}\u{1F9B9}\u{1F9BB}\u{1F9CD}-\u{1F9CF}\u{1F9D1}-\u{1F9DD}]/gu; }; PK ~\`+`+emoji-regex/es2015/index.jsnu["use strict"; module.exports = () => { // https://mths.be/emoji return /\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0065}\u{E006E}\u{E0067}|\u{E0073}\u{E0063}\u{E0074}|\u{E0077}\u{E006C}\u{E0073})\u{E007F}|\u{1F468}(?:\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}\u{1F3FB}|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FE}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u2695\u2696\u2708]\uFE0F|[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|(?:\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708])\uFE0F|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|[\u{1F3FB}-\u{1F3FF}])|(?:\u{1F9D1}\u{1F3FB}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F469})\u{1F3FB}|\u{1F9D1}(?:\u{1F3FF}\u200D\u{1F91D}\u200D\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]|\u200D\u{1F91D}\u200D\u{1F9D1})|(?:\u{1F9D1}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FF}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FE}]|(?:\u{1F9D1}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}\u{1F3FC}]|\u{1F469}(?:\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FB}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FC}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|(?:\u{1F9D1}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}-\u{1F3FD}]|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F469}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}]\uFE0F|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D6}-\u{1F9DD}](?:[\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\u{1F3F4}\u200D\u2620)\uFE0F|\u{1F469}\u200D\u{1F467}\u200D[\u{1F466}\u{1F467}]|\u{1F3F3}\uFE0F\u200D\u{1F308}|\u{1F415}\u200D\u{1F9BA}|\u{1F469}\u200D\u{1F466}|\u{1F469}\u200D\u{1F467}|\u{1F1FD}\u{1F1F0}|\u{1F1F4}\u{1F1F2}|\u{1F1F6}\u{1F1E6}|[#\*0-9]\uFE0F\u20E3|\u{1F1E7}[\u{1F1E6}\u{1F1E7}\u{1F1E9}-\u{1F1EF}\u{1F1F1}-\u{1F1F4}\u{1F1F6}-\u{1F1F9}\u{1F1FB}\u{1F1FC}\u{1F1FE}\u{1F1FF}]|\u{1F1F9}[\u{1F1E6}\u{1F1E8}\u{1F1E9}\u{1F1EB}-\u{1F1ED}\u{1F1EF}-\u{1F1F4}\u{1F1F7}\u{1F1F9}\u{1F1FB}\u{1F1FC}\u{1F1FF}]|\u{1F1EA}[\u{1F1E6}\u{1F1E8}\u{1F1EA}\u{1F1EC}\u{1F1ED}\u{1F1F7}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\u{1F574}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F936}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}-\u{1F9D5}][\u{1F3FB}-\u{1F3FF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F393}\u{1F3A0}-\u{1F3CA}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F4}\u{1F3F8}-\u{1F43E}\u{1F440}\u{1F442}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F57A}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5FB}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CC}\u{1F6D0}-\u{1F6D2}\u{1F6D5}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]|[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299\u{1F004}\u{1F0CF}\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F321}\u{1F324}-\u{1F393}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}-\u{1F3F0}\u{1F3F3}-\u{1F3F5}\u{1F3F7}-\u{1F4FD}\u{1F4FF}-\u{1F53D}\u{1F549}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F56F}\u{1F570}\u{1F573}-\u{1F57A}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F590}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CB}-\u{1F6D2}\u{1F6D5}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6EB}\u{1F6EC}\u{1F6F0}\u{1F6F3}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]\uFE0F|[\u261D\u26F9\u270A-\u270D\u{1F385}\u{1F3C2}-\u{1F3C4}\u{1F3C7}\u{1F3CA}-\u{1F3CC}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}-\u{1F478}\u{1F47C}\u{1F481}-\u{1F483}\u{1F485}-\u{1F487}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F574}\u{1F575}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F645}-\u{1F647}\u{1F64B}-\u{1F64F}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91F}\u{1F926}\u{1F930}-\u{1F939}\u{1F93C}-\u{1F93E}\u{1F9B5}\u{1F9B6}\u{1F9B8}\u{1F9B9}\u{1F9BB}\u{1F9CD}-\u{1F9CF}\u{1F9D1}-\u{1F9DD}]/gu; }; PK ~\~yallist/package.jsonnu[{ "_id": "yallist@4.0.0", "_inBundle": true, "_location": "/npm/yallist", "_phantomChildren": {}, "_requiredBy": [ "/npm/minipass-flush/minipass", "/npm/minipass-json-stream/minipass", "/npm/minipass-pipeline/minipass", "/npm/minipass-sized/minipass", "/npm/minizlib", "/npm/minizlib/minipass", "/npm/tar", "/npm/tar/fs-minipass/minipass" ], "author": { "name": "Isaac Z. Schlueter", "email": "i@izs.me", "url": "http://blog.izs.me/" }, "bugs": { "url": "https://github.com/isaacs/yallist/issues" }, "dependencies": {}, "description": "Yet Another Linked List", "devDependencies": { "tap": "^12.1.0" }, "directories": { "test": "test" }, "files": [ "yallist.js", "iterator.js" ], "homepage": "https://github.com/isaacs/yallist#readme", "license": "ISC", "main": "yallist.js", "name": "yallist", "repository": { "type": "git", "url": "git+https://github.com/isaacs/yallist.git" }, "scripts": { "postpublish": "git push origin --all; git push origin --tags", "postversion": "npm publish", "preversion": "npm test", "test": "tap test/*.js --100" }, "version": "4.0.0" } PK ~\EIz yallist/yallist.jsnu['use strict' module.exports = Yallist Yallist.Node = Node Yallist.create = Yallist function Yallist (list) { var self = this if (!(self instanceof Yallist)) { self = new Yallist() } self.tail = null self.head = null self.length = 0 if (list && typeof list.forEach === 'function') { list.forEach(function (item) { self.push(item) }) } else if (arguments.length > 0) { for (var i = 0, l = arguments.length; i < l; i++) { self.push(arguments[i]) } } return self } Yallist.prototype.removeNode = function (node) { if (node.list !== this) { throw new Error('removing node which does not belong to this list') } var next = node.next var prev = node.prev if (next) { next.prev = prev } if (prev) { prev.next = next } if (node === this.head) { this.head = next } if (node === this.tail) { this.tail = prev } node.list.length-- node.next = null node.prev = null node.list = null return next } Yallist.prototype.unshiftNode = function (node) { if (node === this.head) { return } if (node.list) { node.list.removeNode(node) } var head = this.head node.list = this node.next = head if (head) { head.prev = node } this.head = node if (!this.tail) { this.tail = node } this.length++ } Yallist.prototype.pushNode = function (node) { if (node === this.tail) { return } if (node.list) { node.list.removeNode(node) } var tail = this.tail node.list = this node.prev = tail if (tail) { tail.next = node } this.tail = node if (!this.head) { this.head = node } this.length++ } Yallist.prototype.push = function () { for (var i = 0, l = arguments.length; i < l; i++) { push(this, arguments[i]) } return this.length } Yallist.prototype.unshift = function () { for (var i = 0, l = arguments.length; i < l; i++) { unshift(this, arguments[i]) } return this.length } Yallist.prototype.pop = function () { if (!this.tail) { return undefined } var res = this.tail.value this.tail = this.tail.prev if (this.tail) { this.tail.next = null } else { this.head = null } this.length-- return res } Yallist.prototype.shift = function () { if (!this.head) { return undefined } var res = this.head.value this.head = this.head.next if (this.head) { this.head.prev = null } else { this.tail = null } this.length-- return res } Yallist.prototype.forEach = function (fn, thisp) { thisp = thisp || this for (var walker = this.head, i = 0; walker !== null; i++) { fn.call(thisp, walker.value, i, this) walker = walker.next } } Yallist.prototype.forEachReverse = function (fn, thisp) { thisp = thisp || this for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { fn.call(thisp, walker.value, i, this) walker = walker.prev } } Yallist.prototype.get = function (n) { for (var i = 0, walker = this.head; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.next } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.getReverse = function (n) { for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.prev } if (i === n && walker !== null) { return walker.value } } Yallist.prototype.map = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.head; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.next } return res } Yallist.prototype.mapReverse = function (fn, thisp) { thisp = thisp || this var res = new Yallist() for (var walker = this.tail; walker !== null;) { res.push(fn.call(thisp, walker.value, this)) walker = walker.prev } return res } Yallist.prototype.reduce = function (fn, initial) { var acc var walker = this.head if (arguments.length > 1) { acc = initial } else if (this.head) { walker = this.head.next acc = this.head.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = 0; walker !== null; i++) { acc = fn(acc, walker.value, i) walker = walker.next } return acc } Yallist.prototype.reduceReverse = function (fn, initial) { var acc var walker = this.tail if (arguments.length > 1) { acc = initial } else if (this.tail) { walker = this.tail.prev acc = this.tail.value } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = this.length - 1; walker !== null; i--) { acc = fn(acc, walker.value, i) walker = walker.prev } return acc } Yallist.prototype.toArray = function () { var arr = new Array(this.length) for (var i = 0, walker = this.head; walker !== null; i++) { arr[i] = walker.value walker = walker.next } return arr } Yallist.prototype.toArrayReverse = function () { var arr = new Array(this.length) for (var i = 0, walker = this.tail; walker !== null; i++) { arr[i] = walker.value walker = walker.prev } return arr } Yallist.prototype.slice = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = 0, walker = this.head; walker !== null && i < from; i++) { walker = walker.next } for (; walker !== null && i < to; i++, walker = walker.next) { ret.push(walker.value) } return ret } Yallist.prototype.sliceReverse = function (from, to) { to = to || this.length if (to < 0) { to += this.length } from = from || 0 if (from < 0) { from += this.length } var ret = new Yallist() if (to < from || to < 0) { return ret } if (from < 0) { from = 0 } if (to > this.length) { to = this.length } for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { walker = walker.prev } for (; walker !== null && i > from; i--, walker = walker.prev) { ret.push(walker.value) } return ret } Yallist.prototype.splice = function (start, deleteCount, ...nodes) { if (start > this.length) { start = this.length - 1 } if (start < 0) { start = this.length + start; } for (var i = 0, walker = this.head; walker !== null && i < start; i++) { walker = walker.next } var ret = [] for (var i = 0; walker && i < deleteCount; i++) { ret.push(walker.value) walker = this.removeNode(walker) } if (walker === null) { walker = this.tail } if (walker !== this.head && walker !== this.tail) { walker = walker.prev } for (var i = 0; i < nodes.length; i++) { walker = insert(this, walker, nodes[i]) } return ret; } Yallist.prototype.reverse = function () { var head = this.head var tail = this.tail for (var walker = head; walker !== null; walker = walker.prev) { var p = walker.prev walker.prev = walker.next walker.next = p } this.head = tail this.tail = head return this } function insert (self, node, value) { var inserted = node === self.head ? new Node(value, null, node, self) : new Node(value, node, node.next, self) if (inserted.next === null) { self.tail = inserted } if (inserted.prev === null) { self.head = inserted } self.length++ return inserted } function push (self, item) { self.tail = new Node(item, self.tail, null, self) if (!self.head) { self.head = self.tail } self.length++ } function unshift (self, item) { self.head = new Node(item, null, self.head, self) if (!self.tail) { self.tail = self.head } self.length++ } function Node (value, prev, next, list) { if (!(this instanceof Node)) { return new Node(value, prev, next, list) } this.list = list this.value = value if (prev) { prev.next = this this.prev = prev } else { this.prev = null } if (next) { next.prev = this this.next = next } else { this.next = null } } try { // add if support for Symbol.iterator is present require('./iterator.js')(Yallist) } catch (er) {} PK ~\aGWyallist/LICENSEnu[The ISC License Copyright (c) Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\Yלyallist/iterator.jsnu['use strict' module.exports = function (Yallist) { Yallist.prototype[Symbol.iterator] = function* () { for (let walker = this.head; walker; walker = walker.next) { yield walker.value } } } PK ~\UK: : hasown/package.jsonnu[{ "_id": "hasown@2.0.2", "_inBundle": true, "_location": "/npm/hasown", "_phantomChildren": {}, "_requiredBy": [ "/npm/is-core-module" ], "author": { "name": "Jordan Harband", "email": "ljharb@gmail.com" }, "auto-changelog": { "output": "CHANGELOG.md", "template": "keepachangelog", "unreleased": false, "commitLimit": false, "backfillLimit": false, "hideCredit": true }, "bugs": { "url": "https://github.com/inspect-js/hasOwn/issues" }, "dependencies": { "function-bind": "^1.1.2" }, "description": "A robust, ES3 compatible, \"has own property\" predicate.", "devDependencies": { "@arethetypeswrong/cli": "^0.15.1", "@ljharb/eslint-config": "^21.1.0", "@ljharb/tsconfig": "^0.2.0", "@types/function-bind": "^1.1.10", "@types/mock-property": "^1.0.2", "@types/tape": "^5.6.4", "aud": "^2.0.4", "auto-changelog": "^2.4.0", "eslint": "=8.8.0", "evalmd": "^0.0.19", "in-publish": "^2.0.1", "mock-property": "^1.0.3", "npmignore": "^0.3.1", "nyc": "^10.3.2", "safe-publish-latest": "^2.0.0", "tape": "^5.7.5", "typescript": "next" }, "engines": { "node": ">= 0.4" }, "exports": { ".": "./index.js", "./package.json": "./package.json" }, "homepage": "https://github.com/inspect-js/hasOwn#readme", "keywords": [ "has", "hasOwnProperty", "hasOwn", "has-own", "own", "has", "property", "in", "javascript", "ecmascript" ], "license": "MIT", "main": "index.js", "name": "hasown", "publishConfig": { "ignore": [ ".github/workflows", "test" ] }, "repository": { "type": "git", "url": "git+https://github.com/inspect-js/hasOwn.git" }, "scripts": { "lint": "eslint --ext=js,mjs .", "postlint": "npm run tsc", "posttest": "aud --production", "posttsc": "attw -P", "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"", "prelint": "evalmd README.md", "prepack": "npmignore --auto --commentLines=autogenerated", "prepublish": "not-in-publish || npm run prepublishOnly", "prepublishOnly": "safe-publish-latest", "pretest": "npm run lint", "test": "npm run tests-only", "tests-only": "nyc tape 'test/**/*.js'", "tsc": "tsc -p .", "version": "auto-changelog && git add CHANGELOG.md" }, "sideEffects": false, "testling": { "files": "test/index.js" }, "types": "index.d.ts", "version": "2.0.2" } PK ~\*1;;hasown/LICENSEnu[MIT License Copyright (c) Jordan Harband and contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\\\qhasown/index.jsnu['use strict'; var call = Function.prototype.call; var $hasOwn = Object.prototype.hasOwnProperty; var bind = require('function-bind'); /** @type {import('.')} */ module.exports = bind.call(call, $hasOwn); PK ~\B=EIIhasown/tsconfig.jsonnu[{ "extends": "@ljharb/tsconfig", "exclude": [ "coverage", ], } PK ~\Ƕ+wrap-ansi-cjs/package.jsonnu[{ "_args": [ [ "wrap-ansi-cjs@npm:wrap-ansi@7.0.0", "C:\\xampp\\htdocs\\emeraltd" ] ], "_from": "wrap-ansi-cjs@npm:wrap-ansi@7.0.0", "_id": "wrap-ansi-cjs@npm:wrap-ansi@7.0.0", "_inBundle": true, "_location": "/npm/wrap-ansi-cjs", "_phantomChildren": { "color-convert": "2.0.1" }, "_requested": { "type": "alias", "registry": true, "raw": "wrap-ansi-cjs@npm:wrap-ansi@7.0.0", "name": "wrap-ansi-cjs", "escapedName": "wrap-ansi-cjs", "rawSpec": "npm:wrap-ansi@7.0.0", "saveSpec": null, "fetchSpec": null, "subSpec": { "type": "version", "registry": true, "raw": "wrap-ansi@7.0.0", "name": "wrap-ansi", "escapedName": "wrap-ansi", "rawSpec": "7.0.0", "saveSpec": null, "fetchSpec": "7.0.0" } }, "_requiredBy": [], "_resolved": false, "_spec": "npm:wrap-ansi@7.0.0", "_where": "C:\\xampp\\htdocs\\emeraltd", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "bugs": { "url": "https://github.com/chalk/wrap-ansi/issues" }, "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" }, "description": "Wordwrap a string with ANSI escape codes", "devDependencies": { "ava": "^2.1.0", "chalk": "^4.0.0", "coveralls": "^3.0.3", "has-ansi": "^4.0.0", "nyc": "^15.0.1", "xo": "^0.29.1" }, "engines": { "node": ">=10" }, "files": [ "index.js" ], "funding": "https://github.com/chalk/wrap-ansi?sponsor=1", "homepage": "https://github.com/chalk/wrap-ansi#readme", "keywords": [ "wrap", "break", "wordwrap", "wordbreak", "linewrap", "ansi", "styles", "color", "colour", "colors", "terminal", "console", "cli", "string", "tty", "escape", "formatting", "rgb", "256", "shell", "xterm", "log", "logging", "command-line", "text" ], "license": "MIT", "name": "wrap-ansi-cjs", "repository": { "type": "git", "url": "git+https://github.com/chalk/wrap-ansi.git" }, "scripts": { "test": "xo && nyc ava" }, "version": "7.0.0" } PK ~\ 3wrap-ansi-cjs/node_modules/ansi-styles/package.jsonnu[{ "_args": [ [ "ansi-styles@4.3.0", "C:\\xampp\\htdocs\\emeraltd" ] ], "_from": "ansi-styles@4.3.0", "_id": "ansi-styles@4.3.0", "_inBundle": true, "_location": "/npm/wrap-ansi-cjs/ansi-styles", "_phantomChildren": {}, "_requested": { "type": "version", "registry": true, "raw": "ansi-styles@4.3.0", "name": "ansi-styles", "escapedName": "ansi-styles", "rawSpec": "4.3.0", "saveSpec": null, "fetchSpec": "4.3.0" }, "_requiredBy": [ "/npm/wrap-ansi-cjs" ], "_resolved": false, "_spec": "4.3.0", "_where": "C:\\xampp\\htdocs\\emeraltd", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "bugs": { "url": "https://github.com/chalk/ansi-styles/issues" }, "dependencies": { "color-convert": "^2.0.1" }, "description": "ANSI escape codes for styling strings in the terminal", "devDependencies": { "@types/color-convert": "^1.9.0", "ava": "^2.3.0", "svg-term-cli": "^2.1.1", "tsd": "^0.11.0", "xo": "^0.25.3" }, "engines": { "node": ">=8" }, "files": [ "index.js", "index.d.ts" ], "funding": "https://github.com/chalk/ansi-styles?sponsor=1", "homepage": "https://github.com/chalk/ansi-styles#readme", "keywords": [ "ansi", "styles", "color", "colour", "colors", "terminal", "console", "cli", "string", "tty", "escape", "formatting", "rgb", "256", "shell", "xterm", "log", "logging", "command-line", "text" ], "license": "MIT", "name": "ansi-styles", "repository": { "type": "git", "url": "git+https://github.com/chalk/ansi-styles.git" }, "scripts": { "screenshot": "svg-term --command='node screenshot' --out=screenshot.svg --padding=3 --width=55 --height=3 --at=1000 --no-cursor", "test": "xo && ava && tsd" }, "version": "4.3.0" } PK ~\/++/wrap-ansi-cjs/node_modules/ansi-styles/index.jsnu['use strict'; const wrapAnsi16 = (fn, offset) => (...args) => { const code = fn(...args); return `\u001B[${code + offset}m`; }; const wrapAnsi256 = (fn, offset) => (...args) => { const code = fn(...args); return `\u001B[${38 + offset};5;${code}m`; }; const wrapAnsi16m = (fn, offset) => (...args) => { const rgb = fn(...args); return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; }; const ansi2ansi = n => n; const rgb2rgb = (r, g, b) => [r, g, b]; const setLazyProperty = (object, property, get) => { Object.defineProperty(object, property, { get: () => { const value = get(); Object.defineProperty(object, property, { value, enumerable: true, configurable: true }); return value; }, enumerable: true, configurable: true }); }; /** @type {typeof import('color-convert')} */ let colorConvert; const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { if (colorConvert === undefined) { colorConvert = require('color-convert'); } const offset = isBackground ? 10 : 0; const styles = {}; for (const [sourceSpace, suite] of Object.entries(colorConvert)) { const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; if (sourceSpace === targetSpace) { styles[name] = wrap(identity, offset); } else if (typeof suite === 'object') { styles[name] = wrap(suite[targetSpace], offset); } } return styles; }; function assembleStyles() { const codes = new Map(); const styles = { modifier: { reset: [0, 0], // 21 isn't widely supported and 22 does the same thing bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29] }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], // Bright color blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39] }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], // Bright color bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49] } }; // Alias bright black as gray (and grey) styles.color.gray = styles.color.blackBright; styles.bgColor.bgGray = styles.bgColor.bgBlackBright; styles.color.grey = styles.color.blackBright; styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; for (const [groupName, group] of Object.entries(styles)) { for (const [styleName, style] of Object.entries(group)) { styles[styleName] = { open: `\u001B[${style[0]}m`, close: `\u001B[${style[1]}m` }; group[styleName] = styles[styleName]; codes.set(style[0], style[1]); } Object.defineProperty(styles, groupName, { value: group, enumerable: false }); } Object.defineProperty(styles, 'codes', { value: codes, enumerable: false }); styles.color.close = '\u001B[39m'; styles.bgColor.close = '\u001B[49m'; setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); return styles; } // Make the export immutable Object.defineProperty(module, 'exports', { enumerable: true, get: assembleStyles }); PK ~\E}UU.wrap-ansi-cjs/node_modules/ansi-styles/licensenu[MIT License Copyright (c) Sindre Sorhus (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\hwrap-ansi-cjs/index.jsnu['use strict'; const stringWidth = require('string-width'); const stripAnsi = require('strip-ansi'); const ansiStyles = require('ansi-styles'); const ESCAPES = new Set([ '\u001B', '\u009B' ]); const END_CODE = 39; const ANSI_ESCAPE_BELL = '\u0007'; const ANSI_CSI = '['; const ANSI_OSC = ']'; const ANSI_SGR_TERMINATOR = 'm'; const ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`; const wrapAnsi = code => `${ESCAPES.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`; const wrapAnsiHyperlink = uri => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${uri}${ANSI_ESCAPE_BELL}`; // Calculate the length of words split on ' ', ignoring // the extra characters added by ansi escape codes const wordLengths = string => string.split(' ').map(character => stringWidth(character)); // Wrap a long word across multiple rows // Ansi escape codes do not count towards length const wrapWord = (rows, word, columns) => { const characters = [...word]; let isInsideEscape = false; let isInsideLinkEscape = false; let visible = stringWidth(stripAnsi(rows[rows.length - 1])); for (const [index, character] of characters.entries()) { const characterLength = stringWidth(character); if (visible + characterLength <= columns) { rows[rows.length - 1] += character; } else { rows.push(character); visible = 0; } if (ESCAPES.has(character)) { isInsideEscape = true; isInsideLinkEscape = characters.slice(index + 1).join('').startsWith(ANSI_ESCAPE_LINK); } if (isInsideEscape) { if (isInsideLinkEscape) { if (character === ANSI_ESCAPE_BELL) { isInsideEscape = false; isInsideLinkEscape = false; } } else if (character === ANSI_SGR_TERMINATOR) { isInsideEscape = false; } continue; } visible += characterLength; if (visible === columns && index < characters.length - 1) { rows.push(''); visible = 0; } } // It's possible that the last row we copy over is only // ansi escape characters, handle this edge-case if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) { rows[rows.length - 2] += rows.pop(); } }; // Trims spaces from a string ignoring invisible sequences const stringVisibleTrimSpacesRight = string => { const words = string.split(' '); let last = words.length; while (last > 0) { if (stringWidth(words[last - 1]) > 0) { break; } last--; } if (last === words.length) { return string; } return words.slice(0, last).join(' ') + words.slice(last).join(''); }; // The wrap-ansi module can be invoked in either 'hard' or 'soft' wrap mode // // 'hard' will never allow a string to take up more than columns characters // // 'soft' allows long words to expand past the column length const exec = (string, columns, options = {}) => { if (options.trim !== false && string.trim() === '') { return ''; } let returnValue = ''; let escapeCode; let escapeUrl; const lengths = wordLengths(string); let rows = ['']; for (const [index, word] of string.split(' ').entries()) { if (options.trim !== false) { rows[rows.length - 1] = rows[rows.length - 1].trimStart(); } let rowLength = stringWidth(rows[rows.length - 1]); if (index !== 0) { if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) { // If we start with a new word but the current row length equals the length of the columns, add a new row rows.push(''); rowLength = 0; } if (rowLength > 0 || options.trim === false) { rows[rows.length - 1] += ' '; rowLength++; } } // In 'hard' wrap mode, the length of a line is never allowed to extend past 'columns' if (options.hard && lengths[index] > columns) { const remainingColumns = (columns - rowLength); const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns); const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns); if (breaksStartingNextLine < breaksStartingThisLine) { rows.push(''); } wrapWord(rows, word, columns); continue; } if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) { if (options.wordWrap === false && rowLength < columns) { wrapWord(rows, word, columns); continue; } rows.push(''); } if (rowLength + lengths[index] > columns && options.wordWrap === false) { wrapWord(rows, word, columns); continue; } rows[rows.length - 1] += word; } if (options.trim !== false) { rows = rows.map(stringVisibleTrimSpacesRight); } const pre = [...rows.join('\n')]; for (const [index, character] of pre.entries()) { returnValue += character; if (ESCAPES.has(character)) { const {groups} = new RegExp(`(?:\\${ANSI_CSI}(?\\d+)m|\\${ANSI_ESCAPE_LINK}(?.*)${ANSI_ESCAPE_BELL})`).exec(pre.slice(index).join('')) || {groups: {}}; if (groups.code !== undefined) { const code = Number.parseFloat(groups.code); escapeCode = code === END_CODE ? undefined : code; } else if (groups.uri !== undefined) { escapeUrl = groups.uri.length === 0 ? undefined : groups.uri; } } const code = ansiStyles.codes.get(Number(escapeCode)); if (pre[index + 1] === '\n') { if (escapeUrl) { returnValue += wrapAnsiHyperlink(''); } if (escapeCode && code) { returnValue += wrapAnsi(code); } } else if (character === '\n') { if (escapeCode && code) { returnValue += wrapAnsi(escapeCode); } if (escapeUrl) { returnValue += wrapAnsiHyperlink(escapeUrl); } } } return returnValue; }; // For each newline, invoke the method separately module.exports = (string, columns, options) => { return String(string) .normalize() .replace(/\r\n/g, '\n') .split('\n') .map(line => exec(line, columns, options)) .join('\n'); }; PK ~\i]]wrap-ansi-cjs/licensenu[MIT License Copyright (c) Sindre Sorhus (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\:jsupports-color/package.jsonnu[{ "_id": "supports-color@9.4.0", "_inBundle": true, "_location": "/npm/supports-color", "_phantomChildren": {}, "_requiredBy": [ "/npm" ], "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "bugs": { "url": "https://github.com/chalk/supports-color/issues" }, "description": "Detect whether a terminal supports color", "devDependencies": { "@types/node": "^20.3.2", "ava": "^5.3.1", "import-fresh": "^3.3.0", "tsd": "^0.18.0", "xo": "^0.54.2" }, "engines": { "node": ">=12" }, "exports": { "node": "./index.js", "default": "./browser.js" }, "files": [ "index.js", "index.d.ts", "browser.js", "browser.d.ts" ], "funding": "https://github.com/chalk/supports-color?sponsor=1", "homepage": "https://github.com/chalk/supports-color#readme", "keywords": [ "color", "colour", "colors", "terminal", "console", "cli", "ansi", "styles", "tty", "rgb", "256", "shell", "xterm", "command-line", "support", "supports", "capability", "detect", "truecolor", "16m" ], "license": "MIT", "name": "supports-color", "repository": { "type": "git", "url": "git+https://github.com/chalk/supports-color.git" }, "scripts": { "//test": "xo && ava && tsd", "test": "tsd" }, "type": "module", "version": "9.4.0" } PK ~\&supports-color/index.jsnu[import process from 'node:process'; import os from 'node:os'; import tty from 'node:tty'; // From: https://github.com/sindresorhus/has-flag/blob/main/index.js /// function hasFlag(flag, argv = globalThis.Deno?.args ?? process.argv) { function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process.argv) { const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); const position = argv.indexOf(prefix + flag); const terminatorPosition = argv.indexOf('--'); return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); } const {env} = process; let flagForceColor; if ( hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false') || hasFlag('color=never') ) { flagForceColor = 0; } else if ( hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always') ) { flagForceColor = 1; } function envForceColor() { if ('FORCE_COLOR' in env) { if (env.FORCE_COLOR === 'true') { return 1; } if (env.FORCE_COLOR === 'false') { return 0; } return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3); } } function translateLevel(level) { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3, }; } function _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) { const noFlagForceColor = envForceColor(); if (noFlagForceColor !== undefined) { flagForceColor = noFlagForceColor; } const forceColor = sniffFlags ? flagForceColor : noFlagForceColor; if (forceColor === 0) { return 0; } if (sniffFlags) { if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) { return 3; } if (hasFlag('color=256')) { return 2; } } // Check for Azure DevOps pipelines. // Has to be above the `!streamIsTTY` check. if ('TF_BUILD' in env && 'AGENT_NAME' in env) { return 1; } if (haveStream && !streamIsTTY && forceColor === undefined) { return 0; } const min = forceColor || 0; if (env.TERM === 'dumb') { return min; } if (process.platform === 'win32') { // Windows 10 build 10586 is the first Windows release that supports 256 colors. // Windows 10 build 14931 is the first release that supports 16m/TrueColor. const osRelease = os.release().split('.'); if ( Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10_586 ) { return Number(osRelease[2]) >= 14_931 ? 3 : 2; } return 1; } if ('CI' in env) { if ('GITHUB_ACTIONS' in env || 'GITEA_ACTIONS' in env) { return 3; } if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'BUILDKITE', 'DRONE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { return 1; } return min; } if ('TEAMCITY_VERSION' in env) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; } if (env.COLORTERM === 'truecolor') { return 3; } if (env.TERM === 'xterm-kitty') { return 3; } if ('TERM_PROGRAM' in env) { const version = Number.parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); switch (env.TERM_PROGRAM) { case 'iTerm.app': { return version >= 3 ? 3 : 2; } case 'Apple_Terminal': { return 2; } // No default } } if (/-256(color)?$/i.test(env.TERM)) { return 2; } if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { return 1; } if ('COLORTERM' in env) { return 1; } return min; } export function createSupportsColor(stream, options = {}) { const level = _supportsColor(stream, { streamIsTTY: stream && stream.isTTY, ...options, }); return translateLevel(level); } const supportsColor = { stdout: createSupportsColor({isTTY: tty.isatty(1)}), stderr: createSupportsColor({isTTY: tty.isatty(2)}), }; export default supportsColor; PK ~\i]]supports-color/licensenu[MIT License Copyright (c) Sindre Sorhus (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\V˰j  supports-color/browser.jsnu[/* eslint-env browser */ const level = (() => { if (navigator.userAgentData) { const brand = navigator.userAgentData.brands.find(({brand}) => brand === 'Chromium'); if (brand?.version > 93) { return 3; } } if (/\b(Chrome|Chromium)\//.test(navigator.userAgent)) { return 1; } return 0; })(); const colorSupport = level !== 0 && { level, hasBasic: true, has256: level >= 2, has16m: level >= 3, }; const supportsColor = { stdout: colorSupport, stderr: colorSupport, }; export default supportsColor; PK ~\*fs-minipass/package.jsonnu[{ "_id": "fs-minipass@3.0.3", "_inBundle": true, "_location": "/npm/fs-minipass", "_phantomChildren": {}, "_requiredBy": [ "/npm", "/npm/cacache", "/npm/pacote" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/fs-minipass/issues" }, "dependencies": { "minipass": "^7.0.3" }, "description": "fs read and write streams based on minipass", "devDependencies": { "@npmcli/eslint-config": "^4.0.1", "@npmcli/template-oss": "4.18.0", "mutate-fs": "^2.1.1", "tap": "^16.3.2" }, "engines": { "node": "^14.17.0 || ^16.13.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/fs-minipass#readme", "keywords": [], "license": "ISC", "main": "lib/index.js", "name": "fs-minipass", "repository": { "type": "git", "url": "git+https://github.com/npm/fs-minipass.git" }, "scripts": { "lint": "eslint \"**/*.js\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "check-coverage": true, "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.18.0", "publish": "true" }, "version": "3.0.3" } PK ~\w1&&fs-minipass/lib/index.jsnu['use strict' const { Minipass } = require('minipass') const EE = require('events').EventEmitter const fs = require('fs') const writev = fs.writev const _autoClose = Symbol('_autoClose') const _close = Symbol('_close') const _ended = Symbol('_ended') const _fd = Symbol('_fd') const _finished = Symbol('_finished') const _flags = Symbol('_flags') const _flush = Symbol('_flush') const _handleChunk = Symbol('_handleChunk') const _makeBuf = Symbol('_makeBuf') const _mode = Symbol('_mode') const _needDrain = Symbol('_needDrain') const _onerror = Symbol('_onerror') const _onopen = Symbol('_onopen') const _onread = Symbol('_onread') const _onwrite = Symbol('_onwrite') const _open = Symbol('_open') const _path = Symbol('_path') const _pos = Symbol('_pos') const _queue = Symbol('_queue') const _read = Symbol('_read') const _readSize = Symbol('_readSize') const _reading = Symbol('_reading') const _remain = Symbol('_remain') const _size = Symbol('_size') const _write = Symbol('_write') const _writing = Symbol('_writing') const _defaultFlag = Symbol('_defaultFlag') const _errored = Symbol('_errored') class ReadStream extends Minipass { constructor (path, opt) { opt = opt || {} super(opt) this.readable = true this.writable = false if (typeof path !== 'string') { throw new TypeError('path must be a string') } this[_errored] = false this[_fd] = typeof opt.fd === 'number' ? opt.fd : null this[_path] = path this[_readSize] = opt.readSize || 16 * 1024 * 1024 this[_reading] = false this[_size] = typeof opt.size === 'number' ? opt.size : Infinity this[_remain] = this[_size] this[_autoClose] = typeof opt.autoClose === 'boolean' ? opt.autoClose : true if (typeof this[_fd] === 'number') { this[_read]() } else { this[_open]() } } get fd () { return this[_fd] } get path () { return this[_path] } write () { throw new TypeError('this is a readable stream') } end () { throw new TypeError('this is a readable stream') } [_open] () { fs.open(this[_path], 'r', (er, fd) => this[_onopen](er, fd)) } [_onopen] (er, fd) { if (er) { this[_onerror](er) } else { this[_fd] = fd this.emit('open', fd) this[_read]() } } [_makeBuf] () { return Buffer.allocUnsafe(Math.min(this[_readSize], this[_remain])) } [_read] () { if (!this[_reading]) { this[_reading] = true const buf = this[_makeBuf]() /* istanbul ignore if */ if (buf.length === 0) { return process.nextTick(() => this[_onread](null, 0, buf)) } fs.read(this[_fd], buf, 0, buf.length, null, (er, br, b) => this[_onread](er, br, b)) } } [_onread] (er, br, buf) { this[_reading] = false if (er) { this[_onerror](er) } else if (this[_handleChunk](br, buf)) { this[_read]() } } [_close] () { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd] this[_fd] = null fs.close(fd, er => er ? this.emit('error', er) : this.emit('close')) } } [_onerror] (er) { this[_reading] = true this[_close]() this.emit('error', er) } [_handleChunk] (br, buf) { let ret = false // no effect if infinite this[_remain] -= br if (br > 0) { ret = super.write(br < buf.length ? buf.slice(0, br) : buf) } if (br === 0 || this[_remain] <= 0) { ret = false this[_close]() super.end() } return ret } emit (ev, data) { switch (ev) { case 'prefinish': case 'finish': break case 'drain': if (typeof this[_fd] === 'number') { this[_read]() } break case 'error': if (this[_errored]) { return } this[_errored] = true return super.emit(ev, data) default: return super.emit(ev, data) } } } class ReadStreamSync extends ReadStream { [_open] () { let threw = true try { this[_onopen](null, fs.openSync(this[_path], 'r')) threw = false } finally { if (threw) { this[_close]() } } } [_read] () { let threw = true try { if (!this[_reading]) { this[_reading] = true do { const buf = this[_makeBuf]() /* istanbul ignore next */ const br = buf.length === 0 ? 0 : fs.readSync(this[_fd], buf, 0, buf.length, null) if (!this[_handleChunk](br, buf)) { break } } while (true) this[_reading] = false } threw = false } finally { if (threw) { this[_close]() } } } [_close] () { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd] this[_fd] = null fs.closeSync(fd) this.emit('close') } } } class WriteStream extends EE { constructor (path, opt) { opt = opt || {} super(opt) this.readable = false this.writable = true this[_errored] = false this[_writing] = false this[_ended] = false this[_needDrain] = false this[_queue] = [] this[_path] = path this[_fd] = typeof opt.fd === 'number' ? opt.fd : null this[_mode] = opt.mode === undefined ? 0o666 : opt.mode this[_pos] = typeof opt.start === 'number' ? opt.start : null this[_autoClose] = typeof opt.autoClose === 'boolean' ? opt.autoClose : true // truncating makes no sense when writing into the middle const defaultFlag = this[_pos] !== null ? 'r+' : 'w' this[_defaultFlag] = opt.flags === undefined this[_flags] = this[_defaultFlag] ? defaultFlag : opt.flags if (this[_fd] === null) { this[_open]() } } emit (ev, data) { if (ev === 'error') { if (this[_errored]) { return } this[_errored] = true } return super.emit(ev, data) } get fd () { return this[_fd] } get path () { return this[_path] } [_onerror] (er) { this[_close]() this[_writing] = true this.emit('error', er) } [_open] () { fs.open(this[_path], this[_flags], this[_mode], (er, fd) => this[_onopen](er, fd)) } [_onopen] (er, fd) { if (this[_defaultFlag] && this[_flags] === 'r+' && er && er.code === 'ENOENT') { this[_flags] = 'w' this[_open]() } else if (er) { this[_onerror](er) } else { this[_fd] = fd this.emit('open', fd) if (!this[_writing]) { this[_flush]() } } } end (buf, enc) { if (buf) { this.write(buf, enc) } this[_ended] = true // synthetic after-write logic, where drain/finish live if (!this[_writing] && !this[_queue].length && typeof this[_fd] === 'number') { this[_onwrite](null, 0) } return this } write (buf, enc) { if (typeof buf === 'string') { buf = Buffer.from(buf, enc) } if (this[_ended]) { this.emit('error', new Error('write() after end()')) return false } if (this[_fd] === null || this[_writing] || this[_queue].length) { this[_queue].push(buf) this[_needDrain] = true return false } this[_writing] = true this[_write](buf) return true } [_write] (buf) { fs.write(this[_fd], buf, 0, buf.length, this[_pos], (er, bw) => this[_onwrite](er, bw)) } [_onwrite] (er, bw) { if (er) { this[_onerror](er) } else { if (this[_pos] !== null) { this[_pos] += bw } if (this[_queue].length) { this[_flush]() } else { this[_writing] = false if (this[_ended] && !this[_finished]) { this[_finished] = true this[_close]() this.emit('finish') } else if (this[_needDrain]) { this[_needDrain] = false this.emit('drain') } } } } [_flush] () { if (this[_queue].length === 0) { if (this[_ended]) { this[_onwrite](null, 0) } } else if (this[_queue].length === 1) { this[_write](this[_queue].pop()) } else { const iovec = this[_queue] this[_queue] = [] writev(this[_fd], iovec, this[_pos], (er, bw) => this[_onwrite](er, bw)) } } [_close] () { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd] this[_fd] = null fs.close(fd, er => er ? this.emit('error', er) : this.emit('close')) } } } class WriteStreamSync extends WriteStream { [_open] () { let fd // only wrap in a try{} block if we know we'll retry, to avoid // the rethrow obscuring the error's source frame in most cases. if (this[_defaultFlag] && this[_flags] === 'r+') { try { fd = fs.openSync(this[_path], this[_flags], this[_mode]) } catch (er) { if (er.code === 'ENOENT') { this[_flags] = 'w' return this[_open]() } else { throw er } } } else { fd = fs.openSync(this[_path], this[_flags], this[_mode]) } this[_onopen](null, fd) } [_close] () { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd] this[_fd] = null fs.closeSync(fd) this.emit('close') } } [_write] (buf) { // throw the original, but try to close if it fails let threw = true try { this[_onwrite](null, fs.writeSync(this[_fd], buf, 0, buf.length, this[_pos])) threw = false } finally { if (threw) { try { this[_close]() } catch { // ok error } } } } } exports.ReadStream = ReadStream exports.ReadStreamSync = ReadStreamSync exports.WriteStream = WriteStream exports.WriteStreamSync = WriteStreamSync PK ~\aGWfs-minipass/LICENSEnu[The ISC License Copyright (c) Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\.2RRmkdirp/package.jsonnu[{ "_id": "mkdirp@1.0.4", "_inBundle": true, "_location": "/npm/mkdirp", "_phantomChildren": {}, "_requiredBy": [ "/npm/tar" ], "bin": { "mkdirp": "bin/cmd.js" }, "bugs": { "url": "https://github.com/isaacs/node-mkdirp/issues" }, "description": "Recursively mkdir, like `mkdir -p`", "devDependencies": { "require-inject": "^1.4.4", "tap": "^14.10.7" }, "engines": { "node": ">=10" }, "files": [ "bin", "lib", "index.js" ], "homepage": "https://github.com/isaacs/node-mkdirp#readme", "keywords": [ "mkdir", "directory", "make dir", "make", "dir", "recursive", "native" ], "license": "MIT", "main": "index.js", "name": "mkdirp", "repository": { "type": "git", "url": "git+https://github.com/isaacs/node-mkdirp.git" }, "scripts": { "postpublish": "git push origin --follow-tags", "postversion": "npm publish", "preversion": "npm test", "snap": "tap", "test": "tap" }, "tap": { "check-coverage": true, "coverage-map": "map.js" }, "version": "1.0.4" } PK ~\Q;!;!mkdirp/readme.markdownnu[# mkdirp Like `mkdir -p`, but in Node.js! Now with a modern API and no\* bugs! \* may contain some bugs # example ## pow.js ```js const mkdirp = require('mkdirp') // return value is a Promise resolving to the first directory created mkdirp('/tmp/foo/bar/baz').then(made => console.log(`made directories, starting with ${made}`)) ``` Output (where `/tmp/foo` already exists) ``` made directories, starting with /tmp/foo/bar ``` Or, if you don't have time to wait around for promises: ```js const mkdirp = require('mkdirp') // return value is the first directory created const made = mkdirp.sync('/tmp/foo/bar/baz') console.log(`made directories, starting with ${made}`) ``` And now /tmp/foo/bar/baz exists, huzzah! # methods ```js const mkdirp = require('mkdirp') ``` ## mkdirp(dir, [opts]) -> Promise Create a new directory and any necessary subdirectories at `dir` with octal permission string `opts.mode`. If `opts` is a string or number, it will be treated as the `opts.mode`. If `opts.mode` isn't specified, it defaults to `0o777 & (~process.umask())`. Promise resolves to first directory `made` that had to be created, or `undefined` if everything already exists. Promise rejects if any errors are encountered. Note that, in the case of promise rejection, some directories _may_ have been created, as recursive directory creation is not an atomic operation. You can optionally pass in an alternate `fs` implementation by passing in `opts.fs`. Your implementation should have `opts.fs.mkdir(path, opts, cb)` and `opts.fs.stat(path, cb)`. You can also override just one or the other of `mkdir` and `stat` by passing in `opts.stat` or `opts.mkdir`, or providing an `fs` option that only overrides one of these. ## mkdirp.sync(dir, opts) -> String|null Synchronously create a new directory and any necessary subdirectories at `dir` with octal permission string `opts.mode`. If `opts` is a string or number, it will be treated as the `opts.mode`. If `opts.mode` isn't specified, it defaults to `0o777 & (~process.umask())`. Returns the first directory that had to be created, or undefined if everything already exists. You can optionally pass in an alternate `fs` implementation by passing in `opts.fs`. Your implementation should have `opts.fs.mkdirSync(path, mode)` and `opts.fs.statSync(path)`. You can also override just one or the other of `mkdirSync` and `statSync` by passing in `opts.statSync` or `opts.mkdirSync`, or providing an `fs` option that only overrides one of these. ## mkdirp.manual, mkdirp.manualSync Use the manual implementation (not the native one). This is the default when the native implementation is not available or the stat/mkdir implementation is overridden. ## mkdirp.native, mkdirp.nativeSync Use the native implementation (not the manual one). This is the default when the native implementation is available and stat/mkdir are not overridden. # implementation On Node.js v10.12.0 and above, use the native `fs.mkdir(p, {recursive:true})` option, unless `fs.mkdir`/`fs.mkdirSync` has been overridden by an option. ## native implementation - If the path is a root directory, then pass it to the underlying implementation and return the result/error. (In this case, it'll either succeed or fail, but we aren't actually creating any dirs.) - Walk up the path statting each directory, to find the first path that will be created, `made`. - Call `fs.mkdir(path, { recursive: true })` (or `fs.mkdirSync`) - If error, raise it to the caller. - Return `made`. ## manual implementation - Call underlying `fs.mkdir` implementation, with `recursive: false` - If error: - If path is a root directory, raise to the caller and do not handle it - If ENOENT, mkdirp parent dir, store result as `made` - stat(path) - If error, raise original `mkdir` error - If directory, return `made` - Else, raise original `mkdir` error - else - return `undefined` if a root dir, or `made` if set, or `path` ## windows vs unix caveat On Windows file systems, attempts to create a root directory (ie, a drive letter or root UNC path) will fail. If the root directory exists, then it will fail with `EPERM`. If the root directory does not exist, then it will fail with `ENOENT`. On posix file systems, attempts to create a root directory (in recursive mode) will succeed silently, as it is treated like just another directory that already exists. (In non-recursive mode, of course, it fails with `EEXIST`.) In order to preserve this system-specific behavior (and because it's not as if we can create the parent of a root directory anyway), attempts to create a root directory are passed directly to the `fs` implementation, and any errors encountered are not handled. ## native error caveat The native implementation (as of at least Node.js v13.4.0) does not provide appropriate errors in some cases (see [nodejs/node#31481](https://github.com/nodejs/node/issues/31481) and [nodejs/node#28015](https://github.com/nodejs/node/issues/28015)). In order to work around this issue, the native implementation will fall back to the manual implementation if an `ENOENT` error is encountered. # choosing a recursive mkdir implementation There are a few to choose from! Use the one that suits your needs best :D ## use `fs.mkdir(path, {recursive: true}, cb)` if: - You wish to optimize performance even at the expense of other factors. - You don't need to know the first dir created. - You are ok with getting `ENOENT` as the error when some other problem is the actual cause. - You can limit your platforms to Node.js v10.12 and above. - You're ok with using callbacks instead of promises. - You don't need/want a CLI. - You don't need to override the `fs` methods in use. ## use this module (mkdirp 1.x) if: - You need to know the first directory that was created. - You wish to use the native implementation if available, but fall back when it's not. - You prefer promise-returning APIs to callback-taking APIs. - You want more useful error messages than the native recursive mkdir provides (at least as of Node.js v13.4), and are ok with re-trying on `ENOENT` to achieve this. - You need (or at least, are ok with) a CLI. - You need to override the `fs` methods in use. ## use [`make-dir`](http://npm.im/make-dir) if: - You do not need to know the first dir created (and wish to save a few `stat` calls when using the native implementation for this reason). - You wish to use the native implementation if available, but fall back when it's not. - You prefer promise-returning APIs to callback-taking APIs. - You are ok with occasionally getting `ENOENT` errors for failures that are actually related to something other than a missing file system entry. - You don't need/want a CLI. - You need to override the `fs` methods in use. ## use mkdirp 0.x if: - You need to know the first directory that was created. - You need (or at least, are ok with) a CLI. - You need to override the `fs` methods in use. - You're ok with using callbacks instead of promises. - You are not running on Windows, where the root-level ENOENT errors can lead to infinite regress. - You think vinyl just sounds warmer and richer for some weird reason. - You are supporting truly ancient Node.js versions, before even the advent of a `Promise` language primitive. (Please don't. You deserve better.) # cli This package also ships with a `mkdirp` command. ``` $ mkdirp -h usage: mkdirp [DIR1,DIR2..] {OPTIONS} Create each supplied directory including any necessary parent directories that don't yet exist. If the directory already exists, do nothing. OPTIONS are: -m If a directory needs to be created, set the mode as an octal --mode= permission string. -v --version Print the mkdirp version number -h --help Print this helpful banner -p --print Print the first directories created for each path provided --manual Use manual implementation, even if native is available ``` # install With [npm](http://npmjs.org) do: ``` npm install mkdirp ``` to get the library locally, or ``` npm install -g mkdirp ``` to get the command everywhere, or ``` npx mkdirp ... ``` to run the command without installing it globally. # platform support This module works on node v8, but only v10 and above are officially supported, as Node v8 reached its LTS end of life 2020-01-01, which is in the past, as of this writing. # license MIT PK ~\+ mkdirp/lib/find-made.jsnu[const {dirname} = require('path') const findMade = (opts, parent, path = undefined) => { // we never want the 'made' return value to be a root directory if (path === parent) return Promise.resolve() return opts.statAsync(parent).then( st => st.isDirectory() ? path : undefined, // will fail later er => er.code === 'ENOENT' ? findMade(opts, dirname(parent), parent) : undefined ) } const findMadeSync = (opts, parent, path = undefined) => { if (path === parent) return undefined try { return opts.statSync(parent).isDirectory() ? path : undefined } catch (er) { return er.code === 'ENOENT' ? findMadeSync(opts, dirname(parent), parent) : undefined } } module.exports = {findMade, findMadeSync} PK ~\|4mkdirp/lib/opts-arg.jsnu[const { promisify } = require('util') const fs = require('fs') const optsArg = opts => { if (!opts) opts = { mode: 0o777, fs } else if (typeof opts === 'object') opts = { mode: 0o777, fs, ...opts } else if (typeof opts === 'number') opts = { mode: opts, fs } else if (typeof opts === 'string') opts = { mode: parseInt(opts, 8), fs } else throw new TypeError('invalid options argument') opts.mkdir = opts.mkdir || opts.fs.mkdir || fs.mkdir opts.mkdirAsync = promisify(opts.mkdir) opts.stat = opts.stat || opts.fs.stat || fs.stat opts.statAsync = promisify(opts.stat) opts.statSync = opts.statSync || opts.fs.statSync || fs.statSync opts.mkdirSync = opts.mkdirSync || opts.fs.mkdirSync || fs.mkdirSync return opts } module.exports = optsArg PK ~\9iJJmkdirp/lib/mkdirp-manual.jsnu[const {dirname} = require('path') const mkdirpManual = (path, opts, made) => { opts.recursive = false const parent = dirname(path) if (parent === path) { return opts.mkdirAsync(path, opts).catch(er => { // swallowed by recursive implementation on posix systems // any other error is a failure if (er.code !== 'EISDIR') throw er }) } return opts.mkdirAsync(path, opts).then(() => made || path, er => { if (er.code === 'ENOENT') return mkdirpManual(parent, opts) .then(made => mkdirpManual(path, opts, made)) if (er.code !== 'EEXIST' && er.code !== 'EROFS') throw er return opts.statAsync(path).then(st => { if (st.isDirectory()) return made else throw er }, () => { throw er }) }) } const mkdirpManualSync = (path, opts, made) => { const parent = dirname(path) opts.recursive = false if (parent === path) { try { return opts.mkdirSync(path, opts) } catch (er) { // swallowed by recursive implementation on posix systems // any other error is a failure if (er.code !== 'EISDIR') throw er else return } } try { opts.mkdirSync(path, opts) return made || path } catch (er) { if (er.code === 'ENOENT') return mkdirpManualSync(path, opts, mkdirpManualSync(parent, opts, made)) if (er.code !== 'EEXIST' && er.code !== 'EROFS') throw er try { if (!opts.statSync(path).isDirectory()) throw er } catch (_) { throw er } } } module.exports = {mkdirpManual, mkdirpManualSync} PK ~\1Dmkdirp/lib/use-native.jsnu[const fs = require('fs') const version = process.env.__TESTING_MKDIRP_NODE_VERSION__ || process.version const versArr = version.replace(/^v/, '').split('.') const hasNative = +versArr[0] > 10 || +versArr[0] === 10 && +versArr[1] >= 12 const useNative = !hasNative ? () => false : opts => opts.mkdir === fs.mkdir const useNativeSync = !hasNative ? () => false : opts => opts.mkdirSync === fs.mkdirSync module.exports = {useNative, useNativeSync} PK ~\mkdirp/lib/path-arg.jsnu[const platform = process.env.__TESTING_MKDIRP_PLATFORM__ || process.platform const { resolve, parse } = require('path') const pathArg = path => { if (/\0/.test(path)) { // simulate same failure that node raises throw Object.assign( new TypeError('path must be a string without null bytes'), { path, code: 'ERR_INVALID_ARG_VALUE', } ) } path = resolve(path) if (platform === 'win32') { const badWinChars = /[*|"<>?:]/ const {root} = parse(path) if (badWinChars.test(path.substr(root.length))) { throw Object.assign(new Error('Illegal characters in path.'), { path, code: 'EINVAL', }) } } return path } module.exports = pathArg PK ~\RZmkdirp/lib/mkdirp-native.jsnu[const {dirname} = require('path') const {findMade, findMadeSync} = require('./find-made.js') const {mkdirpManual, mkdirpManualSync} = require('./mkdirp-manual.js') const mkdirpNative = (path, opts) => { opts.recursive = true const parent = dirname(path) if (parent === path) return opts.mkdirAsync(path, opts) return findMade(opts, path).then(made => opts.mkdirAsync(path, opts).then(() => made) .catch(er => { if (er.code === 'ENOENT') return mkdirpManual(path, opts) else throw er })) } const mkdirpNativeSync = (path, opts) => { opts.recursive = true const parent = dirname(path) if (parent === path) return opts.mkdirSync(path, opts) const made = findMadeSync(opts, path) try { opts.mkdirSync(path, opts) return made } catch (er) { if (er.code === 'ENOENT') return mkdirpManualSync(path, opts) else throw er } } module.exports = {mkdirpNative, mkdirpNativeSync} PK ~\0mkdirp/LICENSEnu[Copyright James Halliday (mail@substack.net) and Isaac Z. Schlueter (i@izs.me) This project is free software released under the MIT license: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\E}9qmkdirp/index.jsnu[const optsArg = require('./lib/opts-arg.js') const pathArg = require('./lib/path-arg.js') const {mkdirpNative, mkdirpNativeSync} = require('./lib/mkdirp-native.js') const {mkdirpManual, mkdirpManualSync} = require('./lib/mkdirp-manual.js') const {useNative, useNativeSync} = require('./lib/use-native.js') const mkdirp = (path, opts) => { path = pathArg(path) opts = optsArg(opts) return useNative(opts) ? mkdirpNative(path, opts) : mkdirpManual(path, opts) } const mkdirpSync = (path, opts) => { path = pathArg(path) opts = optsArg(opts) return useNativeSync(opts) ? mkdirpNativeSync(path, opts) : mkdirpManualSync(path, opts) } mkdirp.sync = mkdirpSync mkdirp.native = (path, opts) => mkdirpNative(pathArg(path), optsArg(opts)) mkdirp.manual = (path, opts) => mkdirpManual(pathArg(path), optsArg(opts)) mkdirp.nativeSync = (path, opts) => mkdirpNativeSync(pathArg(path), optsArg(opts)) mkdirp.manualSync = (path, opts) => mkdirpManualSync(pathArg(path), optsArg(opts)) module.exports = mkdirp PK ~\}&&mkdirp/bin/cmd.jsnu[#!/usr/bin/env node const usage = () => ` usage: mkdirp [DIR1,DIR2..] {OPTIONS} Create each supplied directory including any necessary parent directories that don't yet exist. If the directory already exists, do nothing. OPTIONS are: -m If a directory needs to be created, set the mode as an octal --mode= permission string. -v --version Print the mkdirp version number -h --help Print this helpful banner -p --print Print the first directories created for each path provided --manual Use manual implementation, even if native is available ` const dirs = [] const opts = {} let print = false let dashdash = false let manual = false for (const arg of process.argv.slice(2)) { if (dashdash) dirs.push(arg) else if (arg === '--') dashdash = true else if (arg === '--manual') manual = true else if (/^-h/.test(arg) || /^--help/.test(arg)) { console.log(usage()) process.exit(0) } else if (arg === '-v' || arg === '--version') { console.log(require('../package.json').version) process.exit(0) } else if (arg === '-p' || arg === '--print') { print = true } else if (/^-m/.test(arg) || /^--mode=/.test(arg)) { const mode = parseInt(arg.replace(/^(-m|--mode=)/, ''), 8) if (isNaN(mode)) { console.error(`invalid mode argument: ${arg}\nMust be an octal number.`) process.exit(1) } opts.mode = mode } else dirs.push(arg) } const mkdirp = require('../') const impl = manual ? mkdirp.manual : mkdirp if (dirs.length === 0) console.error(usage()) Promise.all(dirs.map(dir => impl(dir, opts))) .then(made => print ? made.forEach(m => m && console.log(m)) : null) .catch(er => { console.error(er.message) if (er.code) console.error(' code: ' + er.code) process.exit(1) }) PK ~\23abbrev/package.jsonnu[{ "_id": "abbrev@2.0.0", "_inBundle": true, "_location": "/npm/abbrev", "_phantomChildren": {}, "_requiredBy": [ "/npm", "/npm/nopt" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/abbrev-js/issues" }, "description": "Like ruby's abbrev module, but in js", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.8.0", "tap": "^16.3.0" }, "engines": { "node": "^14.17.0 || ^16.13.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/abbrev-js#readme", "license": "ISC", "main": "lib/index.js", "name": "abbrev", "repository": { "type": "git", "url": "git+https://github.com/npm/abbrev-js.git" }, "scripts": { "lint": "eslint \"**/*.js\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.8.0" }, "version": "2.0.0" } PK ~\Gv##abbrev/lib/index.jsnu[module.exports = abbrev function abbrev (...args) { let list = args.length === 1 || Array.isArray(args[0]) ? args[0] : args for (let i = 0, l = list.length; i < l; i++) { list[i] = typeof list[i] === 'string' ? list[i] : String(list[i]) } // sort them lexicographically, so that they're next to their nearest kin list = list.sort(lexSort) // walk through each, seeing how much it has in common with the next and previous const abbrevs = {} let prev = '' for (let ii = 0, ll = list.length; ii < ll; ii++) { const current = list[ii] const next = list[ii + 1] || '' let nextMatches = true let prevMatches = true if (current === next) { continue } let j = 0 const cl = current.length for (; j < cl; j++) { const curChar = current.charAt(j) nextMatches = nextMatches && curChar === next.charAt(j) prevMatches = prevMatches && curChar === prev.charAt(j) if (!nextMatches && !prevMatches) { j++ break } } prev = current if (j === cl) { abbrevs[current] = current continue } for (let a = current.slice(0, j); j <= cl; j++) { abbrevs[a] = current a += current.charAt(j) } } return abbrevs } function lexSort (a, b) { return a === b ? 0 : a > b ? 1 : -1 } PK ~\2Babbrev/LICENSEnu[This software is dual-licensed under the ISC and MIT licenses. You may use this software under EITHER of the following licenses. ---------- The ISC License Copyright (c) Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ---------- Copyright Isaac Z. Schlueter and Contributors All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\ ꣪string-width-cjs/package.jsonnu[{ "_args": [ [ "string-width-cjs@npm:string-width@4.2.3", "C:\\xampp\\htdocs\\emeraltd" ] ], "_from": "string-width-cjs@npm:string-width@4.2.3", "_id": "string-width-cjs@npm:string-width@4.2.3", "_inBundle": true, "_location": "/npm/string-width-cjs", "_phantomChildren": {}, "_requested": { "type": "alias", "registry": true, "raw": "string-width-cjs@npm:string-width@4.2.3", "name": "string-width-cjs", "escapedName": "string-width-cjs", "rawSpec": "npm:string-width@4.2.3", "saveSpec": null, "fetchSpec": null, "subSpec": { "type": "version", "registry": true, "raw": "string-width@4.2.3", "name": "string-width", "escapedName": "string-width", "rawSpec": "4.2.3", "saveSpec": null, "fetchSpec": "4.2.3" } }, "_requiredBy": [], "_resolved": false, "_spec": "npm:string-width@4.2.3", "_where": "C:\\xampp\\htdocs\\emeraltd", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "bugs": { "url": "https://github.com/sindresorhus/string-width/issues" }, "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" }, "description": "Get the visual width of a string - the number of columns required to display it", "devDependencies": { "ava": "^1.4.1", "tsd": "^0.7.1", "xo": "^0.24.0" }, "engines": { "node": ">=8" }, "files": [ "index.js", "index.d.ts" ], "homepage": "https://github.com/sindresorhus/string-width#readme", "keywords": [ "string", "character", "unicode", "width", "visual", "column", "columns", "fullwidth", "full-width", "full", "ansi", "escape", "codes", "cli", "command-line", "terminal", "console", "cjk", "chinese", "japanese", "korean", "fixed-width" ], "license": "MIT", "name": "string-width-cjs", "repository": { "type": "git", "url": "git+https://github.com/sindresorhus/string-width.git" }, "scripts": { "test": "xo && ava && tsd" }, "version": "4.2.3" } PK ~\Ikstring-width-cjs/index.jsnu['use strict'; const stripAnsi = require('strip-ansi'); const isFullwidthCodePoint = require('is-fullwidth-code-point'); const emojiRegex = require('emoji-regex'); const stringWidth = string => { if (typeof string !== 'string' || string.length === 0) { return 0; } string = stripAnsi(string); if (string.length === 0) { return 0; } string = string.replace(emojiRegex(), ' '); let width = 0; for (let i = 0; i < string.length; i++) { const code = string.codePointAt(i); // Ignore control characters if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { continue; } // Ignore combining characters if (code >= 0x300 && code <= 0x36F) { continue; } // Surrogates if (code > 0xFFFF) { i++; } width += isFullwidthCodePoint(code) ? 2 : 1; } return width; }; module.exports = stringWidth; // TODO: remove this in the next major version module.exports.default = stringWidth; PK ~\E}UUstring-width-cjs/licensenu[MIT License Copyright (c) Sindre Sorhus (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\8^indent-string/package.jsonnu[{ "_id": "indent-string@4.0.0", "_inBundle": true, "_location": "/npm/indent-string", "_phantomChildren": {}, "_requiredBy": [ "/npm/aggregate-error" ], "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "bugs": { "url": "https://github.com/sindresorhus/indent-string/issues" }, "description": "Indent each line in a string", "devDependencies": { "ava": "^1.4.1", "tsd": "^0.7.2", "xo": "^0.24.0" }, "engines": { "node": ">=8" }, "files": [ "index.js", "index.d.ts" ], "homepage": "https://github.com/sindresorhus/indent-string#readme", "keywords": [ "indent", "string", "pad", "align", "line", "text", "each", "every" ], "license": "MIT", "name": "indent-string", "repository": { "type": "git", "url": "git+https://github.com/sindresorhus/indent-string.git" }, "scripts": { "test": "xo && ava && tsd" }, "version": "4.0.0" } PK ~\]$Kindent-string/index.jsnu['use strict'; module.exports = (string, count = 1, options) => { options = { indent: ' ', includeEmptyLines: false, ...options }; if (typeof string !== 'string') { throw new TypeError( `Expected \`input\` to be a \`string\`, got \`${typeof string}\`` ); } if (typeof count !== 'number') { throw new TypeError( `Expected \`count\` to be a \`number\`, got \`${typeof count}\`` ); } if (typeof options.indent !== 'string') { throw new TypeError( `Expected \`options.indent\` to be a \`string\`, got \`${typeof options.indent}\`` ); } if (count === 0) { return string; } const regex = options.includeEmptyLines ? /^/gm : /^(?!\s*$)/gm; return string.replace(regex, options.indent.repeat(count)); }; PK ~\E}UUindent-string/licensenu[MIT License Copyright (c) Sindre Sorhus (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\Ghosted-git-info/package.jsonnu[{ "_id": "hosted-git-info@7.0.2", "_inBundle": true, "_location": "/npm/hosted-git-info", "_phantomChildren": {}, "_requiredBy": [ "/npm", "/npm/@npmcli/arborist", "/npm/@npmcli/package-json", "/npm/normalize-package-data", "/npm/npm-package-arg" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/hosted-git-info/issues" }, "dependencies": { "lru-cache": "^10.0.1" }, "description": "Provides metadata and conversions from repository urls for GitHub, Bitbucket and GitLab", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.22.0", "tap": "^16.0.1" }, "engines": { "node": "^16.14.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/hosted-git-info", "keywords": [ "git", "github", "bitbucket", "gitlab" ], "license": "ISC", "main": "./lib/index.js", "name": "hosted-git-info", "repository": { "type": "git", "url": "git+https://github.com/npm/hosted-git-info.git" }, "scripts": { "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap", "test:coverage": "tap --coverage-report=html" }, "tap": { "color": 1, "coverage": true, "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.22.0", "publish": "true" }, "version": "7.0.2" } PK ~\kEH{{hosted-git-info/lib/from-url.jsnu['use strict' const parseUrl = require('./parse-url') // look for github shorthand inputs, such as npm/cli const isGitHubShorthand = (arg) => { // it cannot contain whitespace before the first # // it cannot start with a / because that's probably an absolute file path // but it must include a slash since repos are username/repository // it cannot start with a . because that's probably a relative file path // it cannot start with an @ because that's a scoped package if it passes the other tests // it cannot contain a : before a # because that tells us that there's a protocol // a second / may not exist before a # const firstHash = arg.indexOf('#') const firstSlash = arg.indexOf('/') const secondSlash = arg.indexOf('/', firstSlash + 1) const firstColon = arg.indexOf(':') const firstSpace = /\s/.exec(arg) const firstAt = arg.indexOf('@') const spaceOnlyAfterHash = !firstSpace || (firstHash > -1 && firstSpace.index > firstHash) const atOnlyAfterHash = firstAt === -1 || (firstHash > -1 && firstAt > firstHash) const colonOnlyAfterHash = firstColon === -1 || (firstHash > -1 && firstColon > firstHash) const secondSlashOnlyAfterHash = secondSlash === -1 || (firstHash > -1 && secondSlash > firstHash) const hasSlash = firstSlash > 0 // if a # is found, what we really want to know is that the character // immediately before # is not a / const doesNotEndWithSlash = firstHash > -1 ? arg[firstHash - 1] !== '/' : !arg.endsWith('/') const doesNotStartWithDot = !arg.startsWith('.') return spaceOnlyAfterHash && hasSlash && doesNotEndWithSlash && doesNotStartWithDot && atOnlyAfterHash && colonOnlyAfterHash && secondSlashOnlyAfterHash } module.exports = (giturl, opts, { gitHosts, protocols }) => { if (!giturl) { return } const correctedUrl = isGitHubShorthand(giturl) ? `github:${giturl}` : giturl const parsed = parseUrl(correctedUrl, protocols) if (!parsed) { return } const gitHostShortcut = gitHosts.byShortcut[parsed.protocol] const gitHostDomain = gitHosts.byDomain[parsed.hostname.startsWith('www.') ? parsed.hostname.slice(4) : parsed.hostname] const gitHostName = gitHostShortcut || gitHostDomain if (!gitHostName) { return } const gitHostInfo = gitHosts[gitHostShortcut || gitHostDomain] let auth = null if (protocols[parsed.protocol]?.auth && (parsed.username || parsed.password)) { auth = `${parsed.username}${parsed.password ? ':' + parsed.password : ''}` } let committish = null let user = null let project = null let defaultRepresentation = null try { if (gitHostShortcut) { let pathname = parsed.pathname.startsWith('/') ? parsed.pathname.slice(1) : parsed.pathname const firstAt = pathname.indexOf('@') // we ignore auth for shortcuts, so just trim it out if (firstAt > -1) { pathname = pathname.slice(firstAt + 1) } const lastSlash = pathname.lastIndexOf('/') if (lastSlash > -1) { user = decodeURIComponent(pathname.slice(0, lastSlash)) // we want nulls only, never empty strings if (!user) { user = null } project = decodeURIComponent(pathname.slice(lastSlash + 1)) } else { project = decodeURIComponent(pathname) } if (project.endsWith('.git')) { project = project.slice(0, -4) } if (parsed.hash) { committish = decodeURIComponent(parsed.hash.slice(1)) } defaultRepresentation = 'shortcut' } else { if (!gitHostInfo.protocols.includes(parsed.protocol)) { return } const segments = gitHostInfo.extract(parsed) if (!segments) { return } user = segments.user && decodeURIComponent(segments.user) project = decodeURIComponent(segments.project) committish = decodeURIComponent(segments.committish) defaultRepresentation = protocols[parsed.protocol]?.name || parsed.protocol.slice(0, -1) } } catch (err) { /* istanbul ignore else */ if (err instanceof URIError) { return } else { throw err } } return [gitHostName, user, auth, project, committish, defaultRepresentation, opts] } PK ~\qo@@hosted-git-info/lib/index.jsnu['use strict' const { LRUCache } = require('lru-cache') const hosts = require('./hosts.js') const fromUrl = require('./from-url.js') const parseUrl = require('./parse-url.js') const cache = new LRUCache({ max: 1000 }) class GitHost { constructor (type, user, auth, project, committish, defaultRepresentation, opts = {}) { Object.assign(this, GitHost.#gitHosts[type], { type, user, auth, project, committish, default: defaultRepresentation, opts, }) } static #gitHosts = { byShortcut: {}, byDomain: {} } static #protocols = { 'git+ssh:': { name: 'sshurl' }, 'ssh:': { name: 'sshurl' }, 'git+https:': { name: 'https', auth: true }, 'git:': { auth: true }, 'http:': { auth: true }, 'https:': { auth: true }, 'git+http:': { auth: true }, } static addHost (name, host) { GitHost.#gitHosts[name] = host GitHost.#gitHosts.byDomain[host.domain] = name GitHost.#gitHosts.byShortcut[`${name}:`] = name GitHost.#protocols[`${name}:`] = { name } } static fromUrl (giturl, opts) { if (typeof giturl !== 'string') { return } const key = giturl + JSON.stringify(opts || {}) if (!cache.has(key)) { const hostArgs = fromUrl(giturl, opts, { gitHosts: GitHost.#gitHosts, protocols: GitHost.#protocols, }) cache.set(key, hostArgs ? new GitHost(...hostArgs) : undefined) } return cache.get(key) } static parseUrl (url) { return parseUrl(url) } #fill (template, opts) { if (typeof template !== 'function') { return null } const options = { ...this, ...this.opts, ...opts } // the path should always be set so we don't end up with 'undefined' in urls if (!options.path) { options.path = '' } // template functions will insert the leading slash themselves if (options.path.startsWith('/')) { options.path = options.path.slice(1) } if (options.noCommittish) { options.committish = null } const result = template(options) return options.noGitPlus && result.startsWith('git+') ? result.slice(4) : result } hash () { return this.committish ? `#${this.committish}` : '' } ssh (opts) { return this.#fill(this.sshtemplate, opts) } sshurl (opts) { return this.#fill(this.sshurltemplate, opts) } browse (path, ...args) { // not a string, treat path as opts if (typeof path !== 'string') { return this.#fill(this.browsetemplate, path) } if (typeof args[0] !== 'string') { return this.#fill(this.browsetreetemplate, { ...args[0], path }) } return this.#fill(this.browsetreetemplate, { ...args[1], fragment: args[0], path }) } // If the path is known to be a file, then browseFile should be used. For some hosts // the url is the same as browse, but for others like GitHub a file can use both `/tree/` // and `/blob/` in the path. When using a default committish of `HEAD` then the `/tree/` // path will redirect to a specific commit. Using the `/blob/` path avoids this and // does not redirect to a different commit. browseFile (path, ...args) { if (typeof args[0] !== 'string') { return this.#fill(this.browseblobtemplate, { ...args[0], path }) } return this.#fill(this.browseblobtemplate, { ...args[1], fragment: args[0], path }) } docs (opts) { return this.#fill(this.docstemplate, opts) } bugs (opts) { return this.#fill(this.bugstemplate, opts) } https (opts) { return this.#fill(this.httpstemplate, opts) } git (opts) { return this.#fill(this.gittemplate, opts) } shortcut (opts) { return this.#fill(this.shortcuttemplate, opts) } path (opts) { return this.#fill(this.pathtemplate, opts) } tarball (opts) { return this.#fill(this.tarballtemplate, { ...opts, noCommittish: false }) } file (path, opts) { return this.#fill(this.filetemplate, { ...opts, path }) } edit (path, opts) { return this.#fill(this.edittemplate, { ...opts, path }) } getDefaultRepresentation () { return this.default } toString (opts) { if (this.default && typeof this[this.default] === 'function') { return this[this.default](opts) } return this.sshurl(opts) } } for (const [name, host] of Object.entries(hosts)) { GitHost.addHost(name, host) } module.exports = GitHost PK ~\5 hosted-git-info/lib/parse-url.jsnu[const url = require('url') const lastIndexOfBefore = (str, char, beforeChar) => { const startPosition = str.indexOf(beforeChar) return str.lastIndexOf(char, startPosition > -1 ? startPosition : Infinity) } const safeUrl = (u) => { try { return new url.URL(u) } catch { // this fn should never throw } } // accepts input like git:github.com:user/repo and inserts the // after the first : const correctProtocol = (arg, protocols) => { const firstColon = arg.indexOf(':') const proto = arg.slice(0, firstColon + 1) if (Object.prototype.hasOwnProperty.call(protocols, proto)) { return arg } const firstAt = arg.indexOf('@') if (firstAt > -1) { if (firstAt > firstColon) { return `git+ssh://${arg}` } else { return arg } } const doubleSlash = arg.indexOf('//') if (doubleSlash === firstColon + 1) { return arg } return `${arg.slice(0, firstColon + 1)}//${arg.slice(firstColon + 1)}` } // attempt to correct an scp style url so that it will parse with `new URL()` const correctUrl = (giturl) => { // ignore @ that come after the first hash since the denotes the start // of a committish which can contain @ characters const firstAt = lastIndexOfBefore(giturl, '@', '#') // ignore colons that come after the hash since that could include colons such as: // git@github.com:user/package-2#semver:^1.0.0 const lastColonBeforeHash = lastIndexOfBefore(giturl, ':', '#') if (lastColonBeforeHash > firstAt) { // the last : comes after the first @ (or there is no @) // like it would in: // proto://hostname.com:user/repo // username@hostname.com:user/repo // :password@hostname.com:user/repo // username:password@hostname.com:user/repo // proto://username@hostname.com:user/repo // proto://:password@hostname.com:user/repo // proto://username:password@hostname.com:user/repo // then we replace the last : with a / to create a valid path giturl = giturl.slice(0, lastColonBeforeHash) + '/' + giturl.slice(lastColonBeforeHash + 1) } if (lastIndexOfBefore(giturl, ':', '#') === -1 && giturl.indexOf('//') === -1) { // we have no : at all // as it would be in: // username@hostname.com/user/repo // then we prepend a protocol giturl = `git+ssh://${giturl}` } return giturl } module.exports = (giturl, protocols) => { const withProtocol = protocols ? correctProtocol(giturl, protocols) : giturl return safeUrl(withProtocol) || safeUrl(correctUrl(withProtocol)) } PK ~\}=##hosted-git-info/lib/hosts.jsnu[/* eslint-disable max-len */ 'use strict' const maybeJoin = (...args) => args.every(arg => arg) ? args.join('') : '' const maybeEncode = (arg) => arg ? encodeURIComponent(arg) : '' const formatHashFragment = (f) => f.toLowerCase().replace(/^\W+|\/|\W+$/g, '').replace(/\W+/g, '-') const defaults = { sshtemplate: ({ domain, user, project, committish }) => `git@${domain}:${user}/${project}.git${maybeJoin('#', committish)}`, sshurltemplate: ({ domain, user, project, committish }) => `git+ssh://git@${domain}/${user}/${project}.git${maybeJoin('#', committish)}`, edittemplate: ({ domain, user, project, committish, editpath, path }) => `https://${domain}/${user}/${project}${maybeJoin('/', editpath, '/', maybeEncode(committish || 'HEAD'), '/', path)}`, browsetemplate: ({ domain, user, project, committish, treepath }) => `https://${domain}/${user}/${project}${maybeJoin('/', treepath, '/', maybeEncode(committish))}`, browsetreetemplate: ({ domain, user, project, committish, treepath, path, fragment, hashformat }) => `https://${domain}/${user}/${project}/${treepath}/${maybeEncode(committish || 'HEAD')}/${path}${maybeJoin('#', hashformat(fragment || ''))}`, browseblobtemplate: ({ domain, user, project, committish, blobpath, path, fragment, hashformat }) => `https://${domain}/${user}/${project}/${blobpath}/${maybeEncode(committish || 'HEAD')}/${path}${maybeJoin('#', hashformat(fragment || ''))}`, docstemplate: ({ domain, user, project, treepath, committish }) => `https://${domain}/${user}/${project}${maybeJoin('/', treepath, '/', maybeEncode(committish))}#readme`, httpstemplate: ({ auth, domain, user, project, committish }) => `git+https://${maybeJoin(auth, '@')}${domain}/${user}/${project}.git${maybeJoin('#', committish)}`, filetemplate: ({ domain, user, project, committish, path }) => `https://${domain}/${user}/${project}/raw/${maybeEncode(committish || 'HEAD')}/${path}`, shortcuttemplate: ({ type, user, project, committish }) => `${type}:${user}/${project}${maybeJoin('#', committish)}`, pathtemplate: ({ user, project, committish }) => `${user}/${project}${maybeJoin('#', committish)}`, bugstemplate: ({ domain, user, project }) => `https://${domain}/${user}/${project}/issues`, hashformat: formatHashFragment, } const hosts = {} hosts.github = { // First two are insecure and generally shouldn't be used any more, but // they are still supported. protocols: ['git:', 'http:', 'git+ssh:', 'git+https:', 'ssh:', 'https:'], domain: 'github.com', treepath: 'tree', blobpath: 'blob', editpath: 'edit', filetemplate: ({ auth, user, project, committish, path }) => `https://${maybeJoin(auth, '@')}raw.githubusercontent.com/${user}/${project}/${maybeEncode(committish || 'HEAD')}/${path}`, gittemplate: ({ auth, domain, user, project, committish }) => `git://${maybeJoin(auth, '@')}${domain}/${user}/${project}.git${maybeJoin('#', committish)}`, tarballtemplate: ({ domain, user, project, committish }) => `https://codeload.${domain}/${user}/${project}/tar.gz/${maybeEncode(committish || 'HEAD')}`, extract: (url) => { let [, user, project, type, committish] = url.pathname.split('/', 5) if (type && type !== 'tree') { return } if (!type) { committish = url.hash.slice(1) } if (project && project.endsWith('.git')) { project = project.slice(0, -4) } if (!user || !project) { return } return { user, project, committish } }, } hosts.bitbucket = { protocols: ['git+ssh:', 'git+https:', 'ssh:', 'https:'], domain: 'bitbucket.org', treepath: 'src', blobpath: 'src', editpath: '?mode=edit', edittemplate: ({ domain, user, project, committish, treepath, path, editpath }) => `https://${domain}/${user}/${project}${maybeJoin('/', treepath, '/', maybeEncode(committish || 'HEAD'), '/', path, editpath)}`, tarballtemplate: ({ domain, user, project, committish }) => `https://${domain}/${user}/${project}/get/${maybeEncode(committish || 'HEAD')}.tar.gz`, extract: (url) => { let [, user, project, aux] = url.pathname.split('/', 4) if (['get'].includes(aux)) { return } if (project && project.endsWith('.git')) { project = project.slice(0, -4) } if (!user || !project) { return } return { user, project, committish: url.hash.slice(1) } }, } hosts.gitlab = { protocols: ['git+ssh:', 'git+https:', 'ssh:', 'https:'], domain: 'gitlab.com', treepath: 'tree', blobpath: 'tree', editpath: '-/edit', httpstemplate: ({ auth, domain, user, project, committish }) => `git+https://${maybeJoin(auth, '@')}${domain}/${user}/${project}.git${maybeJoin('#', committish)}`, tarballtemplate: ({ domain, user, project, committish }) => `https://${domain}/${user}/${project}/repository/archive.tar.gz?ref=${maybeEncode(committish || 'HEAD')}`, extract: (url) => { const path = url.pathname.slice(1) if (path.includes('/-/') || path.includes('/archive.tar.gz')) { return } const segments = path.split('/') let project = segments.pop() if (project.endsWith('.git')) { project = project.slice(0, -4) } const user = segments.join('/') if (!user || !project) { return } return { user, project, committish: url.hash.slice(1) } }, } hosts.gist = { protocols: ['git:', 'git+ssh:', 'git+https:', 'ssh:', 'https:'], domain: 'gist.github.com', editpath: 'edit', sshtemplate: ({ domain, project, committish }) => `git@${domain}:${project}.git${maybeJoin('#', committish)}`, sshurltemplate: ({ domain, project, committish }) => `git+ssh://git@${domain}/${project}.git${maybeJoin('#', committish)}`, edittemplate: ({ domain, user, project, committish, editpath }) => `https://${domain}/${user}/${project}${maybeJoin('/', maybeEncode(committish))}/${editpath}`, browsetemplate: ({ domain, project, committish }) => `https://${domain}/${project}${maybeJoin('/', maybeEncode(committish))}`, browsetreetemplate: ({ domain, project, committish, path, hashformat }) => `https://${domain}/${project}${maybeJoin('/', maybeEncode(committish))}${maybeJoin('#', hashformat(path))}`, browseblobtemplate: ({ domain, project, committish, path, hashformat }) => `https://${domain}/${project}${maybeJoin('/', maybeEncode(committish))}${maybeJoin('#', hashformat(path))}`, docstemplate: ({ domain, project, committish }) => `https://${domain}/${project}${maybeJoin('/', maybeEncode(committish))}`, httpstemplate: ({ domain, project, committish }) => `git+https://${domain}/${project}.git${maybeJoin('#', committish)}`, filetemplate: ({ user, project, committish, path }) => `https://gist.githubusercontent.com/${user}/${project}/raw${maybeJoin('/', maybeEncode(committish))}/${path}`, shortcuttemplate: ({ type, project, committish }) => `${type}:${project}${maybeJoin('#', committish)}`, pathtemplate: ({ project, committish }) => `${project}${maybeJoin('#', committish)}`, bugstemplate: ({ domain, project }) => `https://${domain}/${project}`, gittemplate: ({ domain, project, committish }) => `git://${domain}/${project}.git${maybeJoin('#', committish)}`, tarballtemplate: ({ project, committish }) => `https://codeload.github.com/gist/${project}/tar.gz/${maybeEncode(committish || 'HEAD')}`, extract: (url) => { let [, user, project, aux] = url.pathname.split('/', 4) if (aux === 'raw') { return } if (!project) { if (!user) { return } project = user user = null } if (project.endsWith('.git')) { project = project.slice(0, -4) } return { user, project, committish: url.hash.slice(1) } }, hashformat: function (fragment) { return fragment && 'file-' + formatHashFragment(fragment) }, } hosts.sourcehut = { protocols: ['git+ssh:', 'https:'], domain: 'git.sr.ht', treepath: 'tree', blobpath: 'tree', filetemplate: ({ domain, user, project, committish, path }) => `https://${domain}/${user}/${project}/blob/${maybeEncode(committish) || 'HEAD'}/${path}`, httpstemplate: ({ domain, user, project, committish }) => `https://${domain}/${user}/${project}.git${maybeJoin('#', committish)}`, tarballtemplate: ({ domain, user, project, committish }) => `https://${domain}/${user}/${project}/archive/${maybeEncode(committish) || 'HEAD'}.tar.gz`, bugstemplate: () => null, extract: (url) => { let [, user, project, aux] = url.pathname.split('/', 4) // tarball url if (['archive'].includes(aux)) { return } if (project && project.endsWith('.git')) { project = project.slice(0, -4) } if (!user || !project) { return } return { user, project, committish: url.hash.slice(1) } }, } for (const [name, host] of Object.entries(hosts)) { hosts[name] = Object.assign({}, defaults, host) } module.exports = hosts PK ~\&Lhosted-git-info/LICENSEnu[Copyright (c) 2015, Rebecca Turner Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\A"spdx-expression-parse/package.jsonnu[{ "_id": "spdx-expression-parse@4.0.0", "_inBundle": true, "_location": "/npm/spdx-expression-parse", "_phantomChildren": {}, "_requiredBy": [ "/npm" ], "author": { "name": "Kyle E. Mitchell", "email": "kyle@kemitchell.com", "url": "https://kemitchell.com" }, "bugs": { "url": "https://github.com/jslicense/spdx-expression-parse.js/issues" }, "contributors": [ { "name": "C. Scott Ananian", "email": "cscott@cscott.net", "url": "http://cscott.net" }, { "name": "Kyle E. Mitchell", "email": "kyle@kemitchell.com", "url": "https://kemitchell.com" }, { "name": "Shinnosuke Watanabe", "email": "snnskwtnb@gmail.com" }, { "name": "Antoine Motet", "email": "antoine.motet@gmail.com" } ], "dependencies": { "spdx-exceptions": "^2.1.0", "spdx-license-ids": "^3.0.0" }, "description": "parse SPDX license expressions", "devDependencies": { "defence-cli": "^3.0.1", "replace-require-self": "^1.0.0", "standard": "^14.1.0" }, "files": [ "AUTHORS", "index.js", "parse.js", "scan.js" ], "homepage": "https://github.com/jslicense/spdx-expression-parse.js#readme", "keywords": [ "SPDX", "law", "legal", "license", "metadata", "package", "package.json", "standards" ], "license": "MIT", "name": "spdx-expression-parse", "repository": { "type": "git", "url": "git+https://github.com/jslicense/spdx-expression-parse.js.git" }, "scripts": { "lint": "standard", "test": "npm run test:suite && npm run test:readme", "test:readme": "defence -i javascript README.md | replace-require-self | node", "test:suite": "node test.js" }, "version": "4.0.0" } PK ~\WWspdx-expression-parse/LICENSEnu[The MIT License Copyright (c) 2015 Kyle E. Mitchell & other authors listed in AUTHORS Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\]Mspdx-expression-parse/index.jsnu['use strict' var scan = require('./scan') var parse = require('./parse') module.exports = function (source) { return parse(scan(source)) } PK ~\YU U spdx-expression-parse/parse.jsnu['use strict' // The ABNF grammar in the spec is totally ambiguous. // // This parser follows the operator precedence defined in the // `Order of Precedence and Parentheses` section. module.exports = function (tokens) { var index = 0 function hasMore () { return index < tokens.length } function token () { return hasMore() ? tokens[index] : null } function next () { if (!hasMore()) { throw new Error() } index++ } function parseOperator (operator) { var t = token() if (t && t.type === 'OPERATOR' && operator === t.string) { next() return t.string } } function parseWith () { if (parseOperator('WITH')) { var t = token() if (t && t.type === 'EXCEPTION') { next() return t.string } throw new Error('Expected exception after `WITH`') } } function parseLicenseRef () { // TODO: Actually, everything is concatenated into one string // for backward-compatibility but it could be better to return // a nice structure. var begin = index var string = '' var t = token() if (t.type === 'DOCUMENTREF') { next() string += 'DocumentRef-' + t.string + ':' if (!parseOperator(':')) { throw new Error('Expected `:` after `DocumentRef-...`') } } t = token() if (t.type === 'LICENSEREF') { next() string += 'LicenseRef-' + t.string return { license: string } } index = begin } function parseLicense () { var t = token() if (t && t.type === 'LICENSE') { next() var node = { license: t.string } if (parseOperator('+')) { node.plus = true } var exception = parseWith() if (exception) { node.exception = exception } return node } } function parseParenthesizedExpression () { var left = parseOperator('(') if (!left) { return } var expr = parseExpression() if (!parseOperator(')')) { throw new Error('Expected `)`') } return expr } function parseAtom () { return ( parseParenthesizedExpression() || parseLicenseRef() || parseLicense() ) } function makeBinaryOpParser (operator, nextParser) { return function parseBinaryOp () { var left = nextParser() if (!left) { return } if (!parseOperator(operator)) { return left } var right = parseBinaryOp() if (!right) { throw new Error('Expected expression') } return { left: left, conjunction: operator.toLowerCase(), right: right } } } var parseAnd = makeBinaryOpParser('AND', parseAtom) var parseExpression = makeBinaryOpParser('OR', parseAnd) var node = parseExpression() if (!node || hasMore()) { throw new Error('Syntax error') } return node } PK ~\4 spdx-expression-parse/scan.jsnu['use strict' var licenses = [] .concat(require('spdx-license-ids')) .concat(require('spdx-license-ids/deprecated')) var exceptions = require('spdx-exceptions') module.exports = function (source) { var index = 0 function hasMore () { return index < source.length } // `value` can be a regexp or a string. // If it is recognized, the matching source string is returned and // the index is incremented. Otherwise `undefined` is returned. function read (value) { if (value instanceof RegExp) { var chars = source.slice(index) var match = chars.match(value) if (match) { index += match[0].length return match[0] } } else { if (source.indexOf(value, index) === index) { index += value.length return value } } } function skipWhitespace () { read(/[ ]*/) } function operator () { var string var possibilities = [/^WITH/i, /^AND/i, /^OR/i, '(', ')', ':', '+'] for (var i = 0; i < possibilities.length; i++) { string = read(possibilities[i]) if (string) { break } } if (string === '+' && index > 1 && source[index - 2] === ' ') { throw new Error('Space before `+`') } return string && { type: 'OPERATOR', string: string.toUpperCase() } } function idstring () { return read(/[A-Za-z0-9-.]+/) } function expectIdstring () { var string = idstring() if (!string) { throw new Error('Expected idstring at offset ' + index) } return string } function documentRef () { if (read('DocumentRef-')) { var string = expectIdstring() return { type: 'DOCUMENTREF', string: string } } } function licenseRef () { if (read('LicenseRef-')) { var string = expectIdstring() return { type: 'LICENSEREF', string: string } } } function identifier () { var begin = index var string = idstring() if (licenses.indexOf(string) !== -1) { return { type: 'LICENSE', string: string } } else if (exceptions.indexOf(string) !== -1) { return { type: 'EXCEPTION', string: string } } index = begin } // Tries to read the next token. Returns `undefined` if no token is // recognized. function parseToken () { // Ordering matters return ( operator() || documentRef() || licenseRef() || identifier() ) } var tokens = [] while (hasMore()) { skipWhitespace() if (!hasMore()) { break } var token = parseToken() if (!token) { throw new Error('Unexpected `' + source[index] + '` at offset ' + index) } tokens.push(token) } return tokens } PK ~\BF.spdx-expression-parse/AUTHORSnu[C. Scott Ananian (http://cscott.net) Kyle E. Mitchell (https://kemitchell.com) Shinnosuke Watanabe Antoine Motet PK ~\y7ggenv-paths/package.jsonnu[{ "_id": "env-paths@2.2.1", "_inBundle": true, "_location": "/npm/env-paths", "_phantomChildren": {}, "_requiredBy": [ "/npm/node-gyp" ], "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "bugs": { "url": "https://github.com/sindresorhus/env-paths/issues" }, "description": "Get paths for storing things like data, config, cache, etc", "devDependencies": { "ava": "^1.4.1", "tsd": "^0.7.1", "xo": "^0.24.0" }, "engines": { "node": ">=6" }, "files": [ "index.js", "index.d.ts" ], "homepage": "https://github.com/sindresorhus/env-paths#readme", "keywords": [ "common", "user", "paths", "env", "environment", "directory", "dir", "appdir", "path", "data", "config", "cache", "logs", "temp", "linux", "unix" ], "license": "MIT", "name": "env-paths", "repository": { "type": "git", "url": "git+https://github.com/sindresorhus/env-paths.git" }, "scripts": { "test": "xo && ava && tsd" }, "version": "2.2.1" } PK ~\z74kkenv-paths/index.jsnu['use strict'; const path = require('path'); const os = require('os'); const homedir = os.homedir(); const tmpdir = os.tmpdir(); const {env} = process; const macos = name => { const library = path.join(homedir, 'Library'); return { data: path.join(library, 'Application Support', name), config: path.join(library, 'Preferences', name), cache: path.join(library, 'Caches', name), log: path.join(library, 'Logs', name), temp: path.join(tmpdir, name) }; }; const windows = name => { const appData = env.APPDATA || path.join(homedir, 'AppData', 'Roaming'); const localAppData = env.LOCALAPPDATA || path.join(homedir, 'AppData', 'Local'); return { // Data/config/cache/log are invented by me as Windows isn't opinionated about this data: path.join(localAppData, name, 'Data'), config: path.join(appData, name, 'Config'), cache: path.join(localAppData, name, 'Cache'), log: path.join(localAppData, name, 'Log'), temp: path.join(tmpdir, name) }; }; // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html const linux = name => { const username = path.basename(homedir); return { data: path.join(env.XDG_DATA_HOME || path.join(homedir, '.local', 'share'), name), config: path.join(env.XDG_CONFIG_HOME || path.join(homedir, '.config'), name), cache: path.join(env.XDG_CACHE_HOME || path.join(homedir, '.cache'), name), // https://wiki.debian.org/XDGBaseDirectorySpecification#state log: path.join(env.XDG_STATE_HOME || path.join(homedir, '.local', 'state'), name), temp: path.join(tmpdir, username, name) }; }; const envPaths = (name, options) => { if (typeof name !== 'string') { throw new TypeError(`Expected string, got ${typeof name}`); } options = Object.assign({suffix: 'nodejs'}, options); if (options.suffix) { // Add suffix to prevent possible conflict with native apps name += `-${options.suffix}`; } if (process.platform === 'darwin') { return macos(name); } if (process.platform === 'win32') { return windows(name); } return linux(name); }; module.exports = envPaths; // TODO: Remove this for the next major release module.exports.default = envPaths; PK ~\E}UUenv-paths/licensenu[MIT License Copyright (c) Sindre Sorhus (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\A# path-scurry/package.jsonnu[{ "_id": "path-scurry@1.11.1", "_inBundle": true, "_location": "/npm/path-scurry", "_phantomChildren": {}, "_requiredBy": [ "/npm/glob" ], "author": { "name": "Isaac Z. Schlueter", "email": "i@izs.me", "url": "https://blog.izs.me" }, "bugs": { "url": "https://github.com/isaacs/path-scurry/issues" }, "dependencies": { "lru-cache": "^10.2.0", "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" }, "description": "walk paths fast and efficiently", "devDependencies": { "@nodelib/fs.walk": "^1.2.8", "@types/node": "^20.12.11", "c8": "^7.12.0", "eslint-config-prettier": "^8.6.0", "mkdirp": "^3.0.0", "prettier": "^3.2.5", "rimraf": "^5.0.1", "tap": "^18.7.2", "ts-node": "^10.9.2", "tshy": "^1.14.0", "typedoc": "^0.25.12", "typescript": "^5.4.3" }, "engines": { "node": ">=16 || 14 >=14.18" }, "exports": { "./package.json": "./package.json", ".": { "import": { "types": "./dist/esm/index.d.ts", "default": "./dist/esm/index.js" }, "require": { "types": "./dist/commonjs/index.d.ts", "default": "./dist/commonjs/index.js" } } }, "files": [ "dist" ], "funding": { "url": "https://github.com/sponsors/isaacs" }, "homepage": "https://github.com/isaacs/path-scurry#readme", "license": "BlueOak-1.0.0", "main": "./dist/commonjs/index.js", "name": "path-scurry", "prettier": { "experimentalTernaries": true, "semi": false, "printWidth": 75, "tabWidth": 2, "useTabs": false, "singleQuote": true, "jsxSingleQuote": false, "bracketSameLine": true, "arrowParens": "avoid", "endOfLine": "lf" }, "repository": { "type": "git", "url": "git+https://github.com/isaacs/path-scurry.git" }, "scripts": { "bench": "bash ./scripts/bench.sh", "format": "prettier --write . --loglevel warn", "postversion": "npm publish", "prepare": "tshy", "prepublishOnly": "git push origin --follow-tags", "presnap": "npm run prepare", "pretest": "npm run prepare", "preversion": "npm test", "snap": "tap", "test": "tap", "typedoc": "typedoc --tsconfig tsconfig-esm.json ./src/*.ts" }, "tap": { "typecheck": true }, "tshy": { "selfLink": false, "exports": { "./package.json": "./package.json", ".": "./src/index.ts" } }, "type": "module", "types": "./dist/commonjs/index.d.ts", "version": "1.11.1" } PK ~\>&path-scurry/dist/commonjs/package.jsonnu[{ "type": "commonjs" } PK ~\#*JJ"path-scurry/dist/commonjs/index.jsnu["use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.PathScurry = exports.Path = exports.PathScurryDarwin = exports.PathScurryPosix = exports.PathScurryWin32 = exports.PathScurryBase = exports.PathPosix = exports.PathWin32 = exports.PathBase = exports.ChildrenCache = exports.ResolveCache = void 0; const lru_cache_1 = require("lru-cache"); const node_path_1 = require("node:path"); const node_url_1 = require("node:url"); const fs_1 = require("fs"); const actualFS = __importStar(require("node:fs")); const realpathSync = fs_1.realpathSync.native; // TODO: test perf of fs/promises realpath vs realpathCB, // since the promises one uses realpath.native const promises_1 = require("node:fs/promises"); const minipass_1 = require("minipass"); const defaultFS = { lstatSync: fs_1.lstatSync, readdir: fs_1.readdir, readdirSync: fs_1.readdirSync, readlinkSync: fs_1.readlinkSync, realpathSync, promises: { lstat: promises_1.lstat, readdir: promises_1.readdir, readlink: promises_1.readlink, realpath: promises_1.realpath, }, }; // if they just gave us require('fs') then use our default const fsFromOption = (fsOption) => !fsOption || fsOption === defaultFS || fsOption === actualFS ? defaultFS : { ...defaultFS, ...fsOption, promises: { ...defaultFS.promises, ...(fsOption.promises || {}), }, }; // turn something like //?/c:/ into c:\ const uncDriveRegexp = /^\\\\\?\\([a-z]:)\\?$/i; const uncToDrive = (rootPath) => rootPath.replace(/\//g, '\\').replace(uncDriveRegexp, '$1\\'); // windows paths are separated by either / or \ const eitherSep = /[\\\/]/; const UNKNOWN = 0; // may not even exist, for all we know const IFIFO = 0b0001; const IFCHR = 0b0010; const IFDIR = 0b0100; const IFBLK = 0b0110; const IFREG = 0b1000; const IFLNK = 0b1010; const IFSOCK = 0b1100; const IFMT = 0b1111; // mask to unset low 4 bits const IFMT_UNKNOWN = ~IFMT; // set after successfully calling readdir() and getting entries. const READDIR_CALLED = 0b0000_0001_0000; // set after a successful lstat() const LSTAT_CALLED = 0b0000_0010_0000; // set if an entry (or one of its parents) is definitely not a dir const ENOTDIR = 0b0000_0100_0000; // set if an entry (or one of its parents) does not exist // (can also be set on lstat errors like EACCES or ENAMETOOLONG) const ENOENT = 0b0000_1000_0000; // cannot have child entries -- also verify &IFMT is either IFDIR or IFLNK // set if we fail to readlink const ENOREADLINK = 0b0001_0000_0000; // set if we know realpath() will fail const ENOREALPATH = 0b0010_0000_0000; const ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH; const TYPEMASK = 0b0011_1111_1111; const entToType = (s) => s.isFile() ? IFREG : s.isDirectory() ? IFDIR : s.isSymbolicLink() ? IFLNK : s.isCharacterDevice() ? IFCHR : s.isBlockDevice() ? IFBLK : s.isSocket() ? IFSOCK : s.isFIFO() ? IFIFO : UNKNOWN; // normalize unicode path names const normalizeCache = new Map(); const normalize = (s) => { const c = normalizeCache.get(s); if (c) return c; const n = s.normalize('NFKD'); normalizeCache.set(s, n); return n; }; const normalizeNocaseCache = new Map(); const normalizeNocase = (s) => { const c = normalizeNocaseCache.get(s); if (c) return c; const n = normalize(s.toLowerCase()); normalizeNocaseCache.set(s, n); return n; }; /** * An LRUCache for storing resolved path strings or Path objects. * @internal */ class ResolveCache extends lru_cache_1.LRUCache { constructor() { super({ max: 256 }); } } exports.ResolveCache = ResolveCache; // In order to prevent blowing out the js heap by allocating hundreds of // thousands of Path entries when walking extremely large trees, the "children" // in this tree are represented by storing an array of Path entries in an // LRUCache, indexed by the parent. At any time, Path.children() may return an // empty array, indicating that it doesn't know about any of its children, and // thus has to rebuild that cache. This is fine, it just means that we don't // benefit as much from having the cached entries, but huge directory walks // don't blow out the stack, and smaller ones are still as fast as possible. // //It does impose some complexity when building up the readdir data, because we //need to pass a reference to the children array that we started with. /** * an LRUCache for storing child entries. * @internal */ class ChildrenCache extends lru_cache_1.LRUCache { constructor(maxSize = 16 * 1024) { super({ maxSize, // parent + children sizeCalculation: a => a.length + 1, }); } } exports.ChildrenCache = ChildrenCache; const setAsCwd = Symbol('PathScurry setAsCwd'); /** * Path objects are sort of like a super-powered * {@link https://nodejs.org/docs/latest/api/fs.html#class-fsdirent fs.Dirent} * * Each one represents a single filesystem entry on disk, which may or may not * exist. It includes methods for reading various types of information via * lstat, readlink, and readdir, and caches all information to the greatest * degree possible. * * Note that fs operations that would normally throw will instead return an * "empty" value. This is in order to prevent excessive overhead from error * stack traces. */ class PathBase { /** * the basename of this path * * **Important**: *always* test the path name against any test string * usingthe {@link isNamed} method, and not by directly comparing this * string. Otherwise, unicode path strings that the system sees as identical * will not be properly treated as the same path, leading to incorrect * behavior and possible security issues. */ name; /** * the Path entry corresponding to the path root. * * @internal */ root; /** * All roots found within the current PathScurry family * * @internal */ roots; /** * a reference to the parent path, or undefined in the case of root entries * * @internal */ parent; /** * boolean indicating whether paths are compared case-insensitively * @internal */ nocase; /** * boolean indicating that this path is the current working directory * of the PathScurry collection that contains it. */ isCWD = false; // potential default fs override #fs; // Stats fields #dev; get dev() { return this.#dev; } #mode; get mode() { return this.#mode; } #nlink; get nlink() { return this.#nlink; } #uid; get uid() { return this.#uid; } #gid; get gid() { return this.#gid; } #rdev; get rdev() { return this.#rdev; } #blksize; get blksize() { return this.#blksize; } #ino; get ino() { return this.#ino; } #size; get size() { return this.#size; } #blocks; get blocks() { return this.#blocks; } #atimeMs; get atimeMs() { return this.#atimeMs; } #mtimeMs; get mtimeMs() { return this.#mtimeMs; } #ctimeMs; get ctimeMs() { return this.#ctimeMs; } #birthtimeMs; get birthtimeMs() { return this.#birthtimeMs; } #atime; get atime() { return this.#atime; } #mtime; get mtime() { return this.#mtime; } #ctime; get ctime() { return this.#ctime; } #birthtime; get birthtime() { return this.#birthtime; } #matchName; #depth; #fullpath; #fullpathPosix; #relative; #relativePosix; #type; #children; #linkTarget; #realpath; /** * This property is for compatibility with the Dirent class as of * Node v20, where Dirent['parentPath'] refers to the path of the * directory that was passed to readdir. For root entries, it's the path * to the entry itself. */ get parentPath() { return (this.parent || this).fullpath(); } /** * Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively, * this property refers to the *parent* path, not the path object itself. */ get path() { return this.parentPath; } /** * Do not create new Path objects directly. They should always be accessed * via the PathScurry class or other methods on the Path class. * * @internal */ constructor(name, type = UNKNOWN, root, roots, nocase, children, opts) { this.name = name; this.#matchName = nocase ? normalizeNocase(name) : normalize(name); this.#type = type & TYPEMASK; this.nocase = nocase; this.roots = roots; this.root = root || this; this.#children = children; this.#fullpath = opts.fullpath; this.#relative = opts.relative; this.#relativePosix = opts.relativePosix; this.parent = opts.parent; if (this.parent) { this.#fs = this.parent.#fs; } else { this.#fs = fsFromOption(opts.fs); } } /** * Returns the depth of the Path object from its root. * * For example, a path at `/foo/bar` would have a depth of 2. */ depth() { if (this.#depth !== undefined) return this.#depth; if (!this.parent) return (this.#depth = 0); return (this.#depth = this.parent.depth() + 1); } /** * @internal */ childrenCache() { return this.#children; } /** * Get the Path object referenced by the string path, resolved from this Path */ resolve(path) { if (!path) { return this; } const rootPath = this.getRootString(path); const dir = path.substring(rootPath.length); const dirParts = dir.split(this.splitSep); const result = rootPath ? this.getRoot(rootPath).#resolveParts(dirParts) : this.#resolveParts(dirParts); return result; } #resolveParts(dirParts) { let p = this; for (const part of dirParts) { p = p.child(part); } return p; } /** * Returns the cached children Path objects, if still available. If they * have fallen out of the cache, then returns an empty array, and resets the * READDIR_CALLED bit, so that future calls to readdir() will require an fs * lookup. * * @internal */ children() { const cached = this.#children.get(this); if (cached) { return cached; } const children = Object.assign([], { provisional: 0 }); this.#children.set(this, children); this.#type &= ~READDIR_CALLED; return children; } /** * Resolves a path portion and returns or creates the child Path. * * Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is * `'..'`. * * This should not be called directly. If `pathPart` contains any path * separators, it will lead to unsafe undefined behavior. * * Use `Path.resolve()` instead. * * @internal */ child(pathPart, opts) { if (pathPart === '' || pathPart === '.') { return this; } if (pathPart === '..') { return this.parent || this; } // find the child const children = this.children(); const name = this.nocase ? normalizeNocase(pathPart) : normalize(pathPart); for (const p of children) { if (p.#matchName === name) { return p; } } // didn't find it, create provisional child, since it might not // actually exist. If we know the parent isn't a dir, then // in fact it CAN'T exist. const s = this.parent ? this.sep : ''; const fullpath = this.#fullpath ? this.#fullpath + s + pathPart : undefined; const pchild = this.newChild(pathPart, UNKNOWN, { ...opts, parent: this, fullpath, }); if (!this.canReaddir()) { pchild.#type |= ENOENT; } // don't have to update provisional, because if we have real children, // then provisional is set to children.length, otherwise a lower number children.push(pchild); return pchild; } /** * The relative path from the cwd. If it does not share an ancestor with * the cwd, then this ends up being equivalent to the fullpath() */ relative() { if (this.isCWD) return ''; if (this.#relative !== undefined) { return this.#relative; } const name = this.name; const p = this.parent; if (!p) { return (this.#relative = this.name); } const pv = p.relative(); return pv + (!pv || !p.parent ? '' : this.sep) + name; } /** * The relative path from the cwd, using / as the path separator. * If it does not share an ancestor with * the cwd, then this ends up being equivalent to the fullpathPosix() * On posix systems, this is identical to relative(). */ relativePosix() { if (this.sep === '/') return this.relative(); if (this.isCWD) return ''; if (this.#relativePosix !== undefined) return this.#relativePosix; const name = this.name; const p = this.parent; if (!p) { return (this.#relativePosix = this.fullpathPosix()); } const pv = p.relativePosix(); return pv + (!pv || !p.parent ? '' : '/') + name; } /** * The fully resolved path string for this Path entry */ fullpath() { if (this.#fullpath !== undefined) { return this.#fullpath; } const name = this.name; const p = this.parent; if (!p) { return (this.#fullpath = this.name); } const pv = p.fullpath(); const fp = pv + (!p.parent ? '' : this.sep) + name; return (this.#fullpath = fp); } /** * On platforms other than windows, this is identical to fullpath. * * On windows, this is overridden to return the forward-slash form of the * full UNC path. */ fullpathPosix() { if (this.#fullpathPosix !== undefined) return this.#fullpathPosix; if (this.sep === '/') return (this.#fullpathPosix = this.fullpath()); if (!this.parent) { const p = this.fullpath().replace(/\\/g, '/'); if (/^[a-z]:\//i.test(p)) { return (this.#fullpathPosix = `//?/${p}`); } else { return (this.#fullpathPosix = p); } } const p = this.parent; const pfpp = p.fullpathPosix(); const fpp = pfpp + (!pfpp || !p.parent ? '' : '/') + this.name; return (this.#fullpathPosix = fpp); } /** * Is the Path of an unknown type? * * Note that we might know *something* about it if there has been a previous * filesystem operation, for example that it does not exist, or is not a * link, or whether it has child entries. */ isUnknown() { return (this.#type & IFMT) === UNKNOWN; } isType(type) { return this[`is${type}`](); } getType() { return (this.isUnknown() ? 'Unknown' : this.isDirectory() ? 'Directory' : this.isFile() ? 'File' : this.isSymbolicLink() ? 'SymbolicLink' : this.isFIFO() ? 'FIFO' : this.isCharacterDevice() ? 'CharacterDevice' : this.isBlockDevice() ? 'BlockDevice' : /* c8 ignore start */ this.isSocket() ? 'Socket' : 'Unknown'); /* c8 ignore stop */ } /** * Is the Path a regular file? */ isFile() { return (this.#type & IFMT) === IFREG; } /** * Is the Path a directory? */ isDirectory() { return (this.#type & IFMT) === IFDIR; } /** * Is the path a character device? */ isCharacterDevice() { return (this.#type & IFMT) === IFCHR; } /** * Is the path a block device? */ isBlockDevice() { return (this.#type & IFMT) === IFBLK; } /** * Is the path a FIFO pipe? */ isFIFO() { return (this.#type & IFMT) === IFIFO; } /** * Is the path a socket? */ isSocket() { return (this.#type & IFMT) === IFSOCK; } /** * Is the path a symbolic link? */ isSymbolicLink() { return (this.#type & IFLNK) === IFLNK; } /** * Return the entry if it has been subject of a successful lstat, or * undefined otherwise. * * Does not read the filesystem, so an undefined result *could* simply * mean that we haven't called lstat on it. */ lstatCached() { return this.#type & LSTAT_CALLED ? this : undefined; } /** * Return the cached link target if the entry has been the subject of a * successful readlink, or undefined otherwise. * * Does not read the filesystem, so an undefined result *could* just mean we * don't have any cached data. Only use it if you are very sure that a * readlink() has been called at some point. */ readlinkCached() { return this.#linkTarget; } /** * Returns the cached realpath target if the entry has been the subject * of a successful realpath, or undefined otherwise. * * Does not read the filesystem, so an undefined result *could* just mean we * don't have any cached data. Only use it if you are very sure that a * realpath() has been called at some point. */ realpathCached() { return this.#realpath; } /** * Returns the cached child Path entries array if the entry has been the * subject of a successful readdir(), or [] otherwise. * * Does not read the filesystem, so an empty array *could* just mean we * don't have any cached data. Only use it if you are very sure that a * readdir() has been called recently enough to still be valid. */ readdirCached() { const children = this.children(); return children.slice(0, children.provisional); } /** * Return true if it's worth trying to readlink. Ie, we don't (yet) have * any indication that readlink will definitely fail. * * Returns false if the path is known to not be a symlink, if a previous * readlink failed, or if the entry does not exist. */ canReadlink() { if (this.#linkTarget) return true; if (!this.parent) return false; // cases where it cannot possibly succeed const ifmt = this.#type & IFMT; return !((ifmt !== UNKNOWN && ifmt !== IFLNK) || this.#type & ENOREADLINK || this.#type & ENOENT); } /** * Return true if readdir has previously been successfully called on this * path, indicating that cachedReaddir() is likely valid. */ calledReaddir() { return !!(this.#type & READDIR_CALLED); } /** * Returns true if the path is known to not exist. That is, a previous lstat * or readdir failed to verify its existence when that would have been * expected, or a parent entry was marked either enoent or enotdir. */ isENOENT() { return !!(this.#type & ENOENT); } /** * Return true if the path is a match for the given path name. This handles * case sensitivity and unicode normalization. * * Note: even on case-sensitive systems, it is **not** safe to test the * equality of the `.name` property to determine whether a given pathname * matches, due to unicode normalization mismatches. * * Always use this method instead of testing the `path.name` property * directly. */ isNamed(n) { return !this.nocase ? this.#matchName === normalize(n) : this.#matchName === normalizeNocase(n); } /** * Return the Path object corresponding to the target of a symbolic link. * * If the Path is not a symbolic link, or if the readlink call fails for any * reason, `undefined` is returned. * * Result is cached, and thus may be outdated if the filesystem is mutated. */ async readlink() { const target = this.#linkTarget; if (target) { return target; } if (!this.canReadlink()) { return undefined; } /* c8 ignore start */ // already covered by the canReadlink test, here for ts grumples if (!this.parent) { return undefined; } /* c8 ignore stop */ try { const read = await this.#fs.promises.readlink(this.fullpath()); const linkTarget = (await this.parent.realpath())?.resolve(read); if (linkTarget) { return (this.#linkTarget = linkTarget); } } catch (er) { this.#readlinkFail(er.code); return undefined; } } /** * Synchronous {@link PathBase.readlink} */ readlinkSync() { const target = this.#linkTarget; if (target) { return target; } if (!this.canReadlink()) { return undefined; } /* c8 ignore start */ // already covered by the canReadlink test, here for ts grumples if (!this.parent) { return undefined; } /* c8 ignore stop */ try { const read = this.#fs.readlinkSync(this.fullpath()); const linkTarget = this.parent.realpathSync()?.resolve(read); if (linkTarget) { return (this.#linkTarget = linkTarget); } } catch (er) { this.#readlinkFail(er.code); return undefined; } } #readdirSuccess(children) { // succeeded, mark readdir called bit this.#type |= READDIR_CALLED; // mark all remaining provisional children as ENOENT for (let p = children.provisional; p < children.length; p++) { const c = children[p]; if (c) c.#markENOENT(); } } #markENOENT() { // mark as UNKNOWN and ENOENT if (this.#type & ENOENT) return; this.#type = (this.#type | ENOENT) & IFMT_UNKNOWN; this.#markChildrenENOENT(); } #markChildrenENOENT() { // all children are provisional and do not exist const children = this.children(); children.provisional = 0; for (const p of children) { p.#markENOENT(); } } #markENOREALPATH() { this.#type |= ENOREALPATH; this.#markENOTDIR(); } // save the information when we know the entry is not a dir #markENOTDIR() { // entry is not a directory, so any children can't exist. // this *should* be impossible, since any children created // after it's been marked ENOTDIR should be marked ENOENT, // so it won't even get to this point. /* c8 ignore start */ if (this.#type & ENOTDIR) return; /* c8 ignore stop */ let t = this.#type; // this could happen if we stat a dir, then delete it, // then try to read it or one of its children. if ((t & IFMT) === IFDIR) t &= IFMT_UNKNOWN; this.#type = t | ENOTDIR; this.#markChildrenENOENT(); } #readdirFail(code = '') { // markENOTDIR and markENOENT also set provisional=0 if (code === 'ENOTDIR' || code === 'EPERM') { this.#markENOTDIR(); } else if (code === 'ENOENT') { this.#markENOENT(); } else { this.children().provisional = 0; } } #lstatFail(code = '') { // Windows just raises ENOENT in this case, disable for win CI /* c8 ignore start */ if (code === 'ENOTDIR') { // already know it has a parent by this point const p = this.parent; p.#markENOTDIR(); } else if (code === 'ENOENT') { /* c8 ignore stop */ this.#markENOENT(); } } #readlinkFail(code = '') { let ter = this.#type; ter |= ENOREADLINK; if (code === 'ENOENT') ter |= ENOENT; // windows gets a weird error when you try to readlink a file if (code === 'EINVAL' || code === 'UNKNOWN') { // exists, but not a symlink, we don't know WHAT it is, so remove // all IFMT bits. ter &= IFMT_UNKNOWN; } this.#type = ter; // windows just gets ENOENT in this case. We do cover the case, // just disabled because it's impossible on Windows CI /* c8 ignore start */ if (code === 'ENOTDIR' && this.parent) { this.parent.#markENOTDIR(); } /* c8 ignore stop */ } #readdirAddChild(e, c) { return (this.#readdirMaybePromoteChild(e, c) || this.#readdirAddNewChild(e, c)); } #readdirAddNewChild(e, c) { // alloc new entry at head, so it's never provisional const type = entToType(e); const child = this.newChild(e.name, type, { parent: this }); const ifmt = child.#type & IFMT; if (ifmt !== IFDIR && ifmt !== IFLNK && ifmt !== UNKNOWN) { child.#type |= ENOTDIR; } c.unshift(child); c.provisional++; return child; } #readdirMaybePromoteChild(e, c) { for (let p = c.provisional; p < c.length; p++) { const pchild = c[p]; const name = this.nocase ? normalizeNocase(e.name) : normalize(e.name); if (name !== pchild.#matchName) { continue; } return this.#readdirPromoteChild(e, pchild, p, c); } } #readdirPromoteChild(e, p, index, c) { const v = p.name; // retain any other flags, but set ifmt from dirent p.#type = (p.#type & IFMT_UNKNOWN) | entToType(e); // case sensitivity fixing when we learn the true name. if (v !== e.name) p.name = e.name; // just advance provisional index (potentially off the list), // otherwise we have to splice/pop it out and re-insert at head if (index !== c.provisional) { if (index === c.length - 1) c.pop(); else c.splice(index, 1); c.unshift(p); } c.provisional++; return p; } /** * Call lstat() on this Path, and update all known information that can be * determined. * * Note that unlike `fs.lstat()`, the returned value does not contain some * information, such as `mode`, `dev`, `nlink`, and `ino`. If that * information is required, you will need to call `fs.lstat` yourself. * * If the Path refers to a nonexistent file, or if the lstat call fails for * any reason, `undefined` is returned. Otherwise the updated Path object is * returned. * * Results are cached, and thus may be out of date if the filesystem is * mutated. */ async lstat() { if ((this.#type & ENOENT) === 0) { try { this.#applyStat(await this.#fs.promises.lstat(this.fullpath())); return this; } catch (er) { this.#lstatFail(er.code); } } } /** * synchronous {@link PathBase.lstat} */ lstatSync() { if ((this.#type & ENOENT) === 0) { try { this.#applyStat(this.#fs.lstatSync(this.fullpath())); return this; } catch (er) { this.#lstatFail(er.code); } } } #applyStat(st) { const { atime, atimeMs, birthtime, birthtimeMs, blksize, blocks, ctime, ctimeMs, dev, gid, ino, mode, mtime, mtimeMs, nlink, rdev, size, uid, } = st; this.#atime = atime; this.#atimeMs = atimeMs; this.#birthtime = birthtime; this.#birthtimeMs = birthtimeMs; this.#blksize = blksize; this.#blocks = blocks; this.#ctime = ctime; this.#ctimeMs = ctimeMs; this.#dev = dev; this.#gid = gid; this.#ino = ino; this.#mode = mode; this.#mtime = mtime; this.#mtimeMs = mtimeMs; this.#nlink = nlink; this.#rdev = rdev; this.#size = size; this.#uid = uid; const ifmt = entToType(st); // retain any other flags, but set the ifmt this.#type = (this.#type & IFMT_UNKNOWN) | ifmt | LSTAT_CALLED; if (ifmt !== UNKNOWN && ifmt !== IFDIR && ifmt !== IFLNK) { this.#type |= ENOTDIR; } } #onReaddirCB = []; #readdirCBInFlight = false; #callOnReaddirCB(children) { this.#readdirCBInFlight = false; const cbs = this.#onReaddirCB.slice(); this.#onReaddirCB.length = 0; cbs.forEach(cb => cb(null, children)); } /** * Standard node-style callback interface to get list of directory entries. * * If the Path cannot or does not contain any children, then an empty array * is returned. * * Results are cached, and thus may be out of date if the filesystem is * mutated. * * @param cb The callback called with (er, entries). Note that the `er` * param is somewhat extraneous, as all readdir() errors are handled and * simply result in an empty set of entries being returned. * @param allowZalgo Boolean indicating that immediately known results should * *not* be deferred with `queueMicrotask`. Defaults to `false`. Release * zalgo at your peril, the dark pony lord is devious and unforgiving. */ readdirCB(cb, allowZalgo = false) { if (!this.canReaddir()) { if (allowZalgo) cb(null, []); else queueMicrotask(() => cb(null, [])); return; } const children = this.children(); if (this.calledReaddir()) { const c = children.slice(0, children.provisional); if (allowZalgo) cb(null, c); else queueMicrotask(() => cb(null, c)); return; } // don't have to worry about zalgo at this point. this.#onReaddirCB.push(cb); if (this.#readdirCBInFlight) { return; } this.#readdirCBInFlight = true; // else read the directory, fill up children // de-provisionalize any provisional children. const fullpath = this.fullpath(); this.#fs.readdir(fullpath, { withFileTypes: true }, (er, entries) => { if (er) { this.#readdirFail(er.code); children.provisional = 0; } else { // if we didn't get an error, we always get entries. //@ts-ignore for (const e of entries) { this.#readdirAddChild(e, children); } this.#readdirSuccess(children); } this.#callOnReaddirCB(children.slice(0, children.provisional)); return; }); } #asyncReaddirInFlight; /** * Return an array of known child entries. * * If the Path cannot or does not contain any children, then an empty array * is returned. * * Results are cached, and thus may be out of date if the filesystem is * mutated. */ async readdir() { if (!this.canReaddir()) { return []; } const children = this.children(); if (this.calledReaddir()) { return children.slice(0, children.provisional); } // else read the directory, fill up children // de-provisionalize any provisional children. const fullpath = this.fullpath(); if (this.#asyncReaddirInFlight) { await this.#asyncReaddirInFlight; } else { /* c8 ignore start */ let resolve = () => { }; /* c8 ignore stop */ this.#asyncReaddirInFlight = new Promise(res => (resolve = res)); try { for (const e of await this.#fs.promises.readdir(fullpath, { withFileTypes: true, })) { this.#readdirAddChild(e, children); } this.#readdirSuccess(children); } catch (er) { this.#readdirFail(er.code); children.provisional = 0; } this.#asyncReaddirInFlight = undefined; resolve(); } return children.slice(0, children.provisional); } /** * synchronous {@link PathBase.readdir} */ readdirSync() { if (!this.canReaddir()) { return []; } const children = this.children(); if (this.calledReaddir()) { return children.slice(0, children.provisional); } // else read the directory, fill up children // de-provisionalize any provisional children. const fullpath = this.fullpath(); try { for (const e of this.#fs.readdirSync(fullpath, { withFileTypes: true, })) { this.#readdirAddChild(e, children); } this.#readdirSuccess(children); } catch (er) { this.#readdirFail(er.code); children.provisional = 0; } return children.slice(0, children.provisional); } canReaddir() { if (this.#type & ENOCHILD) return false; const ifmt = IFMT & this.#type; // we always set ENOTDIR when setting IFMT, so should be impossible /* c8 ignore start */ if (!(ifmt === UNKNOWN || ifmt === IFDIR || ifmt === IFLNK)) { return false; } /* c8 ignore stop */ return true; } shouldWalk(dirs, walkFilter) { return ((this.#type & IFDIR) === IFDIR && !(this.#type & ENOCHILD) && !dirs.has(this) && (!walkFilter || walkFilter(this))); } /** * Return the Path object corresponding to path as resolved * by realpath(3). * * If the realpath call fails for any reason, `undefined` is returned. * * Result is cached, and thus may be outdated if the filesystem is mutated. * On success, returns a Path object. */ async realpath() { if (this.#realpath) return this.#realpath; if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined; try { const rp = await this.#fs.promises.realpath(this.fullpath()); return (this.#realpath = this.resolve(rp)); } catch (_) { this.#markENOREALPATH(); } } /** * Synchronous {@link realpath} */ realpathSync() { if (this.#realpath) return this.#realpath; if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined; try { const rp = this.#fs.realpathSync(this.fullpath()); return (this.#realpath = this.resolve(rp)); } catch (_) { this.#markENOREALPATH(); } } /** * Internal method to mark this Path object as the scurry cwd, * called by {@link PathScurry#chdir} * * @internal */ [setAsCwd](oldCwd) { if (oldCwd === this) return; oldCwd.isCWD = false; this.isCWD = true; const changed = new Set([]); let rp = []; let p = this; while (p && p.parent) { changed.add(p); p.#relative = rp.join(this.sep); p.#relativePosix = rp.join('/'); p = p.parent; rp.push('..'); } // now un-memoize parents of old cwd p = oldCwd; while (p && p.parent && !changed.has(p)) { p.#relative = undefined; p.#relativePosix = undefined; p = p.parent; } } } exports.PathBase = PathBase; /** * Path class used on win32 systems * * Uses `'\\'` as the path separator for returned paths, either `'\\'` or `'/'` * as the path separator for parsing paths. */ class PathWin32 extends PathBase { /** * Separator for generating path strings. */ sep = '\\'; /** * Separator for parsing path strings. */ splitSep = eitherSep; /** * Do not create new Path objects directly. They should always be accessed * via the PathScurry class or other methods on the Path class. * * @internal */ constructor(name, type = UNKNOWN, root, roots, nocase, children, opts) { super(name, type, root, roots, nocase, children, opts); } /** * @internal */ newChild(name, type = UNKNOWN, opts = {}) { return new PathWin32(name, type, this.root, this.roots, this.nocase, this.childrenCache(), opts); } /** * @internal */ getRootString(path) { return node_path_1.win32.parse(path).root; } /** * @internal */ getRoot(rootPath) { rootPath = uncToDrive(rootPath.toUpperCase()); if (rootPath === this.root.name) { return this.root; } // ok, not that one, check if it matches another we know about for (const [compare, root] of Object.entries(this.roots)) { if (this.sameRoot(rootPath, compare)) { return (this.roots[rootPath] = root); } } // otherwise, have to create a new one. return (this.roots[rootPath] = new PathScurryWin32(rootPath, this).root); } /** * @internal */ sameRoot(rootPath, compare = this.root.name) { // windows can (rarely) have case-sensitive filesystem, but // UNC and drive letters are always case-insensitive, and canonically // represented uppercase. rootPath = rootPath .toUpperCase() .replace(/\//g, '\\') .replace(uncDriveRegexp, '$1\\'); return rootPath === compare; } } exports.PathWin32 = PathWin32; /** * Path class used on all posix systems. * * Uses `'/'` as the path separator. */ class PathPosix extends PathBase { /** * separator for parsing path strings */ splitSep = '/'; /** * separator for generating path strings */ sep = '/'; /** * Do not create new Path objects directly. They should always be accessed * via the PathScurry class or other methods on the Path class. * * @internal */ constructor(name, type = UNKNOWN, root, roots, nocase, children, opts) { super(name, type, root, roots, nocase, children, opts); } /** * @internal */ getRootString(path) { return path.startsWith('/') ? '/' : ''; } /** * @internal */ getRoot(_rootPath) { return this.root; } /** * @internal */ newChild(name, type = UNKNOWN, opts = {}) { return new PathPosix(name, type, this.root, this.roots, this.nocase, this.childrenCache(), opts); } } exports.PathPosix = PathPosix; /** * The base class for all PathScurry classes, providing the interface for path * resolution and filesystem operations. * * Typically, you should *not* instantiate this class directly, but rather one * of the platform-specific classes, or the exported {@link PathScurry} which * defaults to the current platform. */ class PathScurryBase { /** * The root Path entry for the current working directory of this Scurry */ root; /** * The string path for the root of this Scurry's current working directory */ rootPath; /** * A collection of all roots encountered, referenced by rootPath */ roots; /** * The Path entry corresponding to this PathScurry's current working directory. */ cwd; #resolveCache; #resolvePosixCache; #children; /** * Perform path comparisons case-insensitively. * * Defaults true on Darwin and Windows systems, false elsewhere. */ nocase; #fs; /** * This class should not be instantiated directly. * * Use PathScurryWin32, PathScurryDarwin, PathScurryPosix, or PathScurry * * @internal */ constructor(cwd = process.cwd(), pathImpl, sep, { nocase, childrenCacheSize = 16 * 1024, fs = defaultFS, } = {}) { this.#fs = fsFromOption(fs); if (cwd instanceof URL || cwd.startsWith('file://')) { cwd = (0, node_url_1.fileURLToPath)(cwd); } // resolve and split root, and then add to the store. // this is the only time we call path.resolve() const cwdPath = pathImpl.resolve(cwd); this.roots = Object.create(null); this.rootPath = this.parseRootPath(cwdPath); this.#resolveCache = new ResolveCache(); this.#resolvePosixCache = new ResolveCache(); this.#children = new ChildrenCache(childrenCacheSize); const split = cwdPath.substring(this.rootPath.length).split(sep); // resolve('/') leaves '', splits to [''], we don't want that. if (split.length === 1 && !split[0]) { split.pop(); } /* c8 ignore start */ if (nocase === undefined) { throw new TypeError('must provide nocase setting to PathScurryBase ctor'); } /* c8 ignore stop */ this.nocase = nocase; this.root = this.newRoot(this.#fs); this.roots[this.rootPath] = this.root; let prev = this.root; let len = split.length - 1; const joinSep = pathImpl.sep; let abs = this.rootPath; let sawFirst = false; for (const part of split) { const l = len--; prev = prev.child(part, { relative: new Array(l).fill('..').join(joinSep), relativePosix: new Array(l).fill('..').join('/'), fullpath: (abs += (sawFirst ? '' : joinSep) + part), }); sawFirst = true; } this.cwd = prev; } /** * Get the depth of a provided path, string, or the cwd */ depth(path = this.cwd) { if (typeof path === 'string') { path = this.cwd.resolve(path); } return path.depth(); } /** * Return the cache of child entries. Exposed so subclasses can create * child Path objects in a platform-specific way. * * @internal */ childrenCache() { return this.#children; } /** * Resolve one or more path strings to a resolved string * * Same interface as require('path').resolve. * * Much faster than path.resolve() when called multiple times for the same * path, because the resolved Path objects are cached. Much slower * otherwise. */ resolve(...paths) { // first figure out the minimum number of paths we have to test // we always start at cwd, but any absolutes will bump the start let r = ''; for (let i = paths.length - 1; i >= 0; i--) { const p = paths[i]; if (!p || p === '.') continue; r = r ? `${p}/${r}` : p; if (this.isAbsolute(p)) { break; } } const cached = this.#resolveCache.get(r); if (cached !== undefined) { return cached; } const result = this.cwd.resolve(r).fullpath(); this.#resolveCache.set(r, result); return result; } /** * Resolve one or more path strings to a resolved string, returning * the posix path. Identical to .resolve() on posix systems, but on * windows will return a forward-slash separated UNC path. * * Same interface as require('path').resolve. * * Much faster than path.resolve() when called multiple times for the same * path, because the resolved Path objects are cached. Much slower * otherwise. */ resolvePosix(...paths) { // first figure out the minimum number of paths we have to test // we always start at cwd, but any absolutes will bump the start let r = ''; for (let i = paths.length - 1; i >= 0; i--) { const p = paths[i]; if (!p || p === '.') continue; r = r ? `${p}/${r}` : p; if (this.isAbsolute(p)) { break; } } const cached = this.#resolvePosixCache.get(r); if (cached !== undefined) { return cached; } const result = this.cwd.resolve(r).fullpathPosix(); this.#resolvePosixCache.set(r, result); return result; } /** * find the relative path from the cwd to the supplied path string or entry */ relative(entry = this.cwd) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } return entry.relative(); } /** * find the relative path from the cwd to the supplied path string or * entry, using / as the path delimiter, even on Windows. */ relativePosix(entry = this.cwd) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } return entry.relativePosix(); } /** * Return the basename for the provided string or Path object */ basename(entry = this.cwd) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } return entry.name; } /** * Return the dirname for the provided string or Path object */ dirname(entry = this.cwd) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } return (entry.parent || entry).fullpath(); } async readdir(entry = this.cwd, opts = { withFileTypes: true, }) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } else if (!(entry instanceof PathBase)) { opts = entry; entry = this.cwd; } const { withFileTypes } = opts; if (!entry.canReaddir()) { return []; } else { const p = await entry.readdir(); return withFileTypes ? p : p.map(e => e.name); } } readdirSync(entry = this.cwd, opts = { withFileTypes: true, }) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } else if (!(entry instanceof PathBase)) { opts = entry; entry = this.cwd; } const { withFileTypes = true } = opts; if (!entry.canReaddir()) { return []; } else if (withFileTypes) { return entry.readdirSync(); } else { return entry.readdirSync().map(e => e.name); } } /** * Call lstat() on the string or Path object, and update all known * information that can be determined. * * Note that unlike `fs.lstat()`, the returned value does not contain some * information, such as `mode`, `dev`, `nlink`, and `ino`. If that * information is required, you will need to call `fs.lstat` yourself. * * If the Path refers to a nonexistent file, or if the lstat call fails for * any reason, `undefined` is returned. Otherwise the updated Path object is * returned. * * Results are cached, and thus may be out of date if the filesystem is * mutated. */ async lstat(entry = this.cwd) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } return entry.lstat(); } /** * synchronous {@link PathScurryBase.lstat} */ lstatSync(entry = this.cwd) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } return entry.lstatSync(); } async readlink(entry = this.cwd, { withFileTypes } = { withFileTypes: false, }) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } else if (!(entry instanceof PathBase)) { withFileTypes = entry.withFileTypes; entry = this.cwd; } const e = await entry.readlink(); return withFileTypes ? e : e?.fullpath(); } readlinkSync(entry = this.cwd, { withFileTypes } = { withFileTypes: false, }) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } else if (!(entry instanceof PathBase)) { withFileTypes = entry.withFileTypes; entry = this.cwd; } const e = entry.readlinkSync(); return withFileTypes ? e : e?.fullpath(); } async realpath(entry = this.cwd, { withFileTypes } = { withFileTypes: false, }) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } else if (!(entry instanceof PathBase)) { withFileTypes = entry.withFileTypes; entry = this.cwd; } const e = await entry.realpath(); return withFileTypes ? e : e?.fullpath(); } realpathSync(entry = this.cwd, { withFileTypes } = { withFileTypes: false, }) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } else if (!(entry instanceof PathBase)) { withFileTypes = entry.withFileTypes; entry = this.cwd; } const e = entry.realpathSync(); return withFileTypes ? e : e?.fullpath(); } async walk(entry = this.cwd, opts = {}) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } else if (!(entry instanceof PathBase)) { opts = entry; entry = this.cwd; } const { withFileTypes = true, follow = false, filter, walkFilter, } = opts; const results = []; if (!filter || filter(entry)) { results.push(withFileTypes ? entry : entry.fullpath()); } const dirs = new Set(); const walk = (dir, cb) => { dirs.add(dir); dir.readdirCB((er, entries) => { /* c8 ignore start */ if (er) { return cb(er); } /* c8 ignore stop */ let len = entries.length; if (!len) return cb(); const next = () => { if (--len === 0) { cb(); } }; for (const e of entries) { if (!filter || filter(e)) { results.push(withFileTypes ? e : e.fullpath()); } if (follow && e.isSymbolicLink()) { e.realpath() .then(r => (r?.isUnknown() ? r.lstat() : r)) .then(r => r?.shouldWalk(dirs, walkFilter) ? walk(r, next) : next()); } else { if (e.shouldWalk(dirs, walkFilter)) { walk(e, next); } else { next(); } } } }, true); // zalgooooooo }; const start = entry; return new Promise((res, rej) => { walk(start, er => { /* c8 ignore start */ if (er) return rej(er); /* c8 ignore stop */ res(results); }); }); } walkSync(entry = this.cwd, opts = {}) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } else if (!(entry instanceof PathBase)) { opts = entry; entry = this.cwd; } const { withFileTypes = true, follow = false, filter, walkFilter, } = opts; const results = []; if (!filter || filter(entry)) { results.push(withFileTypes ? entry : entry.fullpath()); } const dirs = new Set([entry]); for (const dir of dirs) { const entries = dir.readdirSync(); for (const e of entries) { if (!filter || filter(e)) { results.push(withFileTypes ? e : e.fullpath()); } let r = e; if (e.isSymbolicLink()) { if (!(follow && (r = e.realpathSync()))) continue; if (r.isUnknown()) r.lstatSync(); } if (r.shouldWalk(dirs, walkFilter)) { dirs.add(r); } } } return results; } /** * Support for `for await` * * Alias for {@link PathScurryBase.iterate} * * Note: As of Node 19, this is very slow, compared to other methods of * walking. Consider using {@link PathScurryBase.stream} if memory overhead * and backpressure are concerns, or {@link PathScurryBase.walk} if not. */ [Symbol.asyncIterator]() { return this.iterate(); } iterate(entry = this.cwd, options = {}) { // iterating async over the stream is significantly more performant, // especially in the warm-cache scenario, because it buffers up directory // entries in the background instead of waiting for a yield for each one. if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } else if (!(entry instanceof PathBase)) { options = entry; entry = this.cwd; } return this.stream(entry, options)[Symbol.asyncIterator](); } /** * Iterating over a PathScurry performs a synchronous walk. * * Alias for {@link PathScurryBase.iterateSync} */ [Symbol.iterator]() { return this.iterateSync(); } *iterateSync(entry = this.cwd, opts = {}) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } else if (!(entry instanceof PathBase)) { opts = entry; entry = this.cwd; } const { withFileTypes = true, follow = false, filter, walkFilter, } = opts; if (!filter || filter(entry)) { yield withFileTypes ? entry : entry.fullpath(); } const dirs = new Set([entry]); for (const dir of dirs) { const entries = dir.readdirSync(); for (const e of entries) { if (!filter || filter(e)) { yield withFileTypes ? e : e.fullpath(); } let r = e; if (e.isSymbolicLink()) { if (!(follow && (r = e.realpathSync()))) continue; if (r.isUnknown()) r.lstatSync(); } if (r.shouldWalk(dirs, walkFilter)) { dirs.add(r); } } } } stream(entry = this.cwd, opts = {}) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } else if (!(entry instanceof PathBase)) { opts = entry; entry = this.cwd; } const { withFileTypes = true, follow = false, filter, walkFilter, } = opts; const results = new minipass_1.Minipass({ objectMode: true }); if (!filter || filter(entry)) { results.write(withFileTypes ? entry : entry.fullpath()); } const dirs = new Set(); const queue = [entry]; let processing = 0; const process = () => { let paused = false; while (!paused) { const dir = queue.shift(); if (!dir) { if (processing === 0) results.end(); return; } processing++; dirs.add(dir); const onReaddir = (er, entries, didRealpaths = false) => { /* c8 ignore start */ if (er) return results.emit('error', er); /* c8 ignore stop */ if (follow && !didRealpaths) { const promises = []; for (const e of entries) { if (e.isSymbolicLink()) { promises.push(e .realpath() .then((r) => r?.isUnknown() ? r.lstat() : r)); } } if (promises.length) { Promise.all(promises).then(() => onReaddir(null, entries, true)); return; } } for (const e of entries) { if (e && (!filter || filter(e))) { if (!results.write(withFileTypes ? e : e.fullpath())) { paused = true; } } } processing--; for (const e of entries) { const r = e.realpathCached() || e; if (r.shouldWalk(dirs, walkFilter)) { queue.push(r); } } if (paused && !results.flowing) { results.once('drain', process); } else if (!sync) { process(); } }; // zalgo containment let sync = true; dir.readdirCB(onReaddir, true); sync = false; } }; process(); return results; } streamSync(entry = this.cwd, opts = {}) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } else if (!(entry instanceof PathBase)) { opts = entry; entry = this.cwd; } const { withFileTypes = true, follow = false, filter, walkFilter, } = opts; const results = new minipass_1.Minipass({ objectMode: true }); const dirs = new Set(); if (!filter || filter(entry)) { results.write(withFileTypes ? entry : entry.fullpath()); } const queue = [entry]; let processing = 0; const process = () => { let paused = false; while (!paused) { const dir = queue.shift(); if (!dir) { if (processing === 0) results.end(); return; } processing++; dirs.add(dir); const entries = dir.readdirSync(); for (const e of entries) { if (!filter || filter(e)) { if (!results.write(withFileTypes ? e : e.fullpath())) { paused = true; } } } processing--; for (const e of entries) { let r = e; if (e.isSymbolicLink()) { if (!(follow && (r = e.realpathSync()))) continue; if (r.isUnknown()) r.lstatSync(); } if (r.shouldWalk(dirs, walkFilter)) { queue.push(r); } } } if (paused && !results.flowing) results.once('drain', process); }; process(); return results; } chdir(path = this.cwd) { const oldCwd = this.cwd; this.cwd = typeof path === 'string' ? this.cwd.resolve(path) : path; this.cwd[setAsCwd](oldCwd); } } exports.PathScurryBase = PathScurryBase; /** * Windows implementation of {@link PathScurryBase} * * Defaults to case insensitve, uses `'\\'` to generate path strings. Uses * {@link PathWin32} for Path objects. */ class PathScurryWin32 extends PathScurryBase { /** * separator for generating path strings */ sep = '\\'; constructor(cwd = process.cwd(), opts = {}) { const { nocase = true } = opts; super(cwd, node_path_1.win32, '\\', { ...opts, nocase }); this.nocase = nocase; for (let p = this.cwd; p; p = p.parent) { p.nocase = this.nocase; } } /** * @internal */ parseRootPath(dir) { // if the path starts with a single separator, it's not a UNC, and we'll // just get separator as the root, and driveFromUNC will return \ // In that case, mount \ on the root from the cwd. return node_path_1.win32.parse(dir).root.toUpperCase(); } /** * @internal */ newRoot(fs) { return new PathWin32(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs }); } /** * Return true if the provided path string is an absolute path */ isAbsolute(p) { return (p.startsWith('/') || p.startsWith('\\') || /^[a-z]:(\/|\\)/i.test(p)); } } exports.PathScurryWin32 = PathScurryWin32; /** * {@link PathScurryBase} implementation for all posix systems other than Darwin. * * Defaults to case-sensitive matching, uses `'/'` to generate path strings. * * Uses {@link PathPosix} for Path objects. */ class PathScurryPosix extends PathScurryBase { /** * separator for generating path strings */ sep = '/'; constructor(cwd = process.cwd(), opts = {}) { const { nocase = false } = opts; super(cwd, node_path_1.posix, '/', { ...opts, nocase }); this.nocase = nocase; } /** * @internal */ parseRootPath(_dir) { return '/'; } /** * @internal */ newRoot(fs) { return new PathPosix(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs }); } /** * Return true if the provided path string is an absolute path */ isAbsolute(p) { return p.startsWith('/'); } } exports.PathScurryPosix = PathScurryPosix; /** * {@link PathScurryBase} implementation for Darwin (macOS) systems. * * Defaults to case-insensitive matching, uses `'/'` for generating path * strings. * * Uses {@link PathPosix} for Path objects. */ class PathScurryDarwin extends PathScurryPosix { constructor(cwd = process.cwd(), opts = {}) { const { nocase = true } = opts; super(cwd, { ...opts, nocase }); } } exports.PathScurryDarwin = PathScurryDarwin; /** * Default {@link PathBase} implementation for the current platform. * * {@link PathWin32} on Windows systems, {@link PathPosix} on all others. */ exports.Path = process.platform === 'win32' ? PathWin32 : PathPosix; /** * Default {@link PathScurryBase} implementation for the current platform. * * {@link PathScurryWin32} on Windows systems, {@link PathScurryDarwin} on * Darwin (macOS) systems, {@link PathScurryPosix} on all others. */ exports.PathScurry = process.platform === 'win32' ? PathScurryWin32 : process.platform === 'darwin' ? PathScurryDarwin : PathScurryPosix; //# sourceMappingURL=index.js.mapPK ~\x!path-scurry/dist/esm/package.jsonnu[{ "type": "module" } PK ~\%@==path-scurry/dist/esm/index.jsnu[import { LRUCache } from 'lru-cache'; import { posix, win32 } from 'node:path'; import { fileURLToPath } from 'node:url'; import { lstatSync, readdir as readdirCB, readdirSync, readlinkSync, realpathSync as rps, } from 'fs'; import * as actualFS from 'node:fs'; const realpathSync = rps.native; // TODO: test perf of fs/promises realpath vs realpathCB, // since the promises one uses realpath.native import { lstat, readdir, readlink, realpath } from 'node:fs/promises'; import { Minipass } from 'minipass'; const defaultFS = { lstatSync, readdir: readdirCB, readdirSync, readlinkSync, realpathSync, promises: { lstat, readdir, readlink, realpath, }, }; // if they just gave us require('fs') then use our default const fsFromOption = (fsOption) => !fsOption || fsOption === defaultFS || fsOption === actualFS ? defaultFS : { ...defaultFS, ...fsOption, promises: { ...defaultFS.promises, ...(fsOption.promises || {}), }, }; // turn something like //?/c:/ into c:\ const uncDriveRegexp = /^\\\\\?\\([a-z]:)\\?$/i; const uncToDrive = (rootPath) => rootPath.replace(/\//g, '\\').replace(uncDriveRegexp, '$1\\'); // windows paths are separated by either / or \ const eitherSep = /[\\\/]/; const UNKNOWN = 0; // may not even exist, for all we know const IFIFO = 0b0001; const IFCHR = 0b0010; const IFDIR = 0b0100; const IFBLK = 0b0110; const IFREG = 0b1000; const IFLNK = 0b1010; const IFSOCK = 0b1100; const IFMT = 0b1111; // mask to unset low 4 bits const IFMT_UNKNOWN = ~IFMT; // set after successfully calling readdir() and getting entries. const READDIR_CALLED = 0b0000_0001_0000; // set after a successful lstat() const LSTAT_CALLED = 0b0000_0010_0000; // set if an entry (or one of its parents) is definitely not a dir const ENOTDIR = 0b0000_0100_0000; // set if an entry (or one of its parents) does not exist // (can also be set on lstat errors like EACCES or ENAMETOOLONG) const ENOENT = 0b0000_1000_0000; // cannot have child entries -- also verify &IFMT is either IFDIR or IFLNK // set if we fail to readlink const ENOREADLINK = 0b0001_0000_0000; // set if we know realpath() will fail const ENOREALPATH = 0b0010_0000_0000; const ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH; const TYPEMASK = 0b0011_1111_1111; const entToType = (s) => s.isFile() ? IFREG : s.isDirectory() ? IFDIR : s.isSymbolicLink() ? IFLNK : s.isCharacterDevice() ? IFCHR : s.isBlockDevice() ? IFBLK : s.isSocket() ? IFSOCK : s.isFIFO() ? IFIFO : UNKNOWN; // normalize unicode path names const normalizeCache = new Map(); const normalize = (s) => { const c = normalizeCache.get(s); if (c) return c; const n = s.normalize('NFKD'); normalizeCache.set(s, n); return n; }; const normalizeNocaseCache = new Map(); const normalizeNocase = (s) => { const c = normalizeNocaseCache.get(s); if (c) return c; const n = normalize(s.toLowerCase()); normalizeNocaseCache.set(s, n); return n; }; /** * An LRUCache for storing resolved path strings or Path objects. * @internal */ export class ResolveCache extends LRUCache { constructor() { super({ max: 256 }); } } // In order to prevent blowing out the js heap by allocating hundreds of // thousands of Path entries when walking extremely large trees, the "children" // in this tree are represented by storing an array of Path entries in an // LRUCache, indexed by the parent. At any time, Path.children() may return an // empty array, indicating that it doesn't know about any of its children, and // thus has to rebuild that cache. This is fine, it just means that we don't // benefit as much from having the cached entries, but huge directory walks // don't blow out the stack, and smaller ones are still as fast as possible. // //It does impose some complexity when building up the readdir data, because we //need to pass a reference to the children array that we started with. /** * an LRUCache for storing child entries. * @internal */ export class ChildrenCache extends LRUCache { constructor(maxSize = 16 * 1024) { super({ maxSize, // parent + children sizeCalculation: a => a.length + 1, }); } } const setAsCwd = Symbol('PathScurry setAsCwd'); /** * Path objects are sort of like a super-powered * {@link https://nodejs.org/docs/latest/api/fs.html#class-fsdirent fs.Dirent} * * Each one represents a single filesystem entry on disk, which may or may not * exist. It includes methods for reading various types of information via * lstat, readlink, and readdir, and caches all information to the greatest * degree possible. * * Note that fs operations that would normally throw will instead return an * "empty" value. This is in order to prevent excessive overhead from error * stack traces. */ export class PathBase { /** * the basename of this path * * **Important**: *always* test the path name against any test string * usingthe {@link isNamed} method, and not by directly comparing this * string. Otherwise, unicode path strings that the system sees as identical * will not be properly treated as the same path, leading to incorrect * behavior and possible security issues. */ name; /** * the Path entry corresponding to the path root. * * @internal */ root; /** * All roots found within the current PathScurry family * * @internal */ roots; /** * a reference to the parent path, or undefined in the case of root entries * * @internal */ parent; /** * boolean indicating whether paths are compared case-insensitively * @internal */ nocase; /** * boolean indicating that this path is the current working directory * of the PathScurry collection that contains it. */ isCWD = false; // potential default fs override #fs; // Stats fields #dev; get dev() { return this.#dev; } #mode; get mode() { return this.#mode; } #nlink; get nlink() { return this.#nlink; } #uid; get uid() { return this.#uid; } #gid; get gid() { return this.#gid; } #rdev; get rdev() { return this.#rdev; } #blksize; get blksize() { return this.#blksize; } #ino; get ino() { return this.#ino; } #size; get size() { return this.#size; } #blocks; get blocks() { return this.#blocks; } #atimeMs; get atimeMs() { return this.#atimeMs; } #mtimeMs; get mtimeMs() { return this.#mtimeMs; } #ctimeMs; get ctimeMs() { return this.#ctimeMs; } #birthtimeMs; get birthtimeMs() { return this.#birthtimeMs; } #atime; get atime() { return this.#atime; } #mtime; get mtime() { return this.#mtime; } #ctime; get ctime() { return this.#ctime; } #birthtime; get birthtime() { return this.#birthtime; } #matchName; #depth; #fullpath; #fullpathPosix; #relative; #relativePosix; #type; #children; #linkTarget; #realpath; /** * This property is for compatibility with the Dirent class as of * Node v20, where Dirent['parentPath'] refers to the path of the * directory that was passed to readdir. For root entries, it's the path * to the entry itself. */ get parentPath() { return (this.parent || this).fullpath(); } /** * Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively, * this property refers to the *parent* path, not the path object itself. */ get path() { return this.parentPath; } /** * Do not create new Path objects directly. They should always be accessed * via the PathScurry class or other methods on the Path class. * * @internal */ constructor(name, type = UNKNOWN, root, roots, nocase, children, opts) { this.name = name; this.#matchName = nocase ? normalizeNocase(name) : normalize(name); this.#type = type & TYPEMASK; this.nocase = nocase; this.roots = roots; this.root = root || this; this.#children = children; this.#fullpath = opts.fullpath; this.#relative = opts.relative; this.#relativePosix = opts.relativePosix; this.parent = opts.parent; if (this.parent) { this.#fs = this.parent.#fs; } else { this.#fs = fsFromOption(opts.fs); } } /** * Returns the depth of the Path object from its root. * * For example, a path at `/foo/bar` would have a depth of 2. */ depth() { if (this.#depth !== undefined) return this.#depth; if (!this.parent) return (this.#depth = 0); return (this.#depth = this.parent.depth() + 1); } /** * @internal */ childrenCache() { return this.#children; } /** * Get the Path object referenced by the string path, resolved from this Path */ resolve(path) { if (!path) { return this; } const rootPath = this.getRootString(path); const dir = path.substring(rootPath.length); const dirParts = dir.split(this.splitSep); const result = rootPath ? this.getRoot(rootPath).#resolveParts(dirParts) : this.#resolveParts(dirParts); return result; } #resolveParts(dirParts) { let p = this; for (const part of dirParts) { p = p.child(part); } return p; } /** * Returns the cached children Path objects, if still available. If they * have fallen out of the cache, then returns an empty array, and resets the * READDIR_CALLED bit, so that future calls to readdir() will require an fs * lookup. * * @internal */ children() { const cached = this.#children.get(this); if (cached) { return cached; } const children = Object.assign([], { provisional: 0 }); this.#children.set(this, children); this.#type &= ~READDIR_CALLED; return children; } /** * Resolves a path portion and returns or creates the child Path. * * Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is * `'..'`. * * This should not be called directly. If `pathPart` contains any path * separators, it will lead to unsafe undefined behavior. * * Use `Path.resolve()` instead. * * @internal */ child(pathPart, opts) { if (pathPart === '' || pathPart === '.') { return this; } if (pathPart === '..') { return this.parent || this; } // find the child const children = this.children(); const name = this.nocase ? normalizeNocase(pathPart) : normalize(pathPart); for (const p of children) { if (p.#matchName === name) { return p; } } // didn't find it, create provisional child, since it might not // actually exist. If we know the parent isn't a dir, then // in fact it CAN'T exist. const s = this.parent ? this.sep : ''; const fullpath = this.#fullpath ? this.#fullpath + s + pathPart : undefined; const pchild = this.newChild(pathPart, UNKNOWN, { ...opts, parent: this, fullpath, }); if (!this.canReaddir()) { pchild.#type |= ENOENT; } // don't have to update provisional, because if we have real children, // then provisional is set to children.length, otherwise a lower number children.push(pchild); return pchild; } /** * The relative path from the cwd. If it does not share an ancestor with * the cwd, then this ends up being equivalent to the fullpath() */ relative() { if (this.isCWD) return ''; if (this.#relative !== undefined) { return this.#relative; } const name = this.name; const p = this.parent; if (!p) { return (this.#relative = this.name); } const pv = p.relative(); return pv + (!pv || !p.parent ? '' : this.sep) + name; } /** * The relative path from the cwd, using / as the path separator. * If it does not share an ancestor with * the cwd, then this ends up being equivalent to the fullpathPosix() * On posix systems, this is identical to relative(). */ relativePosix() { if (this.sep === '/') return this.relative(); if (this.isCWD) return ''; if (this.#relativePosix !== undefined) return this.#relativePosix; const name = this.name; const p = this.parent; if (!p) { return (this.#relativePosix = this.fullpathPosix()); } const pv = p.relativePosix(); return pv + (!pv || !p.parent ? '' : '/') + name; } /** * The fully resolved path string for this Path entry */ fullpath() { if (this.#fullpath !== undefined) { return this.#fullpath; } const name = this.name; const p = this.parent; if (!p) { return (this.#fullpath = this.name); } const pv = p.fullpath(); const fp = pv + (!p.parent ? '' : this.sep) + name; return (this.#fullpath = fp); } /** * On platforms other than windows, this is identical to fullpath. * * On windows, this is overridden to return the forward-slash form of the * full UNC path. */ fullpathPosix() { if (this.#fullpathPosix !== undefined) return this.#fullpathPosix; if (this.sep === '/') return (this.#fullpathPosix = this.fullpath()); if (!this.parent) { const p = this.fullpath().replace(/\\/g, '/'); if (/^[a-z]:\//i.test(p)) { return (this.#fullpathPosix = `//?/${p}`); } else { return (this.#fullpathPosix = p); } } const p = this.parent; const pfpp = p.fullpathPosix(); const fpp = pfpp + (!pfpp || !p.parent ? '' : '/') + this.name; return (this.#fullpathPosix = fpp); } /** * Is the Path of an unknown type? * * Note that we might know *something* about it if there has been a previous * filesystem operation, for example that it does not exist, or is not a * link, or whether it has child entries. */ isUnknown() { return (this.#type & IFMT) === UNKNOWN; } isType(type) { return this[`is${type}`](); } getType() { return (this.isUnknown() ? 'Unknown' : this.isDirectory() ? 'Directory' : this.isFile() ? 'File' : this.isSymbolicLink() ? 'SymbolicLink' : this.isFIFO() ? 'FIFO' : this.isCharacterDevice() ? 'CharacterDevice' : this.isBlockDevice() ? 'BlockDevice' : /* c8 ignore start */ this.isSocket() ? 'Socket' : 'Unknown'); /* c8 ignore stop */ } /** * Is the Path a regular file? */ isFile() { return (this.#type & IFMT) === IFREG; } /** * Is the Path a directory? */ isDirectory() { return (this.#type & IFMT) === IFDIR; } /** * Is the path a character device? */ isCharacterDevice() { return (this.#type & IFMT) === IFCHR; } /** * Is the path a block device? */ isBlockDevice() { return (this.#type & IFMT) === IFBLK; } /** * Is the path a FIFO pipe? */ isFIFO() { return (this.#type & IFMT) === IFIFO; } /** * Is the path a socket? */ isSocket() { return (this.#type & IFMT) === IFSOCK; } /** * Is the path a symbolic link? */ isSymbolicLink() { return (this.#type & IFLNK) === IFLNK; } /** * Return the entry if it has been subject of a successful lstat, or * undefined otherwise. * * Does not read the filesystem, so an undefined result *could* simply * mean that we haven't called lstat on it. */ lstatCached() { return this.#type & LSTAT_CALLED ? this : undefined; } /** * Return the cached link target if the entry has been the subject of a * successful readlink, or undefined otherwise. * * Does not read the filesystem, so an undefined result *could* just mean we * don't have any cached data. Only use it if you are very sure that a * readlink() has been called at some point. */ readlinkCached() { return this.#linkTarget; } /** * Returns the cached realpath target if the entry has been the subject * of a successful realpath, or undefined otherwise. * * Does not read the filesystem, so an undefined result *could* just mean we * don't have any cached data. Only use it if you are very sure that a * realpath() has been called at some point. */ realpathCached() { return this.#realpath; } /** * Returns the cached child Path entries array if the entry has been the * subject of a successful readdir(), or [] otherwise. * * Does not read the filesystem, so an empty array *could* just mean we * don't have any cached data. Only use it if you are very sure that a * readdir() has been called recently enough to still be valid. */ readdirCached() { const children = this.children(); return children.slice(0, children.provisional); } /** * Return true if it's worth trying to readlink. Ie, we don't (yet) have * any indication that readlink will definitely fail. * * Returns false if the path is known to not be a symlink, if a previous * readlink failed, or if the entry does not exist. */ canReadlink() { if (this.#linkTarget) return true; if (!this.parent) return false; // cases where it cannot possibly succeed const ifmt = this.#type & IFMT; return !((ifmt !== UNKNOWN && ifmt !== IFLNK) || this.#type & ENOREADLINK || this.#type & ENOENT); } /** * Return true if readdir has previously been successfully called on this * path, indicating that cachedReaddir() is likely valid. */ calledReaddir() { return !!(this.#type & READDIR_CALLED); } /** * Returns true if the path is known to not exist. That is, a previous lstat * or readdir failed to verify its existence when that would have been * expected, or a parent entry was marked either enoent or enotdir. */ isENOENT() { return !!(this.#type & ENOENT); } /** * Return true if the path is a match for the given path name. This handles * case sensitivity and unicode normalization. * * Note: even on case-sensitive systems, it is **not** safe to test the * equality of the `.name` property to determine whether a given pathname * matches, due to unicode normalization mismatches. * * Always use this method instead of testing the `path.name` property * directly. */ isNamed(n) { return !this.nocase ? this.#matchName === normalize(n) : this.#matchName === normalizeNocase(n); } /** * Return the Path object corresponding to the target of a symbolic link. * * If the Path is not a symbolic link, or if the readlink call fails for any * reason, `undefined` is returned. * * Result is cached, and thus may be outdated if the filesystem is mutated. */ async readlink() { const target = this.#linkTarget; if (target) { return target; } if (!this.canReadlink()) { return undefined; } /* c8 ignore start */ // already covered by the canReadlink test, here for ts grumples if (!this.parent) { return undefined; } /* c8 ignore stop */ try { const read = await this.#fs.promises.readlink(this.fullpath()); const linkTarget = (await this.parent.realpath())?.resolve(read); if (linkTarget) { return (this.#linkTarget = linkTarget); } } catch (er) { this.#readlinkFail(er.code); return undefined; } } /** * Synchronous {@link PathBase.readlink} */ readlinkSync() { const target = this.#linkTarget; if (target) { return target; } if (!this.canReadlink()) { return undefined; } /* c8 ignore start */ // already covered by the canReadlink test, here for ts grumples if (!this.parent) { return undefined; } /* c8 ignore stop */ try { const read = this.#fs.readlinkSync(this.fullpath()); const linkTarget = this.parent.realpathSync()?.resolve(read); if (linkTarget) { return (this.#linkTarget = linkTarget); } } catch (er) { this.#readlinkFail(er.code); return undefined; } } #readdirSuccess(children) { // succeeded, mark readdir called bit this.#type |= READDIR_CALLED; // mark all remaining provisional children as ENOENT for (let p = children.provisional; p < children.length; p++) { const c = children[p]; if (c) c.#markENOENT(); } } #markENOENT() { // mark as UNKNOWN and ENOENT if (this.#type & ENOENT) return; this.#type = (this.#type | ENOENT) & IFMT_UNKNOWN; this.#markChildrenENOENT(); } #markChildrenENOENT() { // all children are provisional and do not exist const children = this.children(); children.provisional = 0; for (const p of children) { p.#markENOENT(); } } #markENOREALPATH() { this.#type |= ENOREALPATH; this.#markENOTDIR(); } // save the information when we know the entry is not a dir #markENOTDIR() { // entry is not a directory, so any children can't exist. // this *should* be impossible, since any children created // after it's been marked ENOTDIR should be marked ENOENT, // so it won't even get to this point. /* c8 ignore start */ if (this.#type & ENOTDIR) return; /* c8 ignore stop */ let t = this.#type; // this could happen if we stat a dir, then delete it, // then try to read it or one of its children. if ((t & IFMT) === IFDIR) t &= IFMT_UNKNOWN; this.#type = t | ENOTDIR; this.#markChildrenENOENT(); } #readdirFail(code = '') { // markENOTDIR and markENOENT also set provisional=0 if (code === 'ENOTDIR' || code === 'EPERM') { this.#markENOTDIR(); } else if (code === 'ENOENT') { this.#markENOENT(); } else { this.children().provisional = 0; } } #lstatFail(code = '') { // Windows just raises ENOENT in this case, disable for win CI /* c8 ignore start */ if (code === 'ENOTDIR') { // already know it has a parent by this point const p = this.parent; p.#markENOTDIR(); } else if (code === 'ENOENT') { /* c8 ignore stop */ this.#markENOENT(); } } #readlinkFail(code = '') { let ter = this.#type; ter |= ENOREADLINK; if (code === 'ENOENT') ter |= ENOENT; // windows gets a weird error when you try to readlink a file if (code === 'EINVAL' || code === 'UNKNOWN') { // exists, but not a symlink, we don't know WHAT it is, so remove // all IFMT bits. ter &= IFMT_UNKNOWN; } this.#type = ter; // windows just gets ENOENT in this case. We do cover the case, // just disabled because it's impossible on Windows CI /* c8 ignore start */ if (code === 'ENOTDIR' && this.parent) { this.parent.#markENOTDIR(); } /* c8 ignore stop */ } #readdirAddChild(e, c) { return (this.#readdirMaybePromoteChild(e, c) || this.#readdirAddNewChild(e, c)); } #readdirAddNewChild(e, c) { // alloc new entry at head, so it's never provisional const type = entToType(e); const child = this.newChild(e.name, type, { parent: this }); const ifmt = child.#type & IFMT; if (ifmt !== IFDIR && ifmt !== IFLNK && ifmt !== UNKNOWN) { child.#type |= ENOTDIR; } c.unshift(child); c.provisional++; return child; } #readdirMaybePromoteChild(e, c) { for (let p = c.provisional; p < c.length; p++) { const pchild = c[p]; const name = this.nocase ? normalizeNocase(e.name) : normalize(e.name); if (name !== pchild.#matchName) { continue; } return this.#readdirPromoteChild(e, pchild, p, c); } } #readdirPromoteChild(e, p, index, c) { const v = p.name; // retain any other flags, but set ifmt from dirent p.#type = (p.#type & IFMT_UNKNOWN) | entToType(e); // case sensitivity fixing when we learn the true name. if (v !== e.name) p.name = e.name; // just advance provisional index (potentially off the list), // otherwise we have to splice/pop it out and re-insert at head if (index !== c.provisional) { if (index === c.length - 1) c.pop(); else c.splice(index, 1); c.unshift(p); } c.provisional++; return p; } /** * Call lstat() on this Path, and update all known information that can be * determined. * * Note that unlike `fs.lstat()`, the returned value does not contain some * information, such as `mode`, `dev`, `nlink`, and `ino`. If that * information is required, you will need to call `fs.lstat` yourself. * * If the Path refers to a nonexistent file, or if the lstat call fails for * any reason, `undefined` is returned. Otherwise the updated Path object is * returned. * * Results are cached, and thus may be out of date if the filesystem is * mutated. */ async lstat() { if ((this.#type & ENOENT) === 0) { try { this.#applyStat(await this.#fs.promises.lstat(this.fullpath())); return this; } catch (er) { this.#lstatFail(er.code); } } } /** * synchronous {@link PathBase.lstat} */ lstatSync() { if ((this.#type & ENOENT) === 0) { try { this.#applyStat(this.#fs.lstatSync(this.fullpath())); return this; } catch (er) { this.#lstatFail(er.code); } } } #applyStat(st) { const { atime, atimeMs, birthtime, birthtimeMs, blksize, blocks, ctime, ctimeMs, dev, gid, ino, mode, mtime, mtimeMs, nlink, rdev, size, uid, } = st; this.#atime = atime; this.#atimeMs = atimeMs; this.#birthtime = birthtime; this.#birthtimeMs = birthtimeMs; this.#blksize = blksize; this.#blocks = blocks; this.#ctime = ctime; this.#ctimeMs = ctimeMs; this.#dev = dev; this.#gid = gid; this.#ino = ino; this.#mode = mode; this.#mtime = mtime; this.#mtimeMs = mtimeMs; this.#nlink = nlink; this.#rdev = rdev; this.#size = size; this.#uid = uid; const ifmt = entToType(st); // retain any other flags, but set the ifmt this.#type = (this.#type & IFMT_UNKNOWN) | ifmt | LSTAT_CALLED; if (ifmt !== UNKNOWN && ifmt !== IFDIR && ifmt !== IFLNK) { this.#type |= ENOTDIR; } } #onReaddirCB = []; #readdirCBInFlight = false; #callOnReaddirCB(children) { this.#readdirCBInFlight = false; const cbs = this.#onReaddirCB.slice(); this.#onReaddirCB.length = 0; cbs.forEach(cb => cb(null, children)); } /** * Standard node-style callback interface to get list of directory entries. * * If the Path cannot or does not contain any children, then an empty array * is returned. * * Results are cached, and thus may be out of date if the filesystem is * mutated. * * @param cb The callback called with (er, entries). Note that the `er` * param is somewhat extraneous, as all readdir() errors are handled and * simply result in an empty set of entries being returned. * @param allowZalgo Boolean indicating that immediately known results should * *not* be deferred with `queueMicrotask`. Defaults to `false`. Release * zalgo at your peril, the dark pony lord is devious and unforgiving. */ readdirCB(cb, allowZalgo = false) { if (!this.canReaddir()) { if (allowZalgo) cb(null, []); else queueMicrotask(() => cb(null, [])); return; } const children = this.children(); if (this.calledReaddir()) { const c = children.slice(0, children.provisional); if (allowZalgo) cb(null, c); else queueMicrotask(() => cb(null, c)); return; } // don't have to worry about zalgo at this point. this.#onReaddirCB.push(cb); if (this.#readdirCBInFlight) { return; } this.#readdirCBInFlight = true; // else read the directory, fill up children // de-provisionalize any provisional children. const fullpath = this.fullpath(); this.#fs.readdir(fullpath, { withFileTypes: true }, (er, entries) => { if (er) { this.#readdirFail(er.code); children.provisional = 0; } else { // if we didn't get an error, we always get entries. //@ts-ignore for (const e of entries) { this.#readdirAddChild(e, children); } this.#readdirSuccess(children); } this.#callOnReaddirCB(children.slice(0, children.provisional)); return; }); } #asyncReaddirInFlight; /** * Return an array of known child entries. * * If the Path cannot or does not contain any children, then an empty array * is returned. * * Results are cached, and thus may be out of date if the filesystem is * mutated. */ async readdir() { if (!this.canReaddir()) { return []; } const children = this.children(); if (this.calledReaddir()) { return children.slice(0, children.provisional); } // else read the directory, fill up children // de-provisionalize any provisional children. const fullpath = this.fullpath(); if (this.#asyncReaddirInFlight) { await this.#asyncReaddirInFlight; } else { /* c8 ignore start */ let resolve = () => { }; /* c8 ignore stop */ this.#asyncReaddirInFlight = new Promise(res => (resolve = res)); try { for (const e of await this.#fs.promises.readdir(fullpath, { withFileTypes: true, })) { this.#readdirAddChild(e, children); } this.#readdirSuccess(children); } catch (er) { this.#readdirFail(er.code); children.provisional = 0; } this.#asyncReaddirInFlight = undefined; resolve(); } return children.slice(0, children.provisional); } /** * synchronous {@link PathBase.readdir} */ readdirSync() { if (!this.canReaddir()) { return []; } const children = this.children(); if (this.calledReaddir()) { return children.slice(0, children.provisional); } // else read the directory, fill up children // de-provisionalize any provisional children. const fullpath = this.fullpath(); try { for (const e of this.#fs.readdirSync(fullpath, { withFileTypes: true, })) { this.#readdirAddChild(e, children); } this.#readdirSuccess(children); } catch (er) { this.#readdirFail(er.code); children.provisional = 0; } return children.slice(0, children.provisional); } canReaddir() { if (this.#type & ENOCHILD) return false; const ifmt = IFMT & this.#type; // we always set ENOTDIR when setting IFMT, so should be impossible /* c8 ignore start */ if (!(ifmt === UNKNOWN || ifmt === IFDIR || ifmt === IFLNK)) { return false; } /* c8 ignore stop */ return true; } shouldWalk(dirs, walkFilter) { return ((this.#type & IFDIR) === IFDIR && !(this.#type & ENOCHILD) && !dirs.has(this) && (!walkFilter || walkFilter(this))); } /** * Return the Path object corresponding to path as resolved * by realpath(3). * * If the realpath call fails for any reason, `undefined` is returned. * * Result is cached, and thus may be outdated if the filesystem is mutated. * On success, returns a Path object. */ async realpath() { if (this.#realpath) return this.#realpath; if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined; try { const rp = await this.#fs.promises.realpath(this.fullpath()); return (this.#realpath = this.resolve(rp)); } catch (_) { this.#markENOREALPATH(); } } /** * Synchronous {@link realpath} */ realpathSync() { if (this.#realpath) return this.#realpath; if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined; try { const rp = this.#fs.realpathSync(this.fullpath()); return (this.#realpath = this.resolve(rp)); } catch (_) { this.#markENOREALPATH(); } } /** * Internal method to mark this Path object as the scurry cwd, * called by {@link PathScurry#chdir} * * @internal */ [setAsCwd](oldCwd) { if (oldCwd === this) return; oldCwd.isCWD = false; this.isCWD = true; const changed = new Set([]); let rp = []; let p = this; while (p && p.parent) { changed.add(p); p.#relative = rp.join(this.sep); p.#relativePosix = rp.join('/'); p = p.parent; rp.push('..'); } // now un-memoize parents of old cwd p = oldCwd; while (p && p.parent && !changed.has(p)) { p.#relative = undefined; p.#relativePosix = undefined; p = p.parent; } } } /** * Path class used on win32 systems * * Uses `'\\'` as the path separator for returned paths, either `'\\'` or `'/'` * as the path separator for parsing paths. */ export class PathWin32 extends PathBase { /** * Separator for generating path strings. */ sep = '\\'; /** * Separator for parsing path strings. */ splitSep = eitherSep; /** * Do not create new Path objects directly. They should always be accessed * via the PathScurry class or other methods on the Path class. * * @internal */ constructor(name, type = UNKNOWN, root, roots, nocase, children, opts) { super(name, type, root, roots, nocase, children, opts); } /** * @internal */ newChild(name, type = UNKNOWN, opts = {}) { return new PathWin32(name, type, this.root, this.roots, this.nocase, this.childrenCache(), opts); } /** * @internal */ getRootString(path) { return win32.parse(path).root; } /** * @internal */ getRoot(rootPath) { rootPath = uncToDrive(rootPath.toUpperCase()); if (rootPath === this.root.name) { return this.root; } // ok, not that one, check if it matches another we know about for (const [compare, root] of Object.entries(this.roots)) { if (this.sameRoot(rootPath, compare)) { return (this.roots[rootPath] = root); } } // otherwise, have to create a new one. return (this.roots[rootPath] = new PathScurryWin32(rootPath, this).root); } /** * @internal */ sameRoot(rootPath, compare = this.root.name) { // windows can (rarely) have case-sensitive filesystem, but // UNC and drive letters are always case-insensitive, and canonically // represented uppercase. rootPath = rootPath .toUpperCase() .replace(/\//g, '\\') .replace(uncDriveRegexp, '$1\\'); return rootPath === compare; } } /** * Path class used on all posix systems. * * Uses `'/'` as the path separator. */ export class PathPosix extends PathBase { /** * separator for parsing path strings */ splitSep = '/'; /** * separator for generating path strings */ sep = '/'; /** * Do not create new Path objects directly. They should always be accessed * via the PathScurry class or other methods on the Path class. * * @internal */ constructor(name, type = UNKNOWN, root, roots, nocase, children, opts) { super(name, type, root, roots, nocase, children, opts); } /** * @internal */ getRootString(path) { return path.startsWith('/') ? '/' : ''; } /** * @internal */ getRoot(_rootPath) { return this.root; } /** * @internal */ newChild(name, type = UNKNOWN, opts = {}) { return new PathPosix(name, type, this.root, this.roots, this.nocase, this.childrenCache(), opts); } } /** * The base class for all PathScurry classes, providing the interface for path * resolution and filesystem operations. * * Typically, you should *not* instantiate this class directly, but rather one * of the platform-specific classes, or the exported {@link PathScurry} which * defaults to the current platform. */ export class PathScurryBase { /** * The root Path entry for the current working directory of this Scurry */ root; /** * The string path for the root of this Scurry's current working directory */ rootPath; /** * A collection of all roots encountered, referenced by rootPath */ roots; /** * The Path entry corresponding to this PathScurry's current working directory. */ cwd; #resolveCache; #resolvePosixCache; #children; /** * Perform path comparisons case-insensitively. * * Defaults true on Darwin and Windows systems, false elsewhere. */ nocase; #fs; /** * This class should not be instantiated directly. * * Use PathScurryWin32, PathScurryDarwin, PathScurryPosix, or PathScurry * * @internal */ constructor(cwd = process.cwd(), pathImpl, sep, { nocase, childrenCacheSize = 16 * 1024, fs = defaultFS, } = {}) { this.#fs = fsFromOption(fs); if (cwd instanceof URL || cwd.startsWith('file://')) { cwd = fileURLToPath(cwd); } // resolve and split root, and then add to the store. // this is the only time we call path.resolve() const cwdPath = pathImpl.resolve(cwd); this.roots = Object.create(null); this.rootPath = this.parseRootPath(cwdPath); this.#resolveCache = new ResolveCache(); this.#resolvePosixCache = new ResolveCache(); this.#children = new ChildrenCache(childrenCacheSize); const split = cwdPath.substring(this.rootPath.length).split(sep); // resolve('/') leaves '', splits to [''], we don't want that. if (split.length === 1 && !split[0]) { split.pop(); } /* c8 ignore start */ if (nocase === undefined) { throw new TypeError('must provide nocase setting to PathScurryBase ctor'); } /* c8 ignore stop */ this.nocase = nocase; this.root = this.newRoot(this.#fs); this.roots[this.rootPath] = this.root; let prev = this.root; let len = split.length - 1; const joinSep = pathImpl.sep; let abs = this.rootPath; let sawFirst = false; for (const part of split) { const l = len--; prev = prev.child(part, { relative: new Array(l).fill('..').join(joinSep), relativePosix: new Array(l).fill('..').join('/'), fullpath: (abs += (sawFirst ? '' : joinSep) + part), }); sawFirst = true; } this.cwd = prev; } /** * Get the depth of a provided path, string, or the cwd */ depth(path = this.cwd) { if (typeof path === 'string') { path = this.cwd.resolve(path); } return path.depth(); } /** * Return the cache of child entries. Exposed so subclasses can create * child Path objects in a platform-specific way. * * @internal */ childrenCache() { return this.#children; } /** * Resolve one or more path strings to a resolved string * * Same interface as require('path').resolve. * * Much faster than path.resolve() when called multiple times for the same * path, because the resolved Path objects are cached. Much slower * otherwise. */ resolve(...paths) { // first figure out the minimum number of paths we have to test // we always start at cwd, but any absolutes will bump the start let r = ''; for (let i = paths.length - 1; i >= 0; i--) { const p = paths[i]; if (!p || p === '.') continue; r = r ? `${p}/${r}` : p; if (this.isAbsolute(p)) { break; } } const cached = this.#resolveCache.get(r); if (cached !== undefined) { return cached; } const result = this.cwd.resolve(r).fullpath(); this.#resolveCache.set(r, result); return result; } /** * Resolve one or more path strings to a resolved string, returning * the posix path. Identical to .resolve() on posix systems, but on * windows will return a forward-slash separated UNC path. * * Same interface as require('path').resolve. * * Much faster than path.resolve() when called multiple times for the same * path, because the resolved Path objects are cached. Much slower * otherwise. */ resolvePosix(...paths) { // first figure out the minimum number of paths we have to test // we always start at cwd, but any absolutes will bump the start let r = ''; for (let i = paths.length - 1; i >= 0; i--) { const p = paths[i]; if (!p || p === '.') continue; r = r ? `${p}/${r}` : p; if (this.isAbsolute(p)) { break; } } const cached = this.#resolvePosixCache.get(r); if (cached !== undefined) { return cached; } const result = this.cwd.resolve(r).fullpathPosix(); this.#resolvePosixCache.set(r, result); return result; } /** * find the relative path from the cwd to the supplied path string or entry */ relative(entry = this.cwd) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } return entry.relative(); } /** * find the relative path from the cwd to the supplied path string or * entry, using / as the path delimiter, even on Windows. */ relativePosix(entry = this.cwd) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } return entry.relativePosix(); } /** * Return the basename for the provided string or Path object */ basename(entry = this.cwd) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } return entry.name; } /** * Return the dirname for the provided string or Path object */ dirname(entry = this.cwd) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } return (entry.parent || entry).fullpath(); } async readdir(entry = this.cwd, opts = { withFileTypes: true, }) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } else if (!(entry instanceof PathBase)) { opts = entry; entry = this.cwd; } const { withFileTypes } = opts; if (!entry.canReaddir()) { return []; } else { const p = await entry.readdir(); return withFileTypes ? p : p.map(e => e.name); } } readdirSync(entry = this.cwd, opts = { withFileTypes: true, }) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } else if (!(entry instanceof PathBase)) { opts = entry; entry = this.cwd; } const { withFileTypes = true } = opts; if (!entry.canReaddir()) { return []; } else if (withFileTypes) { return entry.readdirSync(); } else { return entry.readdirSync().map(e => e.name); } } /** * Call lstat() on the string or Path object, and update all known * information that can be determined. * * Note that unlike `fs.lstat()`, the returned value does not contain some * information, such as `mode`, `dev`, `nlink`, and `ino`. If that * information is required, you will need to call `fs.lstat` yourself. * * If the Path refers to a nonexistent file, or if the lstat call fails for * any reason, `undefined` is returned. Otherwise the updated Path object is * returned. * * Results are cached, and thus may be out of date if the filesystem is * mutated. */ async lstat(entry = this.cwd) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } return entry.lstat(); } /** * synchronous {@link PathScurryBase.lstat} */ lstatSync(entry = this.cwd) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } return entry.lstatSync(); } async readlink(entry = this.cwd, { withFileTypes } = { withFileTypes: false, }) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } else if (!(entry instanceof PathBase)) { withFileTypes = entry.withFileTypes; entry = this.cwd; } const e = await entry.readlink(); return withFileTypes ? e : e?.fullpath(); } readlinkSync(entry = this.cwd, { withFileTypes } = { withFileTypes: false, }) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } else if (!(entry instanceof PathBase)) { withFileTypes = entry.withFileTypes; entry = this.cwd; } const e = entry.readlinkSync(); return withFileTypes ? e : e?.fullpath(); } async realpath(entry = this.cwd, { withFileTypes } = { withFileTypes: false, }) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } else if (!(entry instanceof PathBase)) { withFileTypes = entry.withFileTypes; entry = this.cwd; } const e = await entry.realpath(); return withFileTypes ? e : e?.fullpath(); } realpathSync(entry = this.cwd, { withFileTypes } = { withFileTypes: false, }) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } else if (!(entry instanceof PathBase)) { withFileTypes = entry.withFileTypes; entry = this.cwd; } const e = entry.realpathSync(); return withFileTypes ? e : e?.fullpath(); } async walk(entry = this.cwd, opts = {}) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } else if (!(entry instanceof PathBase)) { opts = entry; entry = this.cwd; } const { withFileTypes = true, follow = false, filter, walkFilter, } = opts; const results = []; if (!filter || filter(entry)) { results.push(withFileTypes ? entry : entry.fullpath()); } const dirs = new Set(); const walk = (dir, cb) => { dirs.add(dir); dir.readdirCB((er, entries) => { /* c8 ignore start */ if (er) { return cb(er); } /* c8 ignore stop */ let len = entries.length; if (!len) return cb(); const next = () => { if (--len === 0) { cb(); } }; for (const e of entries) { if (!filter || filter(e)) { results.push(withFileTypes ? e : e.fullpath()); } if (follow && e.isSymbolicLink()) { e.realpath() .then(r => (r?.isUnknown() ? r.lstat() : r)) .then(r => r?.shouldWalk(dirs, walkFilter) ? walk(r, next) : next()); } else { if (e.shouldWalk(dirs, walkFilter)) { walk(e, next); } else { next(); } } } }, true); // zalgooooooo }; const start = entry; return new Promise((res, rej) => { walk(start, er => { /* c8 ignore start */ if (er) return rej(er); /* c8 ignore stop */ res(results); }); }); } walkSync(entry = this.cwd, opts = {}) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } else if (!(entry instanceof PathBase)) { opts = entry; entry = this.cwd; } const { withFileTypes = true, follow = false, filter, walkFilter, } = opts; const results = []; if (!filter || filter(entry)) { results.push(withFileTypes ? entry : entry.fullpath()); } const dirs = new Set([entry]); for (const dir of dirs) { const entries = dir.readdirSync(); for (const e of entries) { if (!filter || filter(e)) { results.push(withFileTypes ? e : e.fullpath()); } let r = e; if (e.isSymbolicLink()) { if (!(follow && (r = e.realpathSync()))) continue; if (r.isUnknown()) r.lstatSync(); } if (r.shouldWalk(dirs, walkFilter)) { dirs.add(r); } } } return results; } /** * Support for `for await` * * Alias for {@link PathScurryBase.iterate} * * Note: As of Node 19, this is very slow, compared to other methods of * walking. Consider using {@link PathScurryBase.stream} if memory overhead * and backpressure are concerns, or {@link PathScurryBase.walk} if not. */ [Symbol.asyncIterator]() { return this.iterate(); } iterate(entry = this.cwd, options = {}) { // iterating async over the stream is significantly more performant, // especially in the warm-cache scenario, because it buffers up directory // entries in the background instead of waiting for a yield for each one. if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } else if (!(entry instanceof PathBase)) { options = entry; entry = this.cwd; } return this.stream(entry, options)[Symbol.asyncIterator](); } /** * Iterating over a PathScurry performs a synchronous walk. * * Alias for {@link PathScurryBase.iterateSync} */ [Symbol.iterator]() { return this.iterateSync(); } *iterateSync(entry = this.cwd, opts = {}) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } else if (!(entry instanceof PathBase)) { opts = entry; entry = this.cwd; } const { withFileTypes = true, follow = false, filter, walkFilter, } = opts; if (!filter || filter(entry)) { yield withFileTypes ? entry : entry.fullpath(); } const dirs = new Set([entry]); for (const dir of dirs) { const entries = dir.readdirSync(); for (const e of entries) { if (!filter || filter(e)) { yield withFileTypes ? e : e.fullpath(); } let r = e; if (e.isSymbolicLink()) { if (!(follow && (r = e.realpathSync()))) continue; if (r.isUnknown()) r.lstatSync(); } if (r.shouldWalk(dirs, walkFilter)) { dirs.add(r); } } } } stream(entry = this.cwd, opts = {}) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } else if (!(entry instanceof PathBase)) { opts = entry; entry = this.cwd; } const { withFileTypes = true, follow = false, filter, walkFilter, } = opts; const results = new Minipass({ objectMode: true }); if (!filter || filter(entry)) { results.write(withFileTypes ? entry : entry.fullpath()); } const dirs = new Set(); const queue = [entry]; let processing = 0; const process = () => { let paused = false; while (!paused) { const dir = queue.shift(); if (!dir) { if (processing === 0) results.end(); return; } processing++; dirs.add(dir); const onReaddir = (er, entries, didRealpaths = false) => { /* c8 ignore start */ if (er) return results.emit('error', er); /* c8 ignore stop */ if (follow && !didRealpaths) { const promises = []; for (const e of entries) { if (e.isSymbolicLink()) { promises.push(e .realpath() .then((r) => r?.isUnknown() ? r.lstat() : r)); } } if (promises.length) { Promise.all(promises).then(() => onReaddir(null, entries, true)); return; } } for (const e of entries) { if (e && (!filter || filter(e))) { if (!results.write(withFileTypes ? e : e.fullpath())) { paused = true; } } } processing--; for (const e of entries) { const r = e.realpathCached() || e; if (r.shouldWalk(dirs, walkFilter)) { queue.push(r); } } if (paused && !results.flowing) { results.once('drain', process); } else if (!sync) { process(); } }; // zalgo containment let sync = true; dir.readdirCB(onReaddir, true); sync = false; } }; process(); return results; } streamSync(entry = this.cwd, opts = {}) { if (typeof entry === 'string') { entry = this.cwd.resolve(entry); } else if (!(entry instanceof PathBase)) { opts = entry; entry = this.cwd; } const { withFileTypes = true, follow = false, filter, walkFilter, } = opts; const results = new Minipass({ objectMode: true }); const dirs = new Set(); if (!filter || filter(entry)) { results.write(withFileTypes ? entry : entry.fullpath()); } const queue = [entry]; let processing = 0; const process = () => { let paused = false; while (!paused) { const dir = queue.shift(); if (!dir) { if (processing === 0) results.end(); return; } processing++; dirs.add(dir); const entries = dir.readdirSync(); for (const e of entries) { if (!filter || filter(e)) { if (!results.write(withFileTypes ? e : e.fullpath())) { paused = true; } } } processing--; for (const e of entries) { let r = e; if (e.isSymbolicLink()) { if (!(follow && (r = e.realpathSync()))) continue; if (r.isUnknown()) r.lstatSync(); } if (r.shouldWalk(dirs, walkFilter)) { queue.push(r); } } } if (paused && !results.flowing) results.once('drain', process); }; process(); return results; } chdir(path = this.cwd) { const oldCwd = this.cwd; this.cwd = typeof path === 'string' ? this.cwd.resolve(path) : path; this.cwd[setAsCwd](oldCwd); } } /** * Windows implementation of {@link PathScurryBase} * * Defaults to case insensitve, uses `'\\'` to generate path strings. Uses * {@link PathWin32} for Path objects. */ export class PathScurryWin32 extends PathScurryBase { /** * separator for generating path strings */ sep = '\\'; constructor(cwd = process.cwd(), opts = {}) { const { nocase = true } = opts; super(cwd, win32, '\\', { ...opts, nocase }); this.nocase = nocase; for (let p = this.cwd; p; p = p.parent) { p.nocase = this.nocase; } } /** * @internal */ parseRootPath(dir) { // if the path starts with a single separator, it's not a UNC, and we'll // just get separator as the root, and driveFromUNC will return \ // In that case, mount \ on the root from the cwd. return win32.parse(dir).root.toUpperCase(); } /** * @internal */ newRoot(fs) { return new PathWin32(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs }); } /** * Return true if the provided path string is an absolute path */ isAbsolute(p) { return (p.startsWith('/') || p.startsWith('\\') || /^[a-z]:(\/|\\)/i.test(p)); } } /** * {@link PathScurryBase} implementation for all posix systems other than Darwin. * * Defaults to case-sensitive matching, uses `'/'` to generate path strings. * * Uses {@link PathPosix} for Path objects. */ export class PathScurryPosix extends PathScurryBase { /** * separator for generating path strings */ sep = '/'; constructor(cwd = process.cwd(), opts = {}) { const { nocase = false } = opts; super(cwd, posix, '/', { ...opts, nocase }); this.nocase = nocase; } /** * @internal */ parseRootPath(_dir) { return '/'; } /** * @internal */ newRoot(fs) { return new PathPosix(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs }); } /** * Return true if the provided path string is an absolute path */ isAbsolute(p) { return p.startsWith('/'); } } /** * {@link PathScurryBase} implementation for Darwin (macOS) systems. * * Defaults to case-insensitive matching, uses `'/'` for generating path * strings. * * Uses {@link PathPosix} for Path objects. */ export class PathScurryDarwin extends PathScurryPosix { constructor(cwd = process.cwd(), opts = {}) { const { nocase = true } = opts; super(cwd, { ...opts, nocase }); } } /** * Default {@link PathBase} implementation for the current platform. * * {@link PathWin32} on Windows systems, {@link PathPosix} on all others. */ export const Path = process.platform === 'win32' ? PathWin32 : PathPosix; /** * Default {@link PathScurryBase} implementation for the current platform. * * {@link PathScurryWin32} on Windows systems, {@link PathScurryDarwin} on * Darwin (macOS) systems, {@link PathScurryPosix} on all others. */ export const PathScurry = process.platform === 'win32' ? PathScurryWin32 : process.platform === 'darwin' ? PathScurryDarwin : PathScurryPosix; //# sourceMappingURL=index.js.mapPK ~\쾇path-scurry/LICENSE.mdnu[# Blue Oak Model License Version 1.0.0 ## Purpose This license gives everyone as much permission to work with this software as possible, while protecting contributors from liability. ## Acceptance In order to receive this license, you must agree to its rules. The rules of this license are both obligations under that agreement and conditions to your license. You must not do anything with this software that triggers a rule that you cannot or will not follow. ## Copyright Each contributor licenses you to do everything with this software that would otherwise infringe that contributor's copyright in it. ## Notices You must ensure that everyone who gets a copy of any part of this software from you, with or without changes, also gets the text of this license or a link to . ## Excuse If anyone notifies you in writing that you have not complied with [Notices](#notices), you can keep your license by taking all practical steps to comply within 30 days after the notice. If you do not do so, your license ends immediately. ## Patent Each contributor licenses you to do everything with this software that would otherwise infringe any patent claims they can license or become able to license. ## Reliability No contributor can revoke this license. ## No Liability ***As far as the law allows, this software comes as is, without any warranty or condition, and no contributor will be liable to anyone for any damages related to this software or this license, under any kind of legal claim.*** PK ~\ ;;minipass-fetch/package.jsonnu[{ "_id": "minipass-fetch@3.0.5", "_inBundle": true, "_location": "/npm/minipass-fetch", "_phantomChildren": {}, "_requiredBy": [ "/npm/make-fetch-happen", "/npm/npm-registry-fetch" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/minipass-fetch/issues" }, "dependencies": { "encoding": "^0.1.13", "minipass": "^7.0.3", "minipass-sized": "^1.0.3", "minizlib": "^2.1.2" }, "description": "An implementation of window.fetch in Node.js using Minipass streams", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.22.0", "@ungap/url-search-params": "^0.2.2", "abort-controller": "^3.0.0", "abortcontroller-polyfill": "~1.7.3", "encoding": "^0.1.13", "form-data": "^4.0.0", "nock": "^13.2.4", "parted": "^0.1.1", "string-to-arraybuffer": "^1.0.2", "tap": "^16.0.0" }, "engines": { "node": "^14.17.0 || ^16.13.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/minipass-fetch#readme", "keywords": [ "fetch", "minipass", "node-fetch", "window.fetch" ], "license": "MIT", "main": "lib/index.js", "name": "minipass-fetch", "optionalDependencies": { "encoding": "^0.1.13" }, "repository": { "type": "git", "url": "git+https://github.com/npm/minipass-fetch.git" }, "scripts": { "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap", "test:tls-fixtures": "./test/fixtures/tls/setup.sh" }, "tap": { "coverage-map": "map.js", "check-coverage": true, "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.22.0", "publish": "true" }, "version": "3.0.5" } PK ~\sDaominipass-fetch/lib/response.jsnu['use strict' const http = require('http') const { STATUS_CODES } = http const Headers = require('./headers.js') const Body = require('./body.js') const { clone, extractContentType } = Body const INTERNALS = Symbol('Response internals') class Response extends Body { constructor (body = null, opts = {}) { super(body, opts) const status = opts.status || 200 const headers = new Headers(opts.headers) if (body !== null && body !== undefined && !headers.has('Content-Type')) { const contentType = extractContentType(body) if (contentType) { headers.append('Content-Type', contentType) } } this[INTERNALS] = { url: opts.url, status, statusText: opts.statusText || STATUS_CODES[status], headers, counter: opts.counter, trailer: Promise.resolve(opts.trailer || new Headers()), } } get trailer () { return this[INTERNALS].trailer } get url () { return this[INTERNALS].url || '' } get status () { return this[INTERNALS].status } get ok () { return this[INTERNALS].status >= 200 && this[INTERNALS].status < 300 } get redirected () { return this[INTERNALS].counter > 0 } get statusText () { return this[INTERNALS].statusText } get headers () { return this[INTERNALS].headers } clone () { return new Response(clone(this), { url: this.url, status: this.status, statusText: this.statusText, headers: this.headers, ok: this.ok, redirected: this.redirected, trailer: this.trailer, }) } get [Symbol.toStringTag] () { return 'Response' } } module.exports = Response Object.defineProperties(Response.prototype, { url: { enumerable: true }, status: { enumerable: true }, ok: { enumerable: true }, redirected: { enumerable: true }, statusText: { enumerable: true }, headers: { enumerable: true }, clone: { enumerable: true }, }) PK ~\Jminipass-fetch/lib/request.jsnu['use strict' const { URL } = require('url') const { Minipass } = require('minipass') const Headers = require('./headers.js') const { exportNodeCompatibleHeaders } = Headers const Body = require('./body.js') const { clone, extractContentType, getTotalBytes } = Body const version = require('../package.json').version const defaultUserAgent = `minipass-fetch/${version} (+https://github.com/isaacs/minipass-fetch)` const INTERNALS = Symbol('Request internals') const isRequest = input => typeof input === 'object' && typeof input[INTERNALS] === 'object' const isAbortSignal = signal => { const proto = ( signal && typeof signal === 'object' && Object.getPrototypeOf(signal) ) return !!(proto && proto.constructor.name === 'AbortSignal') } class Request extends Body { constructor (input, init = {}) { const parsedURL = isRequest(input) ? new URL(input.url) : input && input.href ? new URL(input.href) : new URL(`${input}`) if (isRequest(input)) { init = { ...input[INTERNALS], ...init } } else if (!input || typeof input === 'string') { input = {} } const method = (init.method || input.method || 'GET').toUpperCase() const isGETHEAD = method === 'GET' || method === 'HEAD' if ((init.body !== null && init.body !== undefined || isRequest(input) && input.body !== null) && isGETHEAD) { throw new TypeError('Request with GET/HEAD method cannot have body') } const inputBody = init.body !== null && init.body !== undefined ? init.body : isRequest(input) && input.body !== null ? clone(input) : null super(inputBody, { timeout: init.timeout || input.timeout || 0, size: init.size || input.size || 0, }) const headers = new Headers(init.headers || input.headers || {}) if (inputBody !== null && inputBody !== undefined && !headers.has('Content-Type')) { const contentType = extractContentType(inputBody) if (contentType) { headers.append('Content-Type', contentType) } } const signal = 'signal' in init ? init.signal : null if (signal !== null && signal !== undefined && !isAbortSignal(signal)) { throw new TypeError('Expected signal must be an instanceof AbortSignal') } // TLS specific options that are handled by node const { ca, cert, ciphers, clientCertEngine, crl, dhparam, ecdhCurve, family, honorCipherOrder, key, passphrase, pfx, rejectUnauthorized = process.env.NODE_TLS_REJECT_UNAUTHORIZED !== '0', secureOptions, secureProtocol, servername, sessionIdContext, } = init this[INTERNALS] = { method, redirect: init.redirect || input.redirect || 'follow', headers, parsedURL, signal, ca, cert, ciphers, clientCertEngine, crl, dhparam, ecdhCurve, family, honorCipherOrder, key, passphrase, pfx, rejectUnauthorized, secureOptions, secureProtocol, servername, sessionIdContext, } // node-fetch-only options this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20 this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true this.counter = init.counter || input.counter || 0 this.agent = init.agent || input.agent } get method () { return this[INTERNALS].method } get url () { return this[INTERNALS].parsedURL.toString() } get headers () { return this[INTERNALS].headers } get redirect () { return this[INTERNALS].redirect } get signal () { return this[INTERNALS].signal } clone () { return new Request(this) } get [Symbol.toStringTag] () { return 'Request' } static getNodeRequestOptions (request) { const parsedURL = request[INTERNALS].parsedURL const headers = new Headers(request[INTERNALS].headers) // fetch step 1.3 if (!headers.has('Accept')) { headers.set('Accept', '*/*') } // Basic fetch if (!/^https?:$/.test(parsedURL.protocol)) { throw new TypeError('Only HTTP(S) protocols are supported') } if (request.signal && Minipass.isStream(request.body) && typeof request.body.destroy !== 'function') { throw new Error( 'Cancellation of streamed requests with AbortSignal is not supported') } // HTTP-network-or-cache fetch steps 2.4-2.7 const contentLengthValue = (request.body === null || request.body === undefined) && /^(POST|PUT)$/i.test(request.method) ? '0' : request.body !== null && request.body !== undefined ? getTotalBytes(request) : null if (contentLengthValue) { headers.set('Content-Length', contentLengthValue + '') } // HTTP-network-or-cache fetch step 2.11 if (!headers.has('User-Agent')) { headers.set('User-Agent', defaultUserAgent) } // HTTP-network-or-cache fetch step 2.15 if (request.compress && !headers.has('Accept-Encoding')) { headers.set('Accept-Encoding', 'gzip,deflate') } const agent = typeof request.agent === 'function' ? request.agent(parsedURL) : request.agent if (!headers.has('Connection') && !agent) { headers.set('Connection', 'close') } // TLS specific options that are handled by node const { ca, cert, ciphers, clientCertEngine, crl, dhparam, ecdhCurve, family, honorCipherOrder, key, passphrase, pfx, rejectUnauthorized, secureOptions, secureProtocol, servername, sessionIdContext, } = request[INTERNALS] // HTTP-network fetch step 4.2 // chunked encoding is handled by Node.js // we cannot spread parsedURL directly, so we have to read each property one-by-one // and map them to the equivalent https?.request() method options const urlProps = { auth: parsedURL.username || parsedURL.password ? `${parsedURL.username}:${parsedURL.password}` : '', host: parsedURL.host, hostname: parsedURL.hostname, path: `${parsedURL.pathname}${parsedURL.search}`, port: parsedURL.port, protocol: parsedURL.protocol, } return { ...urlProps, method: request.method, headers: exportNodeCompatibleHeaders(headers), agent, ca, cert, ciphers, clientCertEngine, crl, dhparam, ecdhCurve, family, honorCipherOrder, key, passphrase, pfx, rejectUnauthorized, secureOptions, secureProtocol, servername, sessionIdContext, timeout: request.timeout, } } } module.exports = Request Object.defineProperties(Request.prototype, { method: { enumerable: true }, url: { enumerable: true }, headers: { enumerable: true }, redirect: { enumerable: true }, clone: { enumerable: true }, signal: { enumerable: true }, }) PK ~\bSjj!minipass-fetch/lib/abort-error.jsnu['use strict' class AbortError extends Error { constructor (message) { super(message) this.code = 'FETCH_ABORTED' this.type = 'aborted' Error.captureStackTrace(this, this.constructor) } get name () { return 'AbortError' } // don't allow name to be overridden, but don't throw either set name (s) {} } module.exports = AbortError PK ~\}"33minipass-fetch/lib/index.jsnu['use strict' const { URL } = require('url') const http = require('http') const https = require('https') const zlib = require('minizlib') const { Minipass } = require('minipass') const Body = require('./body.js') const { writeToStream, getTotalBytes } = Body const Response = require('./response.js') const Headers = require('./headers.js') const { createHeadersLenient } = Headers const Request = require('./request.js') const { getNodeRequestOptions } = Request const FetchError = require('./fetch-error.js') const AbortError = require('./abort-error.js') // XXX this should really be split up and unit-ized for easier testing // and better DRY implementation of data/http request aborting const fetch = async (url, opts) => { if (/^data:/.test(url)) { const request = new Request(url, opts) // delay 1 promise tick so that the consumer can abort right away return Promise.resolve().then(() => new Promise((resolve, reject) => { let type, data try { const { pathname, search } = new URL(url) const split = pathname.split(',') if (split.length < 2) { throw new Error('invalid data: URI') } const mime = split.shift() const base64 = /;base64$/.test(mime) type = base64 ? mime.slice(0, -1 * ';base64'.length) : mime const rawData = decodeURIComponent(split.join(',') + search) data = base64 ? Buffer.from(rawData, 'base64') : Buffer.from(rawData) } catch (er) { return reject(new FetchError(`[${request.method}] ${ request.url} invalid URL, ${er.message}`, 'system', er)) } const { signal } = request if (signal && signal.aborted) { return reject(new AbortError('The user aborted a request.')) } const headers = { 'Content-Length': data.length } if (type) { headers['Content-Type'] = type } return resolve(new Response(data, { headers })) })) } return new Promise((resolve, reject) => { // build request object const request = new Request(url, opts) let options try { options = getNodeRequestOptions(request) } catch (er) { return reject(er) } const send = (options.protocol === 'https:' ? https : http).request const { signal } = request let response = null const abort = () => { const error = new AbortError('The user aborted a request.') reject(error) if (Minipass.isStream(request.body) && typeof request.body.destroy === 'function') { request.body.destroy(error) } if (response && response.body) { response.body.emit('error', error) } } if (signal && signal.aborted) { return abort() } const abortAndFinalize = () => { abort() finalize() } const finalize = () => { req.abort() if (signal) { signal.removeEventListener('abort', abortAndFinalize) } clearTimeout(reqTimeout) } // send request const req = send(options) if (signal) { signal.addEventListener('abort', abortAndFinalize) } let reqTimeout = null if (request.timeout) { req.once('socket', () => { reqTimeout = setTimeout(() => { reject(new FetchError(`network timeout at: ${ request.url}`, 'request-timeout')) finalize() }, request.timeout) }) } req.on('error', er => { // if a 'response' event is emitted before the 'error' event, then by the // time this handler is run it's too late to reject the Promise for the // response. instead, we forward the error event to the response stream // so that the error will surface to the user when they try to consume // the body. this is done as a side effect of aborting the request except // for in windows, where we must forward the event manually, otherwise // there is no longer a ref'd socket attached to the request and the // stream never ends so the event loop runs out of work and the process // exits without warning. // coverage skipped here due to the difficulty in testing // istanbul ignore next if (req.res) { req.res.emit('error', er) } reject(new FetchError(`request to ${request.url} failed, reason: ${ er.message}`, 'system', er)) finalize() }) req.on('response', res => { clearTimeout(reqTimeout) const headers = createHeadersLenient(res.headers) // HTTP fetch step 5 if (fetch.isRedirect(res.statusCode)) { // HTTP fetch step 5.2 const location = headers.get('Location') // HTTP fetch step 5.3 let locationURL = null try { locationURL = location === null ? null : new URL(location, request.url).toString() } catch { // error here can only be invalid URL in Location: header // do not throw when options.redirect == manual // let the user extract the errorneous redirect URL if (request.redirect !== 'manual') { /* eslint-disable-next-line max-len */ reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')) finalize() return } } // HTTP fetch step 5.5 if (request.redirect === 'error') { reject(new FetchError('uri requested responds with a redirect, ' + `redirect mode is set to error: ${request.url}`, 'no-redirect')) finalize() return } else if (request.redirect === 'manual') { // node-fetch-specific step: make manual redirect a bit easier to // use by setting the Location header value to the resolved URL. if (locationURL !== null) { // handle corrupted header try { headers.set('Location', locationURL) } catch (err) { /* istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request */ reject(err) } } } else if (request.redirect === 'follow' && locationURL !== null) { // HTTP-redirect fetch step 5 if (request.counter >= request.follow) { reject(new FetchError(`maximum redirect reached at: ${ request.url}`, 'max-redirect')) finalize() return } // HTTP-redirect fetch step 9 if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { reject(new FetchError( 'Cannot follow redirect with body being a readable stream', 'unsupported-redirect' )) finalize() return } // Update host due to redirection request.headers.set('host', (new URL(locationURL)).host) // HTTP-redirect fetch step 6 (counter increment) // Create a new Request object. const requestOpts = { headers: new Headers(request.headers), follow: request.follow, counter: request.counter + 1, agent: request.agent, compress: request.compress, method: request.method, body: request.body, signal: request.signal, timeout: request.timeout, } // if the redirect is to a new hostname, strip the authorization and cookie headers const parsedOriginal = new URL(request.url) const parsedRedirect = new URL(locationURL) if (parsedOriginal.hostname !== parsedRedirect.hostname) { requestOpts.headers.delete('authorization') requestOpts.headers.delete('cookie') } // HTTP-redirect fetch step 11 if (res.statusCode === 303 || ( (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST' )) { requestOpts.method = 'GET' requestOpts.body = undefined requestOpts.headers.delete('content-length') } // HTTP-redirect fetch step 15 resolve(fetch(new Request(locationURL, requestOpts))) finalize() return } } // end if(isRedirect) // prepare response res.once('end', () => signal && signal.removeEventListener('abort', abortAndFinalize)) const body = new Minipass() // if an error occurs, either on the response stream itself, on one of the // decoder streams, or a response length timeout from the Body class, we // forward the error through to our internal body stream. If we see an // error event on that, we call finalize to abort the request and ensure // we don't leave a socket believing a request is in flight. // this is difficult to test, so lacks specific coverage. body.on('error', finalize) // exceedingly rare that the stream would have an error, // but just in case we proxy it to the stream in use. res.on('error', /* istanbul ignore next */ er => body.emit('error', er)) res.on('data', (chunk) => body.write(chunk)) res.on('end', () => body.end()) const responseOptions = { url: request.url, status: res.statusCode, statusText: res.statusMessage, headers: headers, size: request.size, timeout: request.timeout, counter: request.counter, trailer: new Promise(resolveTrailer => res.on('end', () => resolveTrailer(createHeadersLenient(res.trailers)))), } // HTTP-network fetch step 12.1.1.3 const codings = headers.get('Content-Encoding') // HTTP-network fetch step 12.1.1.4: handle content codings // in following scenarios we ignore compression support // 1. compression support is disabled // 2. HEAD request // 3. no Content-Encoding header // 4. no content response (204) // 5. content not modified response (304) if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { response = new Response(body, responseOptions) resolve(response) return } // Be less strict when decoding compressed responses, since sometimes // servers send slightly invalid responses that are still accepted // by common browsers. // Always using Z_SYNC_FLUSH is what cURL does. const zlibOptions = { flush: zlib.constants.Z_SYNC_FLUSH, finishFlush: zlib.constants.Z_SYNC_FLUSH, } // for gzip if (codings === 'gzip' || codings === 'x-gzip') { const unzip = new zlib.Gunzip(zlibOptions) response = new Response( // exceedingly rare that the stream would have an error, // but just in case we proxy it to the stream in use. body.on('error', /* istanbul ignore next */ er => unzip.emit('error', er)).pipe(unzip), responseOptions ) resolve(response) return } // for deflate if (codings === 'deflate' || codings === 'x-deflate') { // handle the infamous raw deflate response from old servers // a hack for old IIS and Apache servers const raw = res.pipe(new Minipass()) raw.once('data', chunk => { // see http://stackoverflow.com/questions/37519828 const decoder = (chunk[0] & 0x0F) === 0x08 ? new zlib.Inflate() : new zlib.InflateRaw() // exceedingly rare that the stream would have an error, // but just in case we proxy it to the stream in use. body.on('error', /* istanbul ignore next */ er => decoder.emit('error', er)).pipe(decoder) response = new Response(decoder, responseOptions) resolve(response) }) return } // for br if (codings === 'br') { // ignoring coverage so tests don't have to fake support (or lack of) for brotli // istanbul ignore next try { var decoder = new zlib.BrotliDecompress() } catch (err) { reject(err) finalize() return } // exceedingly rare that the stream would have an error, // but just in case we proxy it to the stream in use. body.on('error', /* istanbul ignore next */ er => decoder.emit('error', er)).pipe(decoder) response = new Response(decoder, responseOptions) resolve(response) return } // otherwise, use response as-is response = new Response(body, responseOptions) resolve(response) }) writeToStream(req, request) }) } module.exports = fetch fetch.isRedirect = code => code === 301 || code === 302 || code === 303 || code === 307 || code === 308 fetch.Headers = Headers fetch.Request = Request fetch.Response = Response fetch.FetchError = FetchError fetch.AbortError = AbortError PK ~\θM4)4)minipass-fetch/lib/body.jsnu['use strict' const { Minipass } = require('minipass') const MinipassSized = require('minipass-sized') const Blob = require('./blob.js') const { BUFFER } = Blob const FetchError = require('./fetch-error.js') // optional dependency on 'encoding' let convert try { convert = require('encoding').convert } catch (e) { // defer error until textConverted is called } const INTERNALS = Symbol('Body internals') const CONSUME_BODY = Symbol('consumeBody') class Body { constructor (bodyArg, options = {}) { const { size = 0, timeout = 0 } = options const body = bodyArg === undefined || bodyArg === null ? null : isURLSearchParams(bodyArg) ? Buffer.from(bodyArg.toString()) : isBlob(bodyArg) ? bodyArg : Buffer.isBuffer(bodyArg) ? bodyArg : Object.prototype.toString.call(bodyArg) === '[object ArrayBuffer]' ? Buffer.from(bodyArg) : ArrayBuffer.isView(bodyArg) ? Buffer.from(bodyArg.buffer, bodyArg.byteOffset, bodyArg.byteLength) : Minipass.isStream(bodyArg) ? bodyArg : Buffer.from(String(bodyArg)) this[INTERNALS] = { body, disturbed: false, error: null, } this.size = size this.timeout = timeout if (Minipass.isStream(body)) { body.on('error', er => { const error = er.name === 'AbortError' ? er : new FetchError(`Invalid response while trying to fetch ${ this.url}: ${er.message}`, 'system', er) this[INTERNALS].error = error }) } } get body () { return this[INTERNALS].body } get bodyUsed () { return this[INTERNALS].disturbed } arrayBuffer () { return this[CONSUME_BODY]().then(buf => buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)) } blob () { const ct = this.headers && this.headers.get('content-type') || '' return this[CONSUME_BODY]().then(buf => Object.assign( new Blob([], { type: ct.toLowerCase() }), { [BUFFER]: buf } )) } async json () { const buf = await this[CONSUME_BODY]() try { return JSON.parse(buf.toString()) } catch (er) { throw new FetchError( `invalid json response body at ${this.url} reason: ${er.message}`, 'invalid-json' ) } } text () { return this[CONSUME_BODY]().then(buf => buf.toString()) } buffer () { return this[CONSUME_BODY]() } textConverted () { return this[CONSUME_BODY]().then(buf => convertBody(buf, this.headers)) } [CONSUME_BODY] () { if (this[INTERNALS].disturbed) { return Promise.reject(new TypeError(`body used already for: ${ this.url}`)) } this[INTERNALS].disturbed = true if (this[INTERNALS].error) { return Promise.reject(this[INTERNALS].error) } // body is null if (this.body === null) { return Promise.resolve(Buffer.alloc(0)) } if (Buffer.isBuffer(this.body)) { return Promise.resolve(this.body) } const upstream = isBlob(this.body) ? this.body.stream() : this.body /* istanbul ignore if: should never happen */ if (!Minipass.isStream(upstream)) { return Promise.resolve(Buffer.alloc(0)) } const stream = this.size && upstream instanceof MinipassSized ? upstream : !this.size && upstream instanceof Minipass && !(upstream instanceof MinipassSized) ? upstream : this.size ? new MinipassSized({ size: this.size }) : new Minipass() // allow timeout on slow response body, but only if the stream is still writable. this // makes the timeout center on the socket stream from lib/index.js rather than the // intermediary minipass stream we create to receive the data const resTimeout = this.timeout && stream.writable ? setTimeout(() => { stream.emit('error', new FetchError( `Response timeout while trying to fetch ${ this.url} (over ${this.timeout}ms)`, 'body-timeout')) }, this.timeout) : null // do not keep the process open just for this timeout, even // though we expect it'll get cleared eventually. if (resTimeout && resTimeout.unref) { resTimeout.unref() } // do the pipe in the promise, because the pipe() can send too much // data through right away and upset the MP Sized object return new Promise((resolve) => { // if the stream is some other kind of stream, then pipe through a MP // so we can collect it more easily. if (stream !== upstream) { upstream.on('error', er => stream.emit('error', er)) upstream.pipe(stream) } resolve() }).then(() => stream.concat()).then(buf => { clearTimeout(resTimeout) return buf }).catch(er => { clearTimeout(resTimeout) // request was aborted, reject with this Error if (er.name === 'AbortError' || er.name === 'FetchError') { throw er } else if (er.name === 'RangeError') { throw new FetchError(`Could not create Buffer from response body for ${ this.url}: ${er.message}`, 'system', er) } else { // other errors, such as incorrect content-encoding or content-length throw new FetchError(`Invalid response body while trying to fetch ${ this.url}: ${er.message}`, 'system', er) } }) } static clone (instance) { if (instance.bodyUsed) { throw new Error('cannot clone body after it is used') } const body = instance.body // check that body is a stream and not form-data object // NB: can't clone the form-data object without having it as a dependency if (Minipass.isStream(body) && typeof body.getBoundary !== 'function') { // create a dedicated tee stream so that we don't lose data // potentially sitting in the body stream's buffer by writing it // immediately to p1 and not having it for p2. const tee = new Minipass() const p1 = new Minipass() const p2 = new Minipass() tee.on('error', er => { p1.emit('error', er) p2.emit('error', er) }) body.on('error', er => tee.emit('error', er)) tee.pipe(p1) tee.pipe(p2) body.pipe(tee) // set instance body to one fork, return the other instance[INTERNALS].body = p1 return p2 } else { return instance.body } } static extractContentType (body) { return body === null || body === undefined ? null : typeof body === 'string' ? 'text/plain;charset=UTF-8' : isURLSearchParams(body) ? 'application/x-www-form-urlencoded;charset=UTF-8' : isBlob(body) ? body.type || null : Buffer.isBuffer(body) ? null : Object.prototype.toString.call(body) === '[object ArrayBuffer]' ? null : ArrayBuffer.isView(body) ? null : typeof body.getBoundary === 'function' ? `multipart/form-data;boundary=${body.getBoundary()}` : Minipass.isStream(body) ? null : 'text/plain;charset=UTF-8' } static getTotalBytes (instance) { const { body } = instance return (body === null || body === undefined) ? 0 : isBlob(body) ? body.size : Buffer.isBuffer(body) ? body.length : body && typeof body.getLengthSync === 'function' && ( // detect form data input from form-data module body._lengthRetrievers && /* istanbul ignore next */ body._lengthRetrievers.length === 0 || // 1.x body.hasKnownLength && body.hasKnownLength()) // 2.x ? body.getLengthSync() : null } static writeToStream (dest, instance) { const { body } = instance if (body === null || body === undefined) { dest.end() } else if (Buffer.isBuffer(body) || typeof body === 'string') { dest.end(body) } else { // body is stream or blob const stream = isBlob(body) ? body.stream() : body stream.on('error', er => dest.emit('error', er)).pipe(dest) } return dest } } Object.defineProperties(Body.prototype, { body: { enumerable: true }, bodyUsed: { enumerable: true }, arrayBuffer: { enumerable: true }, blob: { enumerable: true }, json: { enumerable: true }, text: { enumerable: true }, }) const isURLSearchParams = obj => // Duck-typing as a necessary condition. (typeof obj !== 'object' || typeof obj.append !== 'function' || typeof obj.delete !== 'function' || typeof obj.get !== 'function' || typeof obj.getAll !== 'function' || typeof obj.has !== 'function' || typeof obj.set !== 'function') ? false // Brand-checking and more duck-typing as optional condition. : obj.constructor.name === 'URLSearchParams' || Object.prototype.toString.call(obj) === '[object URLSearchParams]' || typeof obj.sort === 'function' const isBlob = obj => typeof obj === 'object' && typeof obj.arrayBuffer === 'function' && typeof obj.type === 'string' && typeof obj.stream === 'function' && typeof obj.constructor === 'function' && typeof obj.constructor.name === 'string' && /^(Blob|File)$/.test(obj.constructor.name) && /^(Blob|File)$/.test(obj[Symbol.toStringTag]) const convertBody = (buffer, headers) => { /* istanbul ignore if */ if (typeof convert !== 'function') { throw new Error('The package `encoding` must be installed to use the textConverted() function') } const ct = headers && headers.get('content-type') let charset = 'utf-8' let res // header if (ct) { res = /charset=([^;]*)/i.exec(ct) } // no charset in content type, peek at response body for at most 1024 bytes const str = buffer.slice(0, 1024).toString() // html5 if (!res && str) { res = / { name = `${name}` if (invalidTokenRegex.test(name) || name === '') { throw new TypeError(`${name} is not a legal HTTP header name`) } } const validateValue = value => { value = `${value}` if (invalidHeaderCharRegex.test(value)) { throw new TypeError(`${value} is not a legal HTTP header value`) } } const find = (map, name) => { name = name.toLowerCase() for (const key in map) { if (key.toLowerCase() === name) { return key } } return undefined } const MAP = Symbol('map') class Headers { constructor (init = undefined) { this[MAP] = Object.create(null) if (init instanceof Headers) { const rawHeaders = init.raw() const headerNames = Object.keys(rawHeaders) for (const headerName of headerNames) { for (const value of rawHeaders[headerName]) { this.append(headerName, value) } } return } // no-op if (init === undefined || init === null) { return } if (typeof init === 'object') { const method = init[Symbol.iterator] if (method !== null && method !== undefined) { if (typeof method !== 'function') { throw new TypeError('Header pairs must be iterable') } // sequence> // Note: per spec we have to first exhaust the lists then process them const pairs = [] for (const pair of init) { if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { throw new TypeError('Each header pair must be iterable') } const arrPair = Array.from(pair) if (arrPair.length !== 2) { throw new TypeError('Each header pair must be a name/value tuple') } pairs.push(arrPair) } for (const pair of pairs) { this.append(pair[0], pair[1]) } } else { // record for (const key of Object.keys(init)) { this.append(key, init[key]) } } } else { throw new TypeError('Provided initializer must be an object') } } get (name) { name = `${name}` validateName(name) const key = find(this[MAP], name) if (key === undefined) { return null } return this[MAP][key].join(', ') } forEach (callback, thisArg = undefined) { let pairs = getHeaders(this) for (let i = 0; i < pairs.length; i++) { const [name, value] = pairs[i] callback.call(thisArg, value, name, this) // refresh in case the callback added more headers pairs = getHeaders(this) } } set (name, value) { name = `${name}` value = `${value}` validateName(name) validateValue(value) const key = find(this[MAP], name) this[MAP][key !== undefined ? key : name] = [value] } append (name, value) { name = `${name}` value = `${value}` validateName(name) validateValue(value) const key = find(this[MAP], name) if (key !== undefined) { this[MAP][key].push(value) } else { this[MAP][name] = [value] } } has (name) { name = `${name}` validateName(name) return find(this[MAP], name) !== undefined } delete (name) { name = `${name}` validateName(name) const key = find(this[MAP], name) if (key !== undefined) { delete this[MAP][key] } } raw () { return this[MAP] } keys () { return new HeadersIterator(this, 'key') } values () { return new HeadersIterator(this, 'value') } [Symbol.iterator] () { return new HeadersIterator(this, 'key+value') } entries () { return new HeadersIterator(this, 'key+value') } get [Symbol.toStringTag] () { return 'Headers' } static exportNodeCompatibleHeaders (headers) { const obj = Object.assign(Object.create(null), headers[MAP]) // http.request() only supports string as Host header. This hack makes // specifying custom Host header possible. const hostHeaderKey = find(headers[MAP], 'Host') if (hostHeaderKey !== undefined) { obj[hostHeaderKey] = obj[hostHeaderKey][0] } return obj } static createHeadersLenient (obj) { const headers = new Headers() for (const name of Object.keys(obj)) { if (invalidTokenRegex.test(name)) { continue } if (Array.isArray(obj[name])) { for (const val of obj[name]) { if (invalidHeaderCharRegex.test(val)) { continue } if (headers[MAP][name] === undefined) { headers[MAP][name] = [val] } else { headers[MAP][name].push(val) } } } else if (!invalidHeaderCharRegex.test(obj[name])) { headers[MAP][name] = [obj[name]] } } return headers } } Object.defineProperties(Headers.prototype, { get: { enumerable: true }, forEach: { enumerable: true }, set: { enumerable: true }, append: { enumerable: true }, has: { enumerable: true }, delete: { enumerable: true }, keys: { enumerable: true }, values: { enumerable: true }, entries: { enumerable: true }, }) const getHeaders = (headers, kind = 'key+value') => Object.keys(headers[MAP]).sort().map( kind === 'key' ? k => k.toLowerCase() : kind === 'value' ? k => headers[MAP][k].join(', ') : k => [k.toLowerCase(), headers[MAP][k].join(', ')] ) const INTERNAL = Symbol('internal') class HeadersIterator { constructor (target, kind) { this[INTERNAL] = { target, kind, index: 0, } } get [Symbol.toStringTag] () { return 'HeadersIterator' } next () { /* istanbul ignore if: should be impossible */ if (!this || Object.getPrototypeOf(this) !== HeadersIterator.prototype) { throw new TypeError('Value of `this` is not a HeadersIterator') } const { target, kind, index } = this[INTERNAL] const values = getHeaders(target, kind) const len = values.length if (index >= len) { return { value: undefined, done: true, } } this[INTERNAL].index++ return { value: values[index], done: false } } } // manually extend because 'extends' requires a ctor Object.setPrototypeOf(HeadersIterator.prototype, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))) module.exports = Headers PK ~\O  minipass-fetch/lib/blob.jsnu['use strict' const { Minipass } = require('minipass') const TYPE = Symbol('type') const BUFFER = Symbol('buffer') class Blob { constructor (blobParts, options) { this[TYPE] = '' const buffers = [] let size = 0 if (blobParts) { const a = blobParts const length = Number(a.length) for (let i = 0; i < length; i++) { const element = a[i] const buffer = element instanceof Buffer ? element : ArrayBuffer.isView(element) ? Buffer.from(element.buffer, element.byteOffset, element.byteLength) : element instanceof ArrayBuffer ? Buffer.from(element) : element instanceof Blob ? element[BUFFER] : typeof element === 'string' ? Buffer.from(element) : Buffer.from(String(element)) size += buffer.length buffers.push(buffer) } } this[BUFFER] = Buffer.concat(buffers, size) const type = options && options.type !== undefined && String(options.type).toLowerCase() if (type && !/[^\u0020-\u007E]/.test(type)) { this[TYPE] = type } } get size () { return this[BUFFER].length } get type () { return this[TYPE] } text () { return Promise.resolve(this[BUFFER].toString()) } arrayBuffer () { const buf = this[BUFFER] const off = buf.byteOffset const len = buf.byteLength const ab = buf.buffer.slice(off, off + len) return Promise.resolve(ab) } stream () { return new Minipass().end(this[BUFFER]) } slice (start, end, type) { const size = this.size const relativeStart = start === undefined ? 0 : start < 0 ? Math.max(size + start, 0) : Math.min(start, size) const relativeEnd = end === undefined ? size : end < 0 ? Math.max(size + end, 0) : Math.min(end, size) const span = Math.max(relativeEnd - relativeStart, 0) const buffer = this[BUFFER] const slicedBuffer = buffer.slice( relativeStart, relativeStart + span ) const blob = new Blob([], { type }) blob[BUFFER] = slicedBuffer return blob } get [Symbol.toStringTag] () { return 'Blob' } static get BUFFER () { return BUFFER } } Object.defineProperties(Blob.prototype, { size: { enumerable: true }, type: { enumerable: true }, }) module.exports = Blob PK ~\k6!minipass-fetch/lib/fetch-error.jsnu['use strict' class FetchError extends Error { constructor (message, type, systemError) { super(message) this.code = 'FETCH_ERROR' // pick up code, expected, path, ... if (systemError) { Object.assign(this, systemError) } this.errno = this.code // override anything the system error might've clobbered this.type = this.code === 'EBADSIZE' && this.found > this.expect ? 'max-size' : type this.message = message Error.captureStackTrace(this, this.constructor) } get name () { return 'FetchError' } // don't allow name to be overwritten set name (n) {} get [Symbol.toStringTag] () { return 'FetchError' } } module.exports = FetchError PK ~\⤳minipass-fetch/LICENSEnu[The MIT License (MIT) Copyright (c) Isaac Z. Schlueter and Contributors Copyright (c) 2016 David Frank Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --- Note: This is a derivative work based on "node-fetch" by David Frank, modified and distributed under the terms of the MIT license above. https://github.com/bitinn/node-fetch PK ~\6is-core-module/package.jsonnu[{ "_id": "is-core-module@2.13.1", "_inBundle": true, "_location": "/npm/is-core-module", "_phantomChildren": {}, "_requiredBy": [ "/npm/normalize-package-data" ], "author": { "name": "Jordan Harband", "email": "ljharb@gmail.com" }, "auto-changelog": { "output": "CHANGELOG.md", "template": "keepachangelog", "unreleased": false, "commitLimit": false, "backfillLimit": false, "hideCredit": true }, "bugs": { "url": "https://github.com/inspect-js/is-core-module/issues" }, "dependencies": { "hasown": "^2.0.0" }, "description": "Is this specifier a node.js core module?", "devDependencies": { "@ljharb/eslint-config": "^21.1.0", "aud": "^2.0.3", "auto-changelog": "^2.4.0", "eslint": "=8.8.0", "in-publish": "^2.0.1", "mock-property": "^1.0.2", "npmignore": "^0.3.0", "nyc": "^10.3.2", "safe-publish-latest": "^2.0.0", "semver": "^6.3.1", "tape": "^5.7.1" }, "exports": { ".": "./index.js", "./package.json": "./package.json" }, "funding": { "url": "https://github.com/sponsors/ljharb" }, "homepage": "https://github.com/inspect-js/is-core-module", "keywords": [ "core", "modules", "module", "npm", "node", "dependencies" ], "license": "MIT", "main": "index.js", "name": "is-core-module", "publishConfig": { "ignore": [ ".github" ] }, "repository": { "type": "git", "url": "git+https://github.com/inspect-js/is-core-module.git" }, "scripts": { "lint": "eslint .", "posttest": "aud --production", "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"", "prepack": "npmignore --auto --commentLines=autogenerated", "prepublish": "not-in-publish || npm run prepublishOnly", "prepublishOnly": "safe-publish-latest", "pretest": "npm run lint", "test": "npm run tests-only", "tests-only": "nyc tape 'test/**/*.js'", "version": "auto-changelog && git add CHANGELOG.md" }, "sideEffects": false, "version": "2.13.1" } PK ~\(^is-core-module/test/index.jsnu['use strict'; var test = require('tape'); var keys = require('object-keys'); var semver = require('semver'); var mockProperty = require('mock-property'); var isCore = require('../'); var data = require('../core.json'); var supportsNodePrefix = semver.satisfies(process.versions.node, '^14.18 || >= 16', { includePrerelease: true }); test('core modules', function (t) { t.test('isCore()', function (st) { st.ok(isCore('fs')); st.ok(isCore('net')); st.ok(isCore('http')); st.ok(!isCore('seq')); st.ok(!isCore('../')); st.ok(!isCore('toString')); st.end(); }); t.test('core list', function (st) { var cores = keys(data); st.plan(cores.length); for (var i = 0; i < cores.length; ++i) { var mod = cores[i]; var requireFunc = function () { require(mod); }; // eslint-disable-line no-loop-func if (isCore(mod)) { st.doesNotThrow(requireFunc, mod + ' supported; requiring does not throw'); } else { st['throws'](requireFunc, mod + ' not supported; requiring throws'); } } st.end(); }); t.test('core via repl module', { skip: !data.repl }, function (st) { var libs = require('repl')._builtinLibs; // eslint-disable-line no-underscore-dangle if (!libs) { st.skip('repl._builtinLibs does not exist'); } else { for (var i = 0; i < libs.length; ++i) { var mod = libs[i]; st.ok(data[mod], mod + ' is a core module'); st.doesNotThrow( function () { require(mod); }, // eslint-disable-line no-loop-func 'requiring ' + mod + ' does not throw' ); if (mod.slice(0, 5) !== 'node:') { if (supportsNodePrefix) { st.doesNotThrow( function () { require('node:' + mod); }, // eslint-disable-line no-loop-func 'requiring node:' + mod + ' does not throw' ); } else { st['throws']( function () { require('node:' + mod); }, // eslint-disable-line no-loop-func 'requiring node:' + mod + ' throws' ); } } } } st.end(); }); t.test('core via builtinModules list', { skip: !data.module }, function (st) { var libs = require('module').builtinModules; if (!libs) { st.skip('module.builtinModules does not exist'); } else { var excludeList = [ '_debug_agent', 'v8/tools/tickprocessor-driver', 'v8/tools/SourceMap', 'v8/tools/tickprocessor', 'v8/tools/profile' ]; // see https://github.com/nodejs/node/issues/42785 if (semver.satisfies(process.version, '>= 18')) { libs = libs.concat('node:test'); } for (var i = 0; i < libs.length; ++i) { var mod = libs[i]; if (excludeList.indexOf(mod) === -1) { st.ok(data[mod], mod + ' is a core module'); st.doesNotThrow( function () { require(mod); }, // eslint-disable-line no-loop-func 'requiring ' + mod + ' does not throw' ); if (mod.slice(0, 5) !== 'node:') { if (supportsNodePrefix) { st.doesNotThrow( function () { require('node:' + mod); }, // eslint-disable-line no-loop-func 'requiring node:' + mod + ' does not throw' ); } else { st['throws']( function () { require('node:' + mod); }, // eslint-disable-line no-loop-func 'requiring node:' + mod + ' throws' ); } } } } } st.end(); }); t.test('Object.prototype pollution', function (st) { var nonKey = 'not a core module'; st.teardown(mockProperty(Object.prototype, 'fs', { value: false })); st.teardown(mockProperty(Object.prototype, 'path', { value: '>= 999999999' })); st.teardown(mockProperty(Object.prototype, 'http', { value: data.http })); st.teardown(mockProperty(Object.prototype, nonKey, { value: true })); st.equal(isCore('fs'), true, 'fs is a core module even if Object.prototype lies'); st.equal(isCore('path'), true, 'path is a core module even if Object.prototype lies'); st.equal(isCore('http'), true, 'path is a core module even if Object.prototype matches data'); st.equal(isCore(nonKey), false, '"' + nonKey + '" is not a core module even if Object.prototype lies'); st.end(); }); t.end(); }); PK ~\\66is-core-module/LICENSEnu[The MIT License (MIT) Copyright (c) 2014 Dave Justice Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.PK ~\Kis-core-module/index.jsnu['use strict'; var hasOwn = require('hasown'); function specifierIncluded(current, specifier) { var nodeParts = current.split('.'); var parts = specifier.split(' '); var op = parts.length > 1 ? parts[0] : '='; var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.'); for (var i = 0; i < 3; ++i) { var cur = parseInt(nodeParts[i] || 0, 10); var ver = parseInt(versionParts[i] || 0, 10); if (cur === ver) { continue; // eslint-disable-line no-restricted-syntax, no-continue } if (op === '<') { return cur < ver; } if (op === '>=') { return cur >= ver; } return false; } return op === '>='; } function matchesRange(current, range) { var specifiers = range.split(/ ?&& ?/); if (specifiers.length === 0) { return false; } for (var i = 0; i < specifiers.length; ++i) { if (!specifierIncluded(current, specifiers[i])) { return false; } } return true; } function versionIncluded(nodeVersion, specifierValue) { if (typeof specifierValue === 'boolean') { return specifierValue; } var current = typeof nodeVersion === 'undefined' ? process.versions && process.versions.node : nodeVersion; if (typeof current !== 'string') { throw new TypeError(typeof nodeVersion === 'undefined' ? 'Unable to determine current node version' : 'If provided, a valid node version is required'); } if (specifierValue && typeof specifierValue === 'object') { for (var i = 0; i < specifierValue.length; ++i) { if (matchesRange(current, specifierValue[i])) { return true; } } return false; } return matchesRange(current, specifierValue); } var data = require('./core.json'); module.exports = function isCore(x, nodeVersion) { return hasOwn(data, x) && versionIncluded(nodeVersion, data[x]); }; PK ~\Z1is-core-module/core.jsonnu[{ "assert": true, "node:assert": [">= 14.18 && < 15", ">= 16"], "assert/strict": ">= 15", "node:assert/strict": ">= 16", "async_hooks": ">= 8", "node:async_hooks": [">= 14.18 && < 15", ">= 16"], "buffer_ieee754": ">= 0.5 && < 0.9.7", "buffer": true, "node:buffer": [">= 14.18 && < 15", ">= 16"], "child_process": true, "node:child_process": [">= 14.18 && < 15", ">= 16"], "cluster": ">= 0.5", "node:cluster": [">= 14.18 && < 15", ">= 16"], "console": true, "node:console": [">= 14.18 && < 15", ">= 16"], "constants": true, "node:constants": [">= 14.18 && < 15", ">= 16"], "crypto": true, "node:crypto": [">= 14.18 && < 15", ">= 16"], "_debug_agent": ">= 1 && < 8", "_debugger": "< 8", "dgram": true, "node:dgram": [">= 14.18 && < 15", ">= 16"], "diagnostics_channel": [">= 14.17 && < 15", ">= 15.1"], "node:diagnostics_channel": [">= 14.18 && < 15", ">= 16"], "dns": true, "node:dns": [">= 14.18 && < 15", ">= 16"], "dns/promises": ">= 15", "node:dns/promises": ">= 16", "domain": ">= 0.7.12", "node:domain": [">= 14.18 && < 15", ">= 16"], "events": true, "node:events": [">= 14.18 && < 15", ">= 16"], "freelist": "< 6", "fs": true, "node:fs": [">= 14.18 && < 15", ">= 16"], "fs/promises": [">= 10 && < 10.1", ">= 14"], "node:fs/promises": [">= 14.18 && < 15", ">= 16"], "_http_agent": ">= 0.11.1", "node:_http_agent": [">= 14.18 && < 15", ">= 16"], "_http_client": ">= 0.11.1", "node:_http_client": [">= 14.18 && < 15", ">= 16"], "_http_common": ">= 0.11.1", "node:_http_common": [">= 14.18 && < 15", ">= 16"], "_http_incoming": ">= 0.11.1", "node:_http_incoming": [">= 14.18 && < 15", ">= 16"], "_http_outgoing": ">= 0.11.1", "node:_http_outgoing": [">= 14.18 && < 15", ">= 16"], "_http_server": ">= 0.11.1", "node:_http_server": [">= 14.18 && < 15", ">= 16"], "http": true, "node:http": [">= 14.18 && < 15", ">= 16"], "http2": ">= 8.8", "node:http2": [">= 14.18 && < 15", ">= 16"], "https": true, "node:https": [">= 14.18 && < 15", ">= 16"], "inspector": ">= 8", "node:inspector": [">= 14.18 && < 15", ">= 16"], "inspector/promises": [">= 19"], "node:inspector/promises": [">= 19"], "_linklist": "< 8", "module": true, "node:module": [">= 14.18 && < 15", ">= 16"], "net": true, "node:net": [">= 14.18 && < 15", ">= 16"], "node-inspect/lib/_inspect": ">= 7.6 && < 12", "node-inspect/lib/internal/inspect_client": ">= 7.6 && < 12", "node-inspect/lib/internal/inspect_repl": ">= 7.6 && < 12", "os": true, "node:os": [">= 14.18 && < 15", ">= 16"], "path": true, "node:path": [">= 14.18 && < 15", ">= 16"], "path/posix": ">= 15.3", "node:path/posix": ">= 16", "path/win32": ">= 15.3", "node:path/win32": ">= 16", "perf_hooks": ">= 8.5", "node:perf_hooks": [">= 14.18 && < 15", ">= 16"], "process": ">= 1", "node:process": [">= 14.18 && < 15", ">= 16"], "punycode": ">= 0.5", "node:punycode": [">= 14.18 && < 15", ">= 16"], "querystring": true, "node:querystring": [">= 14.18 && < 15", ">= 16"], "readline": true, "node:readline": [">= 14.18 && < 15", ">= 16"], "readline/promises": ">= 17", "node:readline/promises": ">= 17", "repl": true, "node:repl": [">= 14.18 && < 15", ">= 16"], "smalloc": ">= 0.11.5 && < 3", "_stream_duplex": ">= 0.9.4", "node:_stream_duplex": [">= 14.18 && < 15", ">= 16"], "_stream_transform": ">= 0.9.4", "node:_stream_transform": [">= 14.18 && < 15", ">= 16"], "_stream_wrap": ">= 1.4.1", "node:_stream_wrap": [">= 14.18 && < 15", ">= 16"], "_stream_passthrough": ">= 0.9.4", "node:_stream_passthrough": [">= 14.18 && < 15", ">= 16"], "_stream_readable": ">= 0.9.4", "node:_stream_readable": [">= 14.18 && < 15", ">= 16"], "_stream_writable": ">= 0.9.4", "node:_stream_writable": [">= 14.18 && < 15", ">= 16"], "stream": true, "node:stream": [">= 14.18 && < 15", ">= 16"], "stream/consumers": ">= 16.7", "node:stream/consumers": ">= 16.7", "stream/promises": ">= 15", "node:stream/promises": ">= 16", "stream/web": ">= 16.5", "node:stream/web": ">= 16.5", "string_decoder": true, "node:string_decoder": [">= 14.18 && < 15", ">= 16"], "sys": [">= 0.4 && < 0.7", ">= 0.8"], "node:sys": [">= 14.18 && < 15", ">= 16"], "test/reporters": ">= 19.9 && < 20.2", "node:test/reporters": [">= 18.17 && < 19", ">= 19.9", ">= 20"], "node:test": [">= 16.17 && < 17", ">= 18"], "timers": true, "node:timers": [">= 14.18 && < 15", ">= 16"], "timers/promises": ">= 15", "node:timers/promises": ">= 16", "_tls_common": ">= 0.11.13", "node:_tls_common": [">= 14.18 && < 15", ">= 16"], "_tls_legacy": ">= 0.11.3 && < 10", "_tls_wrap": ">= 0.11.3", "node:_tls_wrap": [">= 14.18 && < 15", ">= 16"], "tls": true, "node:tls": [">= 14.18 && < 15", ">= 16"], "trace_events": ">= 10", "node:trace_events": [">= 14.18 && < 15", ">= 16"], "tty": true, "node:tty": [">= 14.18 && < 15", ">= 16"], "url": true, "node:url": [">= 14.18 && < 15", ">= 16"], "util": true, "node:util": [">= 14.18 && < 15", ">= 16"], "util/types": ">= 15.3", "node:util/types": ">= 16", "v8/tools/arguments": ">= 10 && < 12", "v8/tools/codemap": [">= 4.4 && < 5", ">= 5.2 && < 12"], "v8/tools/consarray": [">= 4.4 && < 5", ">= 5.2 && < 12"], "v8/tools/csvparser": [">= 4.4 && < 5", ">= 5.2 && < 12"], "v8/tools/logreader": [">= 4.4 && < 5", ">= 5.2 && < 12"], "v8/tools/profile_view": [">= 4.4 && < 5", ">= 5.2 && < 12"], "v8/tools/splaytree": [">= 4.4 && < 5", ">= 5.2 && < 12"], "v8": ">= 1", "node:v8": [">= 14.18 && < 15", ">= 16"], "vm": true, "node:vm": [">= 14.18 && < 15", ">= 16"], "wasi": [">= 13.4 && < 13.5", ">= 18.17 && < 19", ">= 20"], "node:wasi": [">= 18.17 && < 19", ">= 20"], "worker_threads": ">= 11.7", "node:worker_threads": [">= 14.18 && < 15", ">= 16"], "zlib": ">= 0.5", "node:zlib": [">= 14.18 && < 15", ">= 16"] } PK ~\k!tiny-relative-date/src/factory.jsnu[const calculateDelta = (now, date) => Math.round(Math.abs(now - date) / 1000) export default function relativeDateFactory (translations) { return function relativeDate (date, now = new Date()) { if (!(date instanceof Date)) { date = new Date(date) } let delta = null const minute = 60 const hour = minute * 60 const day = hour * 24 const week = day * 7 const month = day * 30 const year = day * 365 delta = calculateDelta(now, date) if (delta > day && delta < week) { date = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0) delta = calculateDelta(now, date) } const translate = (translatePhrase, timeValue) => { let key if (translatePhrase === 'justNow') { key = translatePhrase } else if (now >= date) { key = `${translatePhrase}Ago` } else { key = `${translatePhrase}FromNow` } const translation = translations[key] if (typeof translation === 'function') { return translation(timeValue) } return translation.replace('{{time}}', timeValue) } switch (false) { case !(delta < 30): return translate('justNow') case !(delta < minute): return translate('seconds', delta) case !(delta < 2 * minute): return translate('aMinute') case !(delta < hour): return translate('minutes', Math.floor(delta / minute)) case Math.floor(delta / hour) !== 1: return translate('anHour') case !(delta < day): return translate('hours', Math.floor(delta / hour)) case !(delta < day * 2): return translate('aDay') case !(delta < week): return translate('days', Math.floor(delta / day)) case Math.floor(delta / week) !== 1: return translate('aWeek') case !(delta < month): return translate('weeks', Math.floor(delta / week)) case Math.floor(delta / month) !== 1: return translate('aMonth') case !(delta < year): return translate('months', Math.floor(delta / month)) case Math.floor(delta / year) !== 1: return translate('aYear') default: return translate('overAYear') } } } PK ~\ Ԑtiny-relative-date/src/index.jsnu[import relativeDateFactory from './factory' import enTranslations from '../translations/en' export default relativeDateFactory(enTranslations) PK ~\ gtiny-relative-date/package.jsonnu[{ "_id": "tiny-relative-date@1.3.0", "_inBundle": true, "_location": "/npm/tiny-relative-date", "_phantomChildren": {}, "_requiredBy": [ "/npm" ], "author": { "name": "Joseph Wynn", "email": "joseph@wildlyinaccurate.com", "url": "https://wildlyinaccurate.com/" }, "bugs": { "url": "https://github.com/wildlyinaccurate/relative-date/issues" }, "description": "Tiny function that provides relative, human-readable dates.", "devDependencies": { "babel-cli": "^6.24.1", "babel-plugin-add-module-exports": "^0.2.1", "babel-preset-es2015": "^6.24.1", "babel-register": "^6.24.1", "eslint": "^4.1.0", "eslint-config-standard": "^10.2.1", "eslint-plugin-import": "^2.6.0", "eslint-plugin-node": "^5.0.0", "eslint-plugin-promise": "^3.5.0", "eslint-plugin-standard": "^3.0.1", "jasmine": "^2.6.0", "jasmine-spec-reporter": "^4.1.1" }, "files": [ "lib/", "src/", "translations/" ], "homepage": "https://github.com/wildlyinaccurate/relative-date#readme", "license": "MIT", "main": "lib/index.js", "module": "src/index.js", "name": "tiny-relative-date", "repository": { "type": "git", "url": "git+https://github.com/wildlyinaccurate/relative-date.git" }, "scripts": { "build": "babel src -d lib", "eslint": "eslint --fix src/**/*.js", "jasmine": "jasmine", "prepublish": "npm run build", "test": "npm run eslint && npm run jasmine" }, "version": "1.3.0" } PK ~\ !tiny-relative-date/lib/factory.jsnu['use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = relativeDateFactory; var calculateDelta = function calculateDelta(now, date) { return Math.round(Math.abs(now - date) / 1000); }; function relativeDateFactory(translations) { return function relativeDate(date) { var now = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Date(); if (!(date instanceof Date)) { date = new Date(date); } var delta = null; var minute = 60; var hour = minute * 60; var day = hour * 24; var week = day * 7; var month = day * 30; var year = day * 365; delta = calculateDelta(now, date); if (delta > day && delta < week) { date = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0); delta = calculateDelta(now, date); } var translate = function translate(translatePhrase, timeValue) { var key = void 0; if (translatePhrase === 'justNow') { key = translatePhrase; } else if (now >= date) { key = translatePhrase + 'Ago'; } else { key = translatePhrase + 'FromNow'; } var translation = translations[key]; if (typeof translation === 'function') { return translation(timeValue); } return translation.replace('{{time}}', timeValue); }; switch (false) { case !(delta < 30): return translate('justNow'); case !(delta < minute): return translate('seconds', delta); case !(delta < 2 * minute): return translate('aMinute'); case !(delta < hour): return translate('minutes', Math.floor(delta / minute)); case Math.floor(delta / hour) !== 1: return translate('anHour'); case !(delta < day): return translate('hours', Math.floor(delta / hour)); case !(delta < day * 2): return translate('aDay'); case !(delta < week): return translate('days', Math.floor(delta / day)); case Math.floor(delta / week) !== 1: return translate('aWeek'); case !(delta < month): return translate('weeks', Math.floor(delta / week)); case Math.floor(delta / month) !== 1: return translate('aMonth'); case !(delta < year): return translate('months', Math.floor(delta / month)); case Math.floor(delta / year) !== 1: return translate('aYear'); default: return translate('overAYear'); } }; } module.exports = exports['default'];PK ~\Etiny-relative-date/lib/index.jsnu['use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _factory = require('./factory'); var _factory2 = _interopRequireDefault(_factory); var _en = require('../translations/en'); var _en2 = _interopRequireDefault(_en); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = (0, _factory2.default)(_en2.default); module.exports = exports['default'];PK ~\r,,tiny-relative-date/LICENSE.mdnu[MIT License Copyright (c) 2017 Joseph Wynn Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\  %tiny-relative-date/translations/de.jsnu[module.exports = { justNow: "gerade eben", secondsAgo: "vor {{time}} Sekunden", aMinuteAgo: "vor einer Minute", minutesAgo: "vor {{time}} Minuten", anHourAgo: "vor einer Stunde", hoursAgo: "vor {{time}} Stunden", aDayAgo: "gestern", daysAgo: "vor {{time}} Tagen", aWeekAgo: "letzte Woche", weeksAgo: "vor {{time}} Wochen", aMonthAgo: "letzten Monat", monthsAgo: "vor {{time}} Monaten", aYearAgo: "letztes Jahr", yearsAgo: "vor {{time}} Jahren", overAYearAgo: "vor über einem Jahr", secondsFromNow: "in {{time}} Sekunden", aMinuteFromNow: "in einer Minute", minutesFromNow: "in {{time}} Minuten", anHourFromNow: "in einer Stunde", hoursFromNow: "in {{time}} Stunden", aDayFromNow: "morgen", daysFromNow: "in {{time}} Tagen", aWeekFromNow: "nächste Woche", weeksFromNow: "in {{time}} Wochen", aMonthFromNow: "nächsten Monat", monthsFromNow: "in {{time}} Monaten", aYearFromNow: "nächstes Jahr", yearsFromNow: "in {{time}} Jahren", overAYearFromNow: "in über einem Jahr" } PK ~\KiDD%tiny-relative-date/translations/es.jsnu[module.exports = { justNow: "recién", secondsAgo: "hace {{time}} segundos", aMinuteAgo: "hace un minuto", minutesAgo: "hace {{time}} minutos", anHourAgo: "hace una hora", hoursAgo: "hace {{time}} horas", aDayAgo: "ayer", daysAgo: "hace {{time}} días", aWeekAgo: "hace una semana", weeksAgo: "hace {{time}} semanas", aMonthAgo: "hace un mes", monthsAgo: "hace {{time}} meses", aYearAgo: "hace un año", yearsAgo: "hace {{time}} años", overAYearAgo: "hace mas de un año", secondsFromNow: "dentro de {{time}} segundos", aMinuteFromNow: "dentro de un minuto", minutesFromNow: "dentro de {{time}} minutos", anHourFromNow: "dentro de una hora", hoursFromNow: "dentro de {{time}} horas", aDayFromNow: "mañana", daysFromNow: "dentro de {{time}} días", aWeekFromNow: "dentro de una semana", weeksFromNow: "dentro de {{time}} semanas", aMonthFromNow: "dentro de un mes", monthsFromNow: "dentro de {{time}} meses", aYearFromNow: "dentro de un año", yearsFromNow: "dentro de {{time}} años", overAYearFromNow: "dentro de mas de un año" } PK ~\M %tiny-relative-date/translations/en.jsnu[module.exports = { justNow: "just now", secondsAgo: "{{time}} seconds ago", aMinuteAgo: "a minute ago", minutesAgo: "{{time}} minutes ago", anHourAgo: "an hour ago", hoursAgo: "{{time}} hours ago", aDayAgo: "yesterday", daysAgo: "{{time}} days ago", aWeekAgo: "a week ago", weeksAgo: "{{time}} weeks ago", aMonthAgo: "a month ago", monthsAgo: "{{time}} months ago", aYearAgo: "a year ago", yearsAgo: "{{time}} years ago", overAYearAgo: "over a year ago", secondsFromNow: "{{time}} seconds from now", aMinuteFromNow: "a minute from now", minutesFromNow: "{{time}} minutes from now", anHourFromNow: "an hour from now", hoursFromNow: "{{time}} hours from now", aDayFromNow: "tomorrow", daysFromNow: "{{time}} days from now", aWeekFromNow: "a week from now", weeksFromNow: "{{time}} weeks from now", aMonthFromNow: "a month from now", monthsFromNow: "{{time}} months from now", aYearFromNow: "a year from now", yearsFromNow: "{{time}} years from now", overAYearFromNow: "over a year from now" } PK ~\-$$+tiny-relative-date/translations/en-short.jsnu[module.exports = { justNow: "now", secondsAgo: "{{time}}s", aMinuteAgo: "1m", minutesAgo: "{{time}}m", anHourAgo: "1h", hoursAgo: "{{time}}h", aDayAgo: "1d", daysAgo: "{{time}}d", aWeekAgo: "1w", weeksAgo: "{{time}}w", aMonthAgo: '4w', monthsAgo: (months) => `${Math.round(months / 12 * 52)}w`, aYearAgo: "1y", yearsAgo: "{{time}}y", overAYearAgo: "1y+", secondsFromNow: "+{{time}}s", aMinuteFromNow: "+1m", minutesFromNow: "+{{time}}m", anHourFromNow: "+1h", hoursFromNow: "+{{time}}h", aDayFromNow: "+1d", daysFromNow: "+{{time}}d", aWeekFromNow: "+1w", weeksFromNow: "+{{time}}w", aMonthFromNow: '+4w', monthsFromNow: (months) => `+${Math.round(months / 12 * 52)}w`, aYearFromNow: "+1y", yearsFromNow: "+{{time}}y", overAYearFromNow: "+1y+" } PK ~\VdN%tiny-relative-date/translations/da.jsnu[module.exports = { justNow: "ligenu", secondsAgo: "{{time}} sekunder siden", aMinuteAgo: "et minut siden", minutesAgo: "{{time}} minutter siden", anHourAgo: "en time siden", hoursAgo: "{{time}} timer siden", aDayAgo: "i går", daysAgo: "{{time}} dage siden", aWeekAgo: "en uge siden", weeksAgo: "{{time}} uger siden", aMonthAgo: "en måned siden", monthsAgo: "{{time}} måneder siden", aYearAgo: "et år siden", yearsAgo: "{{time}} år siden", overAYearAgo: "over et år siden", secondsFromNow: "om {{time}} sekunder", aMinuteFromNow: "om et minut", minutesFromNow: "om {{time}} minutter", anHourFromNow: "om en time", hoursFromNow: "om {{time}} timer", aDayFromNow: "i morgen", daysFromNow: "om {{time}} dage", aWeekFromNow: "om en uge", weeksFromNow: "om {{time}} uger", aMonthFromNow: "om en måned", monthsFromNow: "om {{time}} måneder", aYearFromNow: "om et år", yearsFromNow: "om {{time}} år", overAYearFromNow: "om over et år" } PK ~\\Ϯwalk-up-path/package.jsonnu[{ "_id": "walk-up-path@3.0.1", "_inBundle": true, "_location": "/npm/walk-up-path", "_phantomChildren": {}, "_requiredBy": [ "/npm/@npmcli/arborist", "/npm/@npmcli/config", "/npm/libnpmexec" ], "author": { "name": "Isaac Z. Schlueter", "email": "i@izs.me", "url": "https://izs.me" }, "bugs": { "url": "https://github.com/isaacs/walk-up-path/issues" }, "description": "Given a path string, return a generator that walks up the path, emitting each dirname.", "devDependencies": { "@types/node": "^18.15.5", "@types/tap": "^15.0.8", "c8": "^7.13.0", "eslint-config-prettier": "^8.8.0", "prettier": "^2.8.6", "tap": "^16.3.4", "ts-node": "^10.9.1", "typedoc": "^0.23.28", "typescript": "^5.0.2" }, "exports": { ".": { "require": { "types": "./dist/cjs/index.d.ts", "default": "./dist/cjs/index.js" }, "import": { "types": "./dist/mjs/index.d.ts", "default": "./dist/mjs/index.js" } } }, "files": [ "dist" ], "homepage": "https://github.com/isaacs/walk-up-path#readme", "license": "ISC", "main": "./dist/cjs/index.js", "module": "./dist/mjs/index.js", "name": "walk-up-path", "prettier": { "semi": false, "printWidth": 75, "tabWidth": 2, "useTabs": false, "singleQuote": true, "jsxSingleQuote": false, "bracketSameLine": true, "arrowParens": "avoid", "endOfLine": "lf" }, "repository": { "type": "git", "url": "git+https://github.com/isaacs/walk-up-path.git" }, "scripts": { "format": "prettier --write . --loglevel warn", "postversion": "npm publish", "prepare": "tsc -p tsconfig.json && tsc -p tsconfig-esm.json && bash ./scripts/fixup.sh", "prepublishOnly": "git push origin --follow-tags", "presnap": "npm run prepare", "pretest": "npm run prepare", "preversion": "npm test", "snap": "c8 tap", "test": "c8 tap", "typedoc": "typedoc --tsconfig tsconfig-esm.json ./src/*.ts" }, "tap": { "coverage": false, "node-arg": [ "--no-warnings", "--loader", "ts-node/esm" ], "ts": false }, "types": "./dist/mjs/index.d.ts", "version": "3.0.1" } PK ~\?&walk-up-path/LICENSEnu[The ISC License Copyright (c) Isaac Z. Schlueter Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\x"walk-up-path/dist/mjs/package.jsonnu[{ "type": "module" } PK ~\:2BBwalk-up-path/dist/mjs/index.jsnu[import { dirname, resolve } from 'path'; export const walkUp = function* (path) { for (path = resolve(path); path;) { yield path; const pp = dirname(path); if (pp === path) { break; } else { path = pp; } } }; //# sourceMappingURL=index.js.mapPK ~\>"walk-up-path/dist/cjs/package.jsonnu[{ "type": "commonjs" } PK ~\2YRwalk-up-path/dist/cjs/index.jsnu["use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.walkUp = void 0; const path_1 = require("path"); const walkUp = function* (path) { for (path = (0, path_1.resolve)(path); path;) { yield path; const pp = (0, path_1.dirname)(path); if (pp === path) { break; } else { path = pp; } } }; exports.walkUp = walkUp; //# sourceMappingURL=index.js.mapPK ~\J~promise-retry/package.jsonnu[{ "_id": "promise-retry@2.0.1", "_inBundle": true, "_location": "/npm/promise-retry", "_phantomChildren": {}, "_requiredBy": [ "/npm/@npmcli/git", "/npm/@sigstore/sign", "/npm/make-fetch-happen", "/npm/pacote" ], "author": { "name": "IndigoUnited", "email": "hello@indigounited.com", "url": "http://indigounited.com" }, "bugs": { "url": "https://github.com/IndigoUnited/node-promise-retry/issues/" }, "dependencies": { "err-code": "^2.0.2", "retry": "^0.12.0" }, "description": "Retries a function that returns a promise, leveraging the power of the retry module.", "devDependencies": { "expect.js": "^0.3.1", "mocha": "^8.0.1", "sleep-promise": "^8.0.1" }, "engines": { "node": ">=10" }, "homepage": "https://github.com/IndigoUnited/node-promise-retry#readme", "keywords": [ "retry", "promise", "backoff", "repeat", "replay" ], "license": "MIT", "main": "index.js", "name": "promise-retry", "repository": { "type": "git", "url": "git://github.com/IndigoUnited/node-promise-retry.git" }, "scripts": { "test": "mocha --bail -t 10000" }, "version": "2.0.1" } PK ~\promise-retry/test/test.jsnu['use strict'; var expect = require('expect.js'); var promiseRetry = require('../'); var promiseDelay = require('sleep-promise'); describe('promise-retry', function () { it('should call fn again if retry was called', function () { var count = 0; return promiseRetry(function (retry) { count += 1; return promiseDelay(10) .then(function () { if (count <= 2) { retry(new Error('foo')); } return 'final'; }); }, { factor: 1 }) .then(function (value) { expect(value).to.be('final'); expect(count).to.be(3); }, function () { throw new Error('should not fail'); }); }); it('should call fn with the attempt number', function () { var count = 0; return promiseRetry(function (retry, number) { count += 1; expect(count).to.equal(number); return promiseDelay(10) .then(function () { if (count <= 2) { retry(new Error('foo')); } return 'final'; }); }, { factor: 1 }) .then(function (value) { expect(value).to.be('final'); expect(count).to.be(3); }, function () { throw new Error('should not fail'); }); }); it('should not retry on fulfillment if retry was not called', function () { var count = 0; return promiseRetry(function () { count += 1; return promiseDelay(10) .then(function () { return 'final'; }); }) .then(function (value) { expect(value).to.be('final'); expect(count).to.be(1); }, function () { throw new Error('should not fail'); }); }); it('should not retry on rejection if retry was not called', function () { var count = 0; return promiseRetry(function () { count += 1; return promiseDelay(10) .then(function () { throw new Error('foo'); }); }) .then(function () { throw new Error('should not succeed'); }, function (err) { expect(err.message).to.be('foo'); expect(count).to.be(1); }); }); it('should not retry on rejection if nr of retries is 0', function () { var count = 0; return promiseRetry(function (retry) { count += 1; return promiseDelay(10) .then(function () { throw new Error('foo'); }) .catch(retry); }, { retries : 0 }) .then(function () { throw new Error('should not succeed'); }, function (err) { expect(err.message).to.be('foo'); expect(count).to.be(1); }); }); it('should reject the promise if the retries were exceeded', function () { var count = 0; return promiseRetry(function (retry) { count += 1; return promiseDelay(10) .then(function () { throw new Error('foo'); }) .catch(retry); }, { retries: 2, factor: 1 }) .then(function () { throw new Error('should not succeed'); }, function (err) { expect(err.message).to.be('foo'); expect(count).to.be(3); }); }); it('should pass options to the underlying retry module', function () { var count = 0; return promiseRetry(function (retry) { return promiseDelay(10) .then(function () { if (count < 2) { count += 1; retry(new Error('foo')); } return 'final'; }); }, { retries: 1, factor: 1 }) .then(function () { throw new Error('should not succeed'); }, function (err) { expect(err.message).to.be('foo'); }); }); it('should convert direct fulfillments into promises', function () { return promiseRetry(function () { return 'final'; }, { factor: 1 }) .then(function (value) { expect(value).to.be('final'); }, function () { throw new Error('should not fail'); }); }); it('should convert direct rejections into promises', function () { promiseRetry(function () { throw new Error('foo'); }, { retries: 1, factor: 1 }) .then(function () { throw new Error('should not succeed'); }, function (err) { expect(err.message).to.be('foo'); }); }); it('should not crash on undefined rejections', function () { return promiseRetry(function () { throw undefined; }, { retries: 1, factor: 1 }) .then(function () { throw new Error('should not succeed'); }, function (err) { expect(err).to.be(undefined); }) .then(function () { return promiseRetry(function (retry) { retry(); }, { retries: 1, factor: 1 }); }) .then(function () { throw new Error('should not succeed'); }, function (err) { expect(err).to.be(undefined); }); }); it('should retry if retry() was called with undefined', function () { var count = 0; return promiseRetry(function (retry) { count += 1; return promiseDelay(10) .then(function () { if (count <= 2) { retry(); } return 'final'; }); }, { factor: 1 }) .then(function (value) { expect(value).to.be('final'); expect(count).to.be(3); }, function () { throw new Error('should not fail'); }); }); it('should work with several retries in the same chain', function () { var count = 0; return promiseRetry(function (retry) { count += 1; return promiseDelay(10) .then(function () { retry(new Error('foo')); }) .catch(function (err) { retry(err); }); }, { retries: 1, factor: 1 }) .then(function () { throw new Error('should not succeed'); }, function (err) { expect(err.message).to.be('foo'); expect(count).to.be(2); }); }); it('should allow options to be passed first', function () { var count = 0; return promiseRetry({ factor: 1 }, function (retry) { count += 1; return promiseDelay(10) .then(function () { if (count <= 2) { retry(new Error('foo')); } return 'final'; }); }).then(function (value) { expect(value).to.be('final'); expect(count).to.be(3); }, function () { throw new Error('should not fail'); }); }); }); PK ~\b  promise-retry/LICENSEnu[Copyright (c) 2014 IndigoUnited Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\4bbpromise-retry/index.jsnu['use strict'; var errcode = require('err-code'); var retry = require('retry'); var hasOwn = Object.prototype.hasOwnProperty; function isRetryError(err) { return err && err.code === 'EPROMISERETRY' && hasOwn.call(err, 'retried'); } function promiseRetry(fn, options) { var temp; var operation; if (typeof fn === 'object' && typeof options === 'function') { // Swap options and fn when using alternate signature (options, fn) temp = options; options = fn; fn = temp; } operation = retry.operation(options); return new Promise(function (resolve, reject) { operation.attempt(function (number) { Promise.resolve() .then(function () { return fn(function (err) { if (isRetryError(err)) { err = err.retried; } throw errcode(new Error('Retrying'), 'EPROMISERETRY', { retried: err }); }, number); }) .then(resolve, function (err) { if (isRetryError(err)) { err = err.retried; if (operation.retry(err || new Error())) { return; } } reject(err); }); }); }); } module.exports = promiseRetry; PK ~\Fݠspdx-correct/package.jsonnu[{ "_id": "spdx-correct@3.2.0", "_inBundle": true, "_location": "/npm/spdx-correct", "_phantomChildren": { "spdx-exceptions": "2.5.0", "spdx-license-ids": "3.0.18" }, "_requiredBy": [ "/npm/validate-npm-package-license" ], "bugs": { "url": "https://github.com/jslicense/spdx-correct.js/issues" }, "dependencies": { "spdx-expression-parse": "^3.0.0", "spdx-license-ids": "^3.0.0" }, "description": "correct invalid SPDX expressions", "devDependencies": { "defence-cli": "^3.0.1", "replace-require-self": "^1.0.0", "standard": "^14.3.4", "standard-markdown": "^6.0.0", "tape": "^5.0.1" }, "files": [ "index.js" ], "homepage": "https://github.com/jslicense/spdx-correct.js#readme", "keywords": [ "SPDX", "law", "legal", "license", "metadata" ], "license": "Apache-2.0", "name": "spdx-correct", "repository": { "type": "git", "url": "git+https://github.com/jslicense/spdx-correct.js.git" }, "scripts": { "lint": "standard && standard-markdown README.md", "test": "defence README.md | replace-require-self | node && node test.js" }, "version": "3.2.0" } PK ~\v <spdx-correct/node_modules/spdx-expression-parse/package.jsonnu[{ "_id": "spdx-expression-parse@3.0.1", "_inBundle": true, "_location": "/npm/spdx-correct/spdx-expression-parse", "_phantomChildren": {}, "_requiredBy": [ "/npm/spdx-correct" ], "author": { "name": "Kyle E. Mitchell", "email": "kyle@kemitchell.com", "url": "https://kemitchell.com" }, "bugs": { "url": "https://github.com/jslicense/spdx-expression-parse.js/issues" }, "contributors": [ { "name": "C. Scott Ananian", "email": "cscott@cscott.net", "url": "http://cscott.net" }, { "name": "Kyle E. Mitchell", "email": "kyle@kemitchell.com", "url": "https://kemitchell.com" }, { "name": "Shinnosuke Watanabe", "email": "snnskwtnb@gmail.com" }, { "name": "Antoine Motet", "email": "antoine.motet@gmail.com" } ], "dependencies": { "spdx-exceptions": "^2.1.0", "spdx-license-ids": "^3.0.0" }, "description": "parse SPDX license expressions", "devDependencies": { "defence-cli": "^3.0.1", "replace-require-self": "^1.0.0", "standard": "^14.1.0" }, "files": [ "AUTHORS", "index.js", "parse.js", "scan.js" ], "homepage": "https://github.com/jslicense/spdx-expression-parse.js#readme", "keywords": [ "SPDX", "law", "legal", "license", "metadata", "package", "package.json", "standards" ], "license": "MIT", "name": "spdx-expression-parse", "repository": { "type": "git", "url": "git+https://github.com/jslicense/spdx-expression-parse.js.git" }, "scripts": { "lint": "standard", "test": "npm run test:suite && npm run test:readme", "test:readme": "defence -i javascript README.md | replace-require-self | node", "test:suite": "node test.js" }, "version": "3.0.1" } PK ~\WW7spdx-correct/node_modules/spdx-expression-parse/LICENSEnu[The MIT License Copyright (c) 2015 Kyle E. Mitchell & other authors listed in AUTHORS Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\]M8spdx-correct/node_modules/spdx-expression-parse/index.jsnu['use strict' var scan = require('./scan') var parse = require('./parse') module.exports = function (source) { return parse(scan(source)) } PK ~\YU U 8spdx-correct/node_modules/spdx-expression-parse/parse.jsnu['use strict' // The ABNF grammar in the spec is totally ambiguous. // // This parser follows the operator precedence defined in the // `Order of Precedence and Parentheses` section. module.exports = function (tokens) { var index = 0 function hasMore () { return index < tokens.length } function token () { return hasMore() ? tokens[index] : null } function next () { if (!hasMore()) { throw new Error() } index++ } function parseOperator (operator) { var t = token() if (t && t.type === 'OPERATOR' && operator === t.string) { next() return t.string } } function parseWith () { if (parseOperator('WITH')) { var t = token() if (t && t.type === 'EXCEPTION') { next() return t.string } throw new Error('Expected exception after `WITH`') } } function parseLicenseRef () { // TODO: Actually, everything is concatenated into one string // for backward-compatibility but it could be better to return // a nice structure. var begin = index var string = '' var t = token() if (t.type === 'DOCUMENTREF') { next() string += 'DocumentRef-' + t.string + ':' if (!parseOperator(':')) { throw new Error('Expected `:` after `DocumentRef-...`') } } t = token() if (t.type === 'LICENSEREF') { next() string += 'LicenseRef-' + t.string return { license: string } } index = begin } function parseLicense () { var t = token() if (t && t.type === 'LICENSE') { next() var node = { license: t.string } if (parseOperator('+')) { node.plus = true } var exception = parseWith() if (exception) { node.exception = exception } return node } } function parseParenthesizedExpression () { var left = parseOperator('(') if (!left) { return } var expr = parseExpression() if (!parseOperator(')')) { throw new Error('Expected `)`') } return expr } function parseAtom () { return ( parseParenthesizedExpression() || parseLicenseRef() || parseLicense() ) } function makeBinaryOpParser (operator, nextParser) { return function parseBinaryOp () { var left = nextParser() if (!left) { return } if (!parseOperator(operator)) { return left } var right = parseBinaryOp() if (!right) { throw new Error('Expected expression') } return { left: left, conjunction: operator.toLowerCase(), right: right } } } var parseAnd = makeBinaryOpParser('AND', parseAtom) var parseExpression = makeBinaryOpParser('OR', parseAnd) var node = parseExpression() if (!node || hasMore()) { throw new Error('Syntax error') } return node } PK ~\ d 7spdx-correct/node_modules/spdx-expression-parse/scan.jsnu['use strict' var licenses = [] .concat(require('spdx-license-ids')) .concat(require('spdx-license-ids/deprecated')) var exceptions = require('spdx-exceptions') module.exports = function (source) { var index = 0 function hasMore () { return index < source.length } // `value` can be a regexp or a string. // If it is recognized, the matching source string is returned and // the index is incremented. Otherwise `undefined` is returned. function read (value) { if (value instanceof RegExp) { var chars = source.slice(index) var match = chars.match(value) if (match) { index += match[0].length return match[0] } } else { if (source.indexOf(value, index) === index) { index += value.length return value } } } function skipWhitespace () { read(/[ ]*/) } function operator () { var string var possibilities = ['WITH', 'AND', 'OR', '(', ')', ':', '+'] for (var i = 0; i < possibilities.length; i++) { string = read(possibilities[i]) if (string) { break } } if (string === '+' && index > 1 && source[index - 2] === ' ') { throw new Error('Space before `+`') } return string && { type: 'OPERATOR', string: string } } function idstring () { return read(/[A-Za-z0-9-.]+/) } function expectIdstring () { var string = idstring() if (!string) { throw new Error('Expected idstring at offset ' + index) } return string } function documentRef () { if (read('DocumentRef-')) { var string = expectIdstring() return { type: 'DOCUMENTREF', string: string } } } function licenseRef () { if (read('LicenseRef-')) { var string = expectIdstring() return { type: 'LICENSEREF', string: string } } } function identifier () { var begin = index var string = idstring() if (licenses.indexOf(string) !== -1) { return { type: 'LICENSE', string: string } } else if (exceptions.indexOf(string) !== -1) { return { type: 'EXCEPTION', string: string } } index = begin } // Tries to read the next token. Returns `undefined` if no token is // recognized. function parseToken () { // Ordering matters return ( operator() || documentRef() || licenseRef() || identifier() ) } var tokens = [] while (hasMore()) { skipWhitespace() if (!hasMore()) { break } var token = parseToken() if (!token) { throw new Error('Unexpected `' + source[index] + '` at offset ' + index) } tokens.push(token) } return tokens } PK ~\BF.7spdx-correct/node_modules/spdx-expression-parse/AUTHORSnu[C. Scott Ananian (http://cscott.net) Kyle E. Mitchell (https://kemitchell.com) Shinnosuke Watanabe Antoine Motet PK ~\^,^,spdx-correct/LICENSEnu[ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. PK ~\[`d**spdx-correct/index.jsnu[/* Copyright spdx-correct.js contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ var parse = require('spdx-expression-parse') var spdxLicenseIds = require('spdx-license-ids') function valid (string) { try { parse(string) return true } catch (error) { return false } } // Sorting function that orders the given array of transpositions such // that a transposition with the longer pattern comes before a transposition // with a shorter pattern. This is to prevent e.g. the transposition // ["General Public License", "GPL"] from matching to "Lesser General Public License" // before a longer and more accurate transposition ["Lesser General Public License", "LGPL"] // has a chance to be recognized. function sortTranspositions(a, b) { var length = b[0].length - a[0].length if (length !== 0) return length return a[0].toUpperCase().localeCompare(b[0].toUpperCase()) } // Common transpositions of license identifier acronyms var transpositions = [ ['APGL', 'AGPL'], ['Gpl', 'GPL'], ['GLP', 'GPL'], ['APL', 'Apache'], ['ISD', 'ISC'], ['GLP', 'GPL'], ['IST', 'ISC'], ['Claude', 'Clause'], [' or later', '+'], [' International', ''], ['GNU', 'GPL'], ['GUN', 'GPL'], ['+', ''], ['GNU GPL', 'GPL'], ['GNU LGPL', 'LGPL'], ['GNU/GPL', 'GPL'], ['GNU GLP', 'GPL'], ['GNU LESSER GENERAL PUBLIC LICENSE', 'LGPL'], ['GNU Lesser General Public License', 'LGPL'], ['GNU LESSER GENERAL PUBLIC LICENSE', 'LGPL-2.1'], ['GNU Lesser General Public License', 'LGPL-2.1'], ['LESSER GENERAL PUBLIC LICENSE', 'LGPL'], ['Lesser General Public License', 'LGPL'], ['LESSER GENERAL PUBLIC LICENSE', 'LGPL-2.1'], ['Lesser General Public License', 'LGPL-2.1'], ['GNU General Public License', 'GPL'], ['Gnu public license', 'GPL'], ['GNU Public License', 'GPL'], ['GNU GENERAL PUBLIC LICENSE', 'GPL'], ['MTI', 'MIT'], ['Mozilla Public License', 'MPL'], ['Universal Permissive License', 'UPL'], ['WTH', 'WTF'], ['WTFGPL', 'WTFPL'], ['-License', ''] ].sort(sortTranspositions) var TRANSPOSED = 0 var CORRECT = 1 // Simple corrections to nearly valid identifiers. var transforms = [ // e.g. 'mit' function (argument) { return argument.toUpperCase() }, // e.g. 'MIT ' function (argument) { return argument.trim() }, // e.g. 'M.I.T.' function (argument) { return argument.replace(/\./g, '') }, // e.g. 'Apache- 2.0' function (argument) { return argument.replace(/\s+/g, '') }, // e.g. 'CC BY 4.0'' function (argument) { return argument.replace(/\s+/g, '-') }, // e.g. 'LGPLv2.1' function (argument) { return argument.replace('v', '-') }, // e.g. 'Apache 2.0' function (argument) { return argument.replace(/,?\s*(\d)/, '-$1') }, // e.g. 'GPL 2' function (argument) { return argument.replace(/,?\s*(\d)/, '-$1.0') }, // e.g. 'Apache Version 2.0' function (argument) { return argument .replace(/,?\s*(V\.|v\.|V|v|Version|version)\s*(\d)/, '-$2') }, // e.g. 'Apache Version 2' function (argument) { return argument .replace(/,?\s*(V\.|v\.|V|v|Version|version)\s*(\d)/, '-$2.0') }, // e.g. 'ZLIB' function (argument) { return argument[0].toUpperCase() + argument.slice(1) }, // e.g. 'MPL/2.0' function (argument) { return argument.replace('/', '-') }, // e.g. 'Apache 2' function (argument) { return argument .replace(/\s*V\s*(\d)/, '-$1') .replace(/(\d)$/, '$1.0') }, // e.g. 'GPL-2.0', 'GPL-3.0' function (argument) { if (argument.indexOf('3.0') !== -1) { return argument + '-or-later' } else { return argument + '-only' } }, // e.g. 'GPL-2.0-' function (argument) { return argument + 'only' }, // e.g. 'GPL2' function (argument) { return argument.replace(/(\d)$/, '-$1.0') }, // e.g. 'BSD 3' function (argument) { return argument.replace(/(-| )?(\d)$/, '-$2-Clause') }, // e.g. 'BSD clause 3' function (argument) { return argument.replace(/(-| )clause(-| )(\d)/, '-$3-Clause') }, // e.g. 'New BSD license' function (argument) { return argument.replace(/\b(Modified|New|Revised)(-| )?BSD((-| )License)?/i, 'BSD-3-Clause') }, // e.g. 'Simplified BSD license' function (argument) { return argument.replace(/\bSimplified(-| )?BSD((-| )License)?/i, 'BSD-2-Clause') }, // e.g. 'Free BSD license' function (argument) { return argument.replace(/\b(Free|Net)(-| )?BSD((-| )License)?/i, 'BSD-2-Clause-$1BSD') }, // e.g. 'Clear BSD license' function (argument) { return argument.replace(/\bClear(-| )?BSD((-| )License)?/i, 'BSD-3-Clause-Clear') }, // e.g. 'Old BSD License' function (argument) { return argument.replace(/\b(Old|Original)(-| )?BSD((-| )License)?/i, 'BSD-4-Clause') }, // e.g. 'BY-NC-4.0' function (argument) { return 'CC-' + argument }, // e.g. 'BY-NC' function (argument) { return 'CC-' + argument + '-4.0' }, // e.g. 'Attribution-NonCommercial' function (argument) { return argument .replace('Attribution', 'BY') .replace('NonCommercial', 'NC') .replace('NoDerivatives', 'ND') .replace(/ (\d)/, '-$1') .replace(/ ?International/, '') }, // e.g. 'Attribution-NonCommercial' function (argument) { return 'CC-' + argument .replace('Attribution', 'BY') .replace('NonCommercial', 'NC') .replace('NoDerivatives', 'ND') .replace(/ (\d)/, '-$1') .replace(/ ?International/, '') + '-4.0' } ] var licensesWithVersions = spdxLicenseIds .map(function (id) { var match = /^(.*)-\d+\.\d+$/.exec(id) return match ? [match[0], match[1]] : [id, null] }) .reduce(function (objectMap, item) { var key = item[1] objectMap[key] = objectMap[key] || [] objectMap[key].push(item[0]) return objectMap }, {}) var licensesWithOneVersion = Object.keys(licensesWithVersions) .map(function makeEntries (key) { return [key, licensesWithVersions[key]] }) .filter(function identifySoleVersions (item) { return ( // Licenses has just one valid version suffix. item[1].length === 1 && item[0] !== null && // APL will be considered Apache, rather than APL-1.0 item[0] !== 'APL' ) }) .map(function createLastResorts (item) { return [item[0], item[1][0]] }) licensesWithVersions = undefined // If all else fails, guess that strings containing certain substrings // meant to identify certain licenses. var lastResorts = [ ['UNLI', 'Unlicense'], ['WTF', 'WTFPL'], ['2 CLAUSE', 'BSD-2-Clause'], ['2-CLAUSE', 'BSD-2-Clause'], ['3 CLAUSE', 'BSD-3-Clause'], ['3-CLAUSE', 'BSD-3-Clause'], ['AFFERO', 'AGPL-3.0-or-later'], ['AGPL', 'AGPL-3.0-or-later'], ['APACHE', 'Apache-2.0'], ['ARTISTIC', 'Artistic-2.0'], ['Affero', 'AGPL-3.0-or-later'], ['BEER', 'Beerware'], ['BOOST', 'BSL-1.0'], ['BSD', 'BSD-2-Clause'], ['CDDL', 'CDDL-1.1'], ['ECLIPSE', 'EPL-1.0'], ['FUCK', 'WTFPL'], ['GNU', 'GPL-3.0-or-later'], ['LGPL', 'LGPL-3.0-or-later'], ['GPLV1', 'GPL-1.0-only'], ['GPL-1', 'GPL-1.0-only'], ['GPLV2', 'GPL-2.0-only'], ['GPL-2', 'GPL-2.0-only'], ['GPL', 'GPL-3.0-or-later'], ['MIT +NO-FALSE-ATTRIBS', 'MITNFA'], ['MIT', 'MIT'], ['MPL', 'MPL-2.0'], ['X11', 'X11'], ['ZLIB', 'Zlib'] ].concat(licensesWithOneVersion).sort(sortTranspositions) var SUBSTRING = 0 var IDENTIFIER = 1 var validTransformation = function (identifier) { for (var i = 0; i < transforms.length; i++) { var transformed = transforms[i](identifier).trim() if (transformed !== identifier && valid(transformed)) { return transformed } } return null } var validLastResort = function (identifier) { var upperCased = identifier.toUpperCase() for (var i = 0; i < lastResorts.length; i++) { var lastResort = lastResorts[i] if (upperCased.indexOf(lastResort[SUBSTRING]) > -1) { return lastResort[IDENTIFIER] } } return null } var anyCorrection = function (identifier, check) { for (var i = 0; i < transpositions.length; i++) { var transposition = transpositions[i] var transposed = transposition[TRANSPOSED] if (identifier.indexOf(transposed) > -1) { var corrected = identifier.replace( transposed, transposition[CORRECT] ) var checked = check(corrected) if (checked !== null) { return checked } } } return null } module.exports = function (identifier, options) { options = options || {} var upgrade = options.upgrade === undefined ? true : !!options.upgrade function postprocess (value) { return upgrade ? upgradeGPLs(value) : value } var validArugment = ( typeof identifier === 'string' && identifier.trim().length !== 0 ) if (!validArugment) { throw Error('Invalid argument. Expected non-empty string.') } identifier = identifier.trim() if (valid(identifier)) { return postprocess(identifier) } var noPlus = identifier.replace(/\+$/, '').trim() if (valid(noPlus)) { return postprocess(noPlus) } var transformed = validTransformation(identifier) if (transformed !== null) { return postprocess(transformed) } transformed = anyCorrection(identifier, function (argument) { if (valid(argument)) { return argument } return validTransformation(argument) }) if (transformed !== null) { return postprocess(transformed) } transformed = validLastResort(identifier) if (transformed !== null) { return postprocess(transformed) } transformed = anyCorrection(identifier, validLastResort) if (transformed !== null) { return postprocess(transformed) } return null } function upgradeGPLs (value) { if ([ 'GPL-1.0', 'LGPL-1.0', 'AGPL-1.0', 'GPL-2.0', 'LGPL-2.0', 'AGPL-2.0', 'LGPL-2.1' ].indexOf(value) !== -1) { return value + '-only' } else if ([ 'GPL-1.0+', 'GPL-2.0+', 'GPL-3.0+', 'LGPL-2.0+', 'LGPL-2.1+', 'LGPL-3.0+', 'AGPL-1.0+', 'AGPL-3.0+' ].indexOf(value) !== -1) { return value.replace(/\+$/, '-or-later') } else if (['GPL-3.0', 'LGPL-3.0', 'AGPL-3.0'].indexOf(value) !== -1) { return value + '-or-later' } else { return value } } PK ~\libnpmpack/package.jsonnu[{ "_id": "libnpmpack@7.0.3", "_inBundle": true, "_location": "/npm/libnpmpack", "_phantomChildren": {}, "_requiredBy": [ "/npm" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/libnpmpack/issues" }, "contributors": [ { "name": "Claudia Hernández", "email": "claudia@npmjs.com" } ], "dependencies": { "@npmcli/arborist": "^7.5.3", "@npmcli/run-script": "^8.1.0", "npm-package-arg": "^11.0.2", "pacote": "^18.0.6" }, "description": "Programmatic API for the bits behind npm pack", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.22.0", "nock": "^13.3.3", "spawk": "^1.7.1", "tap": "^16.3.8" }, "engines": { "node": "^16.14.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://npmjs.com/package/libnpmpack", "license": "ISC", "main": "lib/index.js", "name": "libnpmpack", "repository": { "type": "git", "url": "git+https://github.com/npm/cli.git", "directory": "workspaces/libnpmpack" }, "scripts": { "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.22.0", "content": "../../scripts/template-oss/index.js" }, "version": "7.0.3" } PK ~\BJ##libnpmpack/lib/index.jsnu['use strict' const pacote = require('pacote') const npa = require('npm-package-arg') const runScript = require('@npmcli/run-script') const path = require('node:path') const Arborist = require('@npmcli/arborist') const { writeFile } = require('node:fs/promises') module.exports = pack async function pack (spec = 'file:.', opts = {}) { // gets spec spec = npa(spec) const manifest = await pacote.manifest(spec, opts) const stdio = opts.foregroundScripts ? 'inherit' : 'pipe' if (spec.type === 'directory' && !opts.ignoreScripts) { // prepack await runScript({ ...opts, event: 'prepack', path: spec.fetchSpec, stdio, pkg: manifest, }) } // packs tarball const tarball = await pacote.tarball(manifest._resolved, { ...opts, Arborist, integrity: manifest._integrity, }) // check for explicit `false` so the default behavior is to skip writing to disk if (opts.dryRun === false) { const filename = `${manifest.name}-${manifest.version}.tgz` .replace(/^@/, '').replace(/\//, '-') const destination = path.resolve(opts.packDestination, filename) await writeFile(destination, tarball) } if (spec.type === 'directory' && !opts.ignoreScripts) { // postpack await runScript({ ...opts, event: 'postpack', path: spec.fetchSpec, stdio, pkg: manifest, env: { npm_package_from: tarball.from, npm_package_resolved: tarball.resolved, npm_package_integrity: tarball.integrity, }, }) } return tarball } PK ~\gXlibnpmpack/LICENSEnu[Copyright npm, Inc Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\g{'libnpmpack/README.mdnu[# libnpmpack [![npm version](https://img.shields.io/npm/v/libnpmpack.svg)](https://npm.im/libnpmpack) [![license](https://img.shields.io/npm/l/libnpmpack.svg)](https://npm.im/libnpmpack) [![CI - libnpmpack](https://github.com/npm/cli/actions/workflows/ci-libnpmpack.yml/badge.svg)](https://github.com/npm/cli/actions/workflows/ci-libnpmpack.yml) [`libnpmpack`](https://github.com/npm/libnpmpack) is a Node.js library for programmatically packing tarballs from a local directory or from a registry or github spec. If packing from a local source, `libnpmpack` will also run the `prepack` and `postpack` lifecycles. ## Table of Contents * [Example](#example) * [Install](#install) * [API](#api) * [`pack()`](#pack) ## Example ```js const pack = require('libnpmpack') ``` ## Install `$ npm install libnpmpack` ### API #### `> pack(spec, [opts]) -> Promise` Packs a tarball from a local directory or from a registry or github spec and returns a Promise that resolves to the tarball data Buffer, with from, resolved, and integrity fields attached. If no options are passed, the tarball file will be saved on the same directory from which `pack` was called in. `libnpmpack` uses [`pacote`](https://npm.im/pacote). Most options are passed through directly to that library, so please refer to [its own `opts` documentation](https://www.npmjs.com/package/pacote#options) for options that can be passed in. ##### Examples ```javascript // packs from cwd const tarball = await pack() // packs from a local directory const localTar = await pack('/Users/claudiahdz/projects/my-cool-pkg') // packs from a registry spec const registryTar = await pack('abbrev@1.0.3') // packs from a github spec const githubTar = await pack('isaacs/rimraf#PR-192') ``` PK ~\Rcidr-regex/package.jsonnu[{ "_id": "cidr-regex@4.1.1", "_inBundle": true, "_location": "/npm/cidr-regex", "_phantomChildren": {}, "_requiredBy": [ "/npm/is-cidr" ], "author": { "name": "silverwind", "email": "me@silverwind.io" }, "bugs": { "url": "https://github.com/silverwind/cidr-regex/issues" }, "contributors": [ { "name": "Felipe Apostol", "email": "flipjs.io@gmail.com", "url": "http://flipjs.io/" } ], "dependencies": { "ip-regex": "^5.0.0" }, "description": "Regular expression for matching IP addresses in CIDR notation", "devDependencies": { "@types/node": "20.12.12", "eslint": "8.57.0", "eslint-config-silverwind": "85.1.4", "eslint-config-silverwind-typescript": "3.2.7", "typescript": "5.4.5", "typescript-config-silverwind": "4.3.2", "updates": "16.1.1", "versions": "12.0.2", "vite": "5.2.11", "vite-config-silverwind": "1.1.2", "vite-plugin-dts": "3.9.1", "vitest": "1.6.0", "vitest-config-silverwind": "9.0.6" }, "engines": { "node": ">=14" }, "exports": "./dist/index.js", "files": [ "dist" ], "homepage": "https://github.com/silverwind/cidr-regex#readme", "license": "BSD-2-Clause", "main": "./dist/index.js", "name": "cidr-regex", "repository": { "type": "git", "url": "git+https://github.com/silverwind/cidr-regex.git" }, "sideEffects": false, "type": "module", "types": "./dist/index.d.ts", "version": "4.1.1" } PK ~\)  cidr-regex/LICENSEnu[Copyright (c) silverwind All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. PK ~\H*hcidr-regex/dist/index.jsnu[import ipRegex from "ip-regex"; const defaultOpts = { exact: false }; const v4str = `${ipRegex.v4().source}\\/(3[0-2]|[12]?[0-9])`; const v6str = `${ipRegex.v6().source}\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])`; const v4exact = new RegExp(`^${v4str}$`); const v6exact = new RegExp(`^${v6str}$`); const v46exact = new RegExp(`(?:^${v4str}$)|(?:^${v6str}$)`); const cidrRegex = ({ exact } = defaultOpts) => exact ? v46exact : new RegExp(`(?:${v4str})|(?:${v6str})`, "g"); const v4 = cidrRegex.v4 = ({ exact } = defaultOpts) => exact ? v4exact : new RegExp(v4str, "g"); const v6 = cidrRegex.v6 = ({ exact } = defaultOpts) => exact ? v6exact : new RegExp(v6str, "g"); export { cidrRegex as default, v4, v6 }; PK ~\[ exponential-backoff/package.jsonnu[{ "_id": "exponential-backoff@3.1.1", "_inBundle": true, "_location": "/npm/exponential-backoff", "_phantomChildren": {}, "_requiredBy": [ "/npm/node-gyp" ], "author": { "name": "Sami Sayegh" }, "bugs": { "url": "https://github.com/coveo/exponential-backoff/issues" }, "description": "A utility that allows retrying a function with an exponential delay between attempts.", "devDependencies": { "@types/jest": "^24.0.18", "@types/node": "^10.14.21", "husky": "^3.0.9", "jest": "^24.9.0", "lint-staged": "^9.4.2", "prettier": "^1.18.2", "ts-jest": "^24.1.0", "typescript": "^3.6.4" }, "files": [ "dist/" ], "homepage": "https://github.com/coveo/exponential-backoff#readme", "husky": { "hooks": { "pre-commit": "lint-staged" } }, "jest": { "transform": { "^.+\\.ts$": "ts-jest" }, "testRegex": "\\.spec\\.ts$", "moduleFileExtensions": [ "ts", "js" ] }, "keywords": [ "exponential", "backoff", "retry" ], "license": "Apache-2.0", "lint-staged": { "*.{ts,json,md}": [ "prettier --write", "git add" ] }, "main": "dist/backoff.js", "name": "exponential-backoff", "repository": { "type": "git", "url": "git+https://github.com/coveo/exponential-backoff.git" }, "scripts": { "build": "tsc", "test": "jest", "test:watch": "jest --watch" }, "types": "dist/backoff.d.ts", "version": "3.1.1" } PK ~\ >],],exponential-backoff/LICENSEnu[ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.PK ~\z/O/exponential-backoff/dist/jitter/no/no.jitter.jsnu["use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function noJitter(delay) { return delay; } exports.noJitter = noJitter; //# sourceMappingURL=no.jitter.js.mapPK ~\Yy(  3exponential-backoff/dist/jitter/full/full.jitter.jsnu["use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function fullJitter(delay) { var jitteredDelay = Math.random() * delay; return Math.round(jitteredDelay); } exports.fullJitter = fullJitter; //# sourceMappingURL=full.jitter.js.mapPK ~\m#1exponential-backoff/dist/jitter/jitter.factory.jsnu["use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var full_jitter_1 = require("./full/full.jitter"); var no_jitter_1 = require("./no/no.jitter"); function JitterFactory(options) { switch (options.jitter) { case "full": return full_jitter_1.fullJitter; case "none": default: return no_jitter_1.noJitter; } } exports.JitterFactory = JitterFactory; //# sourceMappingURL=jitter.factory.js.mapPK ~\txx1exponential-backoff/dist/delay/delay.interface.jsnu["use strict"; Object.defineProperty(exports, "__esModule", { value: true }); //# sourceMappingURL=delay.interface.js.mapPK ~\z5exponential-backoff/dist/delay/always/always.delay.jsnu["use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var delay_base_1 = require("../delay.base"); var AlwaysDelay = /** @class */ (function (_super) { __extends(AlwaysDelay, _super); function AlwaysDelay() { return _super !== null && _super.apply(this, arguments) || this; } return AlwaysDelay; }(delay_base_1.Delay)); exports.AlwaysDelay = AlwaysDelay; //# sourceMappingURL=always.delay.js.mapPK ~\%=exponential-backoff/dist/delay/skip-first/skip-first.delay.jsnu["use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; Object.defineProperty(exports, "__esModule", { value: true }); var delay_base_1 = require("../delay.base"); var SkipFirstDelay = /** @class */ (function (_super) { __extends(SkipFirstDelay, _super); function SkipFirstDelay() { return _super !== null && _super.apply(this, arguments) || this; } SkipFirstDelay.prototype.apply = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, this.isFirstAttempt ? true : _super.prototype.apply.call(this)]; }); }); }; Object.defineProperty(SkipFirstDelay.prototype, "isFirstAttempt", { get: function () { return this.attempt === 0; }, enumerable: true, configurable: true }); Object.defineProperty(SkipFirstDelay.prototype, "numOfDelayedAttempts", { get: function () { return this.attempt - 1; }, enumerable: true, configurable: true }); return SkipFirstDelay; }(delay_base_1.Delay)); exports.SkipFirstDelay = SkipFirstDelay; //# sourceMappingURL=skip-first.delay.js.mapPK ~\Hee/exponential-backoff/dist/delay/delay.factory.jsnu["use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var skip_first_delay_1 = require("./skip-first/skip-first.delay"); var always_delay_1 = require("./always/always.delay"); function DelayFactory(options, attempt) { var delay = initDelayClass(options); delay.setAttemptNumber(attempt); return delay; } exports.DelayFactory = DelayFactory; function initDelayClass(options) { if (!options.delayFirstAttempt) { return new skip_first_delay_1.SkipFirstDelay(options); } return new always_delay_1.AlwaysDelay(options); } //# sourceMappingURL=delay.factory.js.mapPK ~\}j,exponential-backoff/dist/delay/delay.base.jsnu["use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var jitter_factory_1 = require("../jitter/jitter.factory"); var Delay = /** @class */ (function () { function Delay(options) { this.options = options; this.attempt = 0; } Delay.prototype.apply = function () { var _this = this; return new Promise(function (resolve) { return setTimeout(resolve, _this.jitteredDelay); }); }; Delay.prototype.setAttemptNumber = function (attempt) { this.attempt = attempt; }; Object.defineProperty(Delay.prototype, "jitteredDelay", { get: function () { var jitter = jitter_factory_1.JitterFactory(this.options); return jitter(this.delay); }, enumerable: true, configurable: true }); Object.defineProperty(Delay.prototype, "delay", { get: function () { var constant = this.options.startingDelay; var base = this.options.timeMultiple; var power = this.numOfDelayedAttempts; var delay = constant * Math.pow(base, power); return Math.min(delay, this.options.maxDelay); }, enumerable: true, configurable: true }); Object.defineProperty(Delay.prototype, "numOfDelayedAttempts", { get: function () { return this.attempt; }, enumerable: true, configurable: true }); return Delay; }()); exports.Delay = Delay; //# sourceMappingURL=delay.base.js.mapPK ~\Ś""#exponential-backoff/dist/backoff.jsnu["use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; Object.defineProperty(exports, "__esModule", { value: true }); var options_1 = require("./options"); var delay_factory_1 = require("./delay/delay.factory"); function backOff(request, options) { if (options === void 0) { options = {}; } return __awaiter(this, void 0, void 0, function () { var sanitizedOptions, backOff; return __generator(this, function (_a) { switch (_a.label) { case 0: sanitizedOptions = options_1.getSanitizedOptions(options); backOff = new BackOff(request, sanitizedOptions); return [4 /*yield*/, backOff.execute()]; case 1: return [2 /*return*/, _a.sent()]; } }); }); } exports.backOff = backOff; var BackOff = /** @class */ (function () { function BackOff(request, options) { this.request = request; this.options = options; this.attemptNumber = 0; } BackOff.prototype.execute = function () { return __awaiter(this, void 0, void 0, function () { var e_1, shouldRetry; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!!this.attemptLimitReached) return [3 /*break*/, 7]; _a.label = 1; case 1: _a.trys.push([1, 4, , 6]); return [4 /*yield*/, this.applyDelay()]; case 2: _a.sent(); return [4 /*yield*/, this.request()]; case 3: return [2 /*return*/, _a.sent()]; case 4: e_1 = _a.sent(); this.attemptNumber++; return [4 /*yield*/, this.options.retry(e_1, this.attemptNumber)]; case 5: shouldRetry = _a.sent(); if (!shouldRetry || this.attemptLimitReached) { throw e_1; } return [3 /*break*/, 6]; case 6: return [3 /*break*/, 0]; case 7: throw new Error("Something went wrong."); } }); }); }; Object.defineProperty(BackOff.prototype, "attemptLimitReached", { get: function () { return this.attemptNumber >= this.options.numOfAttempts; }, enumerable: true, configurable: true }); BackOff.prototype.applyDelay = function () { return __awaiter(this, void 0, void 0, function () { var delay; return __generator(this, function (_a) { switch (_a.label) { case 0: delay = delay_factory_1.DelayFactory(this.options, this.attemptNumber); return [4 /*yield*/, delay.apply()]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; return BackOff; }()); //# sourceMappingURL=backoff.js.mapPK ~\V.a#exponential-backoff/dist/options.jsnu["use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; Object.defineProperty(exports, "__esModule", { value: true }); var defaultOptions = { delayFirstAttempt: false, jitter: "none", maxDelay: Infinity, numOfAttempts: 10, retry: function () { return true; }, startingDelay: 100, timeMultiple: 2 }; function getSanitizedOptions(options) { var sanitized = __assign(__assign({}, defaultOptions), options); if (sanitized.numOfAttempts < 1) { sanitized.numOfAttempts = 1; } return sanitized; } exports.getSanitizedOptions = getSanitizedOptions; //# sourceMappingURL=options.js.mapPK ~\fVIInpm-audit-report/package.jsonnu[{ "_id": "npm-audit-report@5.0.0", "_inBundle": true, "_location": "/npm/npm-audit-report", "_phantomChildren": {}, "_requiredBy": [ "/npm" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/npm-audit-report/issues" }, "description": "Given a response from the npm security api, render it into a variety of security reports", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.14.1", "chalk": "^5.2.0", "tap": "^16.0.0" }, "directories": { "lib": "lib", "test": "test" }, "engines": { "node": "^14.17.0 || ^16.13.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/npm-audit-report#readme", "keywords": [ "npm", "security", "report", "audit" ], "license": "ISC", "main": "lib/index.js", "name": "npm-audit-report", "repository": { "type": "git", "url": "git+https://github.com/npm/npm-audit-report.git" }, "scripts": { "lint": "eslint \"**/*.js\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "check-coverage": true, "coverage-map": "map.js", "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.14.1" }, "version": "5.0.0" } PK ~\ڥ!npm-audit-report/lib/exit-code.jsnu[// return 1 if any vulns in the set are at or above the specified severity const severities = new Map(Object.entries([ 'info', 'low', 'moderate', 'high', 'critical', 'none', ]).map(s => s.reverse())) module.exports = (data, level) => Object.entries(data.metadata.vulnerabilities) .some(([sev, count]) => count > 0 && severities.has(sev) && severities.get(sev) >= severities.get(level)) ? 1 : 0 PK ~\Ǐnpm-audit-report/lib/index.jsnu['use strict' const reporters = { install: require('./reporters/install'), detail: require('./reporters/detail'), json: require('./reporters/json'), quiet: require('./reporters/quiet'), } const exitCode = require('./exit-code.js') module.exports = Object.assign((data, options = {}) => { const { reporter = 'install', chalk, unicode = true, indent = 2, } = options // CLI defaults this to `null` so the defaulting method above doesn't work const auditLevel = options.auditLevel || 'low' if (!data) { throw Object.assign( new TypeError('ENOAUDITDATA'), { code: 'ENOAUDITDATA', message: 'missing audit data', } ) } if (typeof data.toJSON === 'function') { data = data.toJSON() } return { report: reporters[reporter](data, { chalk, unicode, indent }), exitCode: exitCode(data, auditLevel), } }, { reporters }) PK ~\\e e (npm-audit-report/lib/reporters/detail.jsnu['use strict' const colors = require('../colors.js') const install = require('./install.js') module.exports = (data, { chalk }) => { const summary = install.summary(data, { chalk }) const none = data.metadata.vulnerabilities.total === 0 return none ? summary : fullReport(data, { chalk, summary }) } const fullReport = (data, { chalk, summary }) => { const c = colors(chalk) const output = [c.white('# npm audit report'), ''] const printed = new Set() for (const [, vuln] of Object.entries(data.vulnerabilities)) { // only print starting from the top-level advisories if (vuln.via.filter(v => typeof v !== 'string').length !== 0) { output.push(printVuln(vuln, c, data.vulnerabilities, printed)) } } output.push(summary) return output.join('\n') } const printVuln = (vuln, c, vulnerabilities, printed, indent = '') => { if (printed.has(vuln)) { return null } printed.add(vuln) const output = [] output.push(c.white(vuln.name) + ' ' + vuln.range) if (indent === '' && (vuln.severity !== 'low' || vuln.severity === 'info')) { output.push(`Severity: ${c.severity(vuln.severity)}`) } for (const via of vuln.via) { if (typeof via === 'string') { output.push(`Depends on vulnerable versions of ${c.white(via)}`) } else if (indent === '') { output.push(`${c.white(via.title)} - ${via.url}`) } } if (indent === '') { const { fixAvailable: fa } = vuln if (fa === false) { output.push(c.red('No fix available')) } else if (fa === true) { output.push(c.green('fix available') + ' via `npm audit fix`') } else { /* istanbul ignore else - should be impossible, just being cautious */ if (typeof fa === 'object' && indent === '') { output.push( `${c.yellow('fix available')} via \`npm audit fix --force\``, `Will install ${fa.name}@${fa.version}` + `, which is ${fa.isSemVerMajor ? 'a breaking change' : 'outside the stated dependency range'}` ) } } } for (const path of vuln.nodes) { output.push(c.dim(path)) } for (const effect of vuln.effects) { const e = printVuln(vulnerabilities[effect], c, vulnerabilities, printed, ' ') if (e) { output.push(...e.split('\n')) } } if (indent === '') { output.push('') } return output.map(l => `${indent}${l}`).join('\n') } PK ~\$A  )npm-audit-report/lib/reporters/install.jsnu[const colors = require('../colors.js') const calculate = (data, { chalk }) => { const c = colors(chalk) const output = [] const { metadata: { vulnerabilities } } = data const vulnCount = vulnerabilities.total let someFixable = false let someForceFixable = false let forceFixSemVerMajor = false let someUnfixable = false if (vulnCount === 0) { output.push(`found ${c.green('0')} vulnerabilities`) } else { for (const [, vuln] of Object.entries(data.vulnerabilities)) { const { fixAvailable } = vuln someFixable = someFixable || fixAvailable === true someUnfixable = someUnfixable || fixAvailable === false if (typeof fixAvailable === 'object') { someForceFixable = true forceFixSemVerMajor = forceFixSemVerMajor || fixAvailable.isSemVerMajor } } const total = vulnerabilities.total const sevs = Object.entries(vulnerabilities).filter(([s, count]) => { return (s === 'low' || s === 'moderate' || s === 'high' || s === 'critical') && count > 0 }) if (sevs.length > 1) { const severities = sevs.map(([s, count]) => { return `${count} ${c.severity(s)}` }).join(', ') output.push(`${c.red(total)} vulnerabilities (${severities})`) } else { const [sev, count] = sevs[0] output.push(`${count} ${c.severity(sev)} severity vulnerabilit${count === 1 ? 'y' : 'ies'}`) } // XXX use a different footer line if some aren't fixable easily. // just 'run `npm audit` for details' maybe? if (someFixable) { output.push('', 'To address ' + (someForceFixable || someUnfixable ? 'issues that do not require attention' : 'all issues') + ', run:\n npm audit fix') } if (someForceFixable) { output.push('', 'To address all issues' + (someUnfixable ? ' possible' : '') + (forceFixSemVerMajor ? ' (including breaking changes)' : '') + ', run:\n npm audit fix --force') } if (someUnfixable) { output.push('', 'Some issues need review, and may require choosing', 'a different dependency.') } } const summary = output.join('\n') return { summary, report: vulnCount > 0 ? `${summary}\n\nRun \`npm audit\` for details.` : summary, } } module.exports = Object.assign((data, opt) => calculate(data, opt).report, { summary: (data, opt) => calculate(data, opt).summary, }) PK ~\:T'npm-audit-report/lib/reporters/quiet.jsnu[module.exports = () => '' PK ~\%JJ&npm-audit-report/lib/reporters/json.jsnu[module.exports = (data, { indent }) => JSON.stringify(data, null, indent) PK ~\R{WA??npm-audit-report/lib/colors.jsnu[module.exports = (chalk) => { const green = s => chalk.green.bold(s) const red = s => chalk.red.bold(s) const magenta = s => chalk.magenta.bold(s) const yellow = s => chalk.yellow.bold(s) const white = s => chalk.bold(s) const severity = (sev, s) => sev.toLowerCase() === 'moderate' ? yellow(s || sev) : sev.toLowerCase() === 'high' ? red(s || sev) : sev.toLowerCase() === 'critical' ? magenta(s || sev) : white(s || sev) const dim = s => chalk.dim(s) return { dim, green, red, magenta, yellow, white, severity, } } PK ~\ gnpm-audit-report/LICENSEnu[ISC License Copyright (c) npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE COPYRIGHT HOLDER DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\npm-profile/package.jsonnu[{ "_id": "npm-profile@10.0.0", "_inBundle": true, "_location": "/npm/npm-profile", "_phantomChildren": {}, "_requiredBy": [ "/npm" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/npm-profile/issues" }, "dependencies": { "npm-registry-fetch": "^17.0.1", "proc-log": "^4.0.0" }, "description": "Library for updating an npmjs.com profile", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.21.4", "nock": "^13.2.4", "tap": "^16.0.1" }, "engines": { "node": ">=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/npm-profile#readme", "keywords": [], "license": "ISC", "main": "./lib/index.js", "name": "npm-profile", "repository": { "type": "git", "url": "git+https://github.com/npm/npm-profile.git" }, "scripts": { "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "check-coverage": true, "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.21.4", "publish": true }, "version": "10.0.0" } PK ~\Bnpm-profile/lib/index.jsnu[const { URL } = require('node:url') const timers = require('node:timers/promises') const fetch = require('npm-registry-fetch') const { HttpErrorBase } = require('npm-registry-fetch/lib/errors') const { log } = require('proc-log') // try loginWeb, catch the "not supported" message and fall back to couch const login = async (opener, prompter, opts = {}) => { try { return await loginWeb(opener, opts) } catch (er) { if (er instanceof WebLoginNotSupported) { log.verbose('web login', 'not supported, trying couch') const { username, password } = await prompter(opts.creds) return loginCouch(username, password, opts) } throw er } } const adduser = async (opener, prompter, opts = {}) => { try { return await adduserWeb(opener, opts) } catch (er) { if (er instanceof WebLoginNotSupported) { log.verbose('web adduser', 'not supported, trying couch') const { username, email, password } = await prompter(opts.creds) return adduserCouch(username, email, password, opts) } throw er } } const adduserWeb = (opener, opts = {}) => { log.verbose('web adduser', 'before first POST') return webAuth(opener, opts, { create: true }) } const loginWeb = (opener, opts = {}) => { log.verbose('web login', 'before first POST') return webAuth(opener, opts, {}) } const isValidUrl = u => { try { return /^https?:$/.test(new URL(u).protocol) } catch { return false } } const webAuth = async (opener, opts, body) => { try { const res = await fetch('/-/v1/login', { ...opts, method: 'POST', body, }) const content = await res.json() log.verbose('web auth', 'got response', content) const { doneUrl, loginUrl } = content if (!isValidUrl(doneUrl) || !isValidUrl(loginUrl)) { throw new WebLoginInvalidResponse('POST', res, content) } return await webAuthOpener(opener, loginUrl, doneUrl, opts) } catch (er) { if ((er.statusCode >= 400 && er.statusCode <= 499) || er.statusCode === 500) { throw new WebLoginNotSupported('POST', { status: er.statusCode, headers: er.headers, }, er.body) } throw er } } const webAuthOpener = async (opener, loginUrl, doneUrl, opts) => { const abortController = new AbortController() const { signal } = abortController try { log.verbose('web auth', 'opening url pair') const [, authResult] = await Promise.all([ opener(loginUrl, { signal }).catch((err) => { if (err.name === 'AbortError') { abortController.abort() return } throw err }), webAuthCheckLogin(doneUrl, { ...opts, cache: false }, { signal }).then((r) => { log.verbose('web auth', 'done-check finished') abortController.abort() return r }), ]) return authResult } catch (er) { abortController.abort() throw er } } const webAuthCheckLogin = async (doneUrl, opts, { signal } = {}) => { signal?.throwIfAborted() const res = await fetch(doneUrl, opts) const content = await res.json() if (res.status === 200) { if (!content.token) { throw new WebLoginInvalidResponse('GET', res, content) } return content } if (res.status === 202) { const retry = +res.headers.get('retry-after') * 1000 if (retry > 0) { await timers.setTimeout(retry, null, { ref: false, signal }) } return webAuthCheckLogin(doneUrl, opts, { signal }) } throw new WebLoginInvalidResponse('GET', res, content) } const couchEndpoint = (username) => `/-/user/org.couchdb.user:${encodeURIComponent(username)}` const putCouch = async (path, username, body, opts) => { const result = await fetch.json(`${couchEndpoint(username)}${path}`, { ...opts, method: 'PUT', body, }) result.username = username return result } const adduserCouch = async (username, email, password, opts = {}) => { const body = { _id: `org.couchdb.user:${username}`, name: username, password: password, email: email, type: 'user', roles: [], date: new Date().toISOString(), } log.verbose('adduser', 'before first PUT', { ...body, password: 'XXXXX', }) return putCouch('', username, body, opts) } const loginCouch = async (username, password, opts = {}) => { const body = { _id: `org.couchdb.user:${username}`, name: username, password: password, type: 'user', roles: [], date: new Date().toISOString(), } log.verbose('login', 'before first PUT', { ...body, password: 'XXXXX', }) try { return await putCouch('', username, body, opts) } catch (err) { if (err.code === 'E400') { err.message = `There is no user with the username "${username}".` throw err } if (err.code !== 'E409') { throw err } } const result = await fetch.json(couchEndpoint(username), { ...opts, query: { write: true }, }) for (const k of Object.keys(result)) { if (!body[k] || k === 'roles') { body[k] = result[k] } } return putCouch(`/-rev/${body._rev}`, username, body, { ...opts, forceAuth: { username, password: Buffer.from(password, 'utf8').toString('base64'), otp: opts.otp, }, }) } const get = (opts = {}) => fetch.json('/-/npm/v1/user', opts) const set = (profile, opts = {}) => fetch.json('/-/npm/v1/user', { ...opts, method: 'POST', // profile keys can't be empty strings, but they CAN be null body: Object.fromEntries(Object.entries(profile).map(([k, v]) => [k, v === '' ? null : v])), }) const paginate = async (href, opts, items = []) => { const result = await fetch.json(href, opts) items = items.concat(result.objects) if (result.urls.next) { return paginate(result.urls.next, opts, items) } return items } const listTokens = (opts = {}) => paginate('/-/npm/v1/tokens', opts) const removeToken = async (tokenKey, opts = {}) => { await fetch(`/-/npm/v1/tokens/token/${tokenKey}`, { ...opts, method: 'DELETE', ignoreBody: true, }) return null } const createToken = (password, readonly, cidrs, opts = {}) => fetch.json('/-/npm/v1/tokens', { ...opts, method: 'POST', body: { password: password, readonly: readonly, cidr_whitelist: cidrs, }, }) class WebLoginInvalidResponse extends HttpErrorBase { constructor (method, res, body) { super(method, res, body) this.message = 'Invalid response from web login endpoint' } } class WebLoginNotSupported extends HttpErrorBase { constructor (method, res, body) { super(method, res, body) this.message = 'Web login not supported' this.code = 'ENYI' } } module.exports = { adduserCouch, loginCouch, adduserWeb, loginWeb, login, adduser, get, set, listTokens, removeToken, createToken, webAuthCheckLogin, webAuthOpener, } PK ~\rnpm-profile/LICENSE.mdnu[ ISC License Copyright npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND NPM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NPM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\q6ttlibnpmfund/package.jsonnu[{ "_id": "libnpmfund@5.0.11", "_inBundle": true, "_location": "/npm/libnpmfund", "_phantomChildren": {}, "_requiredBy": [ "/npm" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/cli/issues" }, "contributors": [ { "name": "Ruy Adorno", "url": "https://ruyadorno.com" } ], "dependencies": { "@npmcli/arborist": "^7.5.3" }, "description": "Programmatic API for npm fund", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.22.0", "tap": "^16.3.8" }, "engines": { "node": "^16.14.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/cli#readme", "keywords": [ "npm", "npmcli", "libnpm", "cli", "git", "fund", "gitfund" ], "license": "ISC", "main": "lib/index.js", "name": "libnpmfund", "repository": { "type": "git", "url": "git+https://github.com/npm/cli.git", "directory": "workspaces/libnpmfund" }, "scripts": { "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.22.0", "content": "../../scripts/template-oss/index.js" }, "version": "5.0.11" } PK ~\x7biilibnpmfund/lib/index.jsnu['use strict' const URL = require('node:url').URL const Arborist = require('@npmcli/arborist') // supports object funding and string shorthand, or an array of these // if original was an array, returns an array; else returns the lone item function normalizeFunding (funding) { const normalizeItem = item => typeof item === 'string' ? { url: item } : item const sources = [].concat(funding || []).map(normalizeItem) return Array.isArray(funding) ? sources : sources[0] } // Is the value of a `funding` property of a `package.json` // a valid type+url for `npm fund` to display? function isValidFunding (funding) { if (!funding) { return false } if (Array.isArray(funding)) { return funding.every(f => !Array.isArray(f) && isValidFunding(f)) } try { var parsed = new URL(funding.url || funding) } catch (error) { return false } if ( parsed.protocol !== 'https:' && parsed.protocol !== 'http:' ) { return false } return Boolean(parsed.host) } const empty = () => Object.create(null) function readTree (tree, opts) { let packageWithFundingCount = 0 const seen = new Set() const { countOnly } = opts || {} const _trailingDependencies = Symbol('trailingDependencies') let filterSet if (opts && opts.workspaces && opts.workspaces.length) { const arb = new Arborist(opts) filterSet = arb.workspaceDependencySet(tree, opts.workspaces) } function tracked (name, version) { const key = String(name) + String(version) if (seen.has(key)) { return true } seen.add(key) } function retrieveDependencies (dependencies) { const trailing = dependencies[_trailingDependencies] if (trailing) { return Object.assign( empty(), dependencies, trailing ) } return dependencies } function hasDependencies (dependencies) { return dependencies && ( Object.keys(dependencies).length || dependencies[_trailingDependencies] ) } function attachFundingInfo (target, funding) { if (funding && isValidFunding(funding)) { target.funding = normalizeFunding(funding) packageWithFundingCount++ } } function getFundingDependencies (t) { const edges = t && t.edgesOut && t.edgesOut.values() if (!edges) { return empty() } const directDepsWithFunding = Array.from(edges).map(edge => { if (!edge || !edge.to) { return empty() } const node = edge.to.target || edge.to if (!node.package) { return empty() } if (filterSet && filterSet.size > 0 && !filterSet.has(node)) { return empty() } const { name, funding, version } = node.package // avoids duplicated items within the funding tree if (tracked(name, version)) { return empty() } const fundingItem = {} if (version) { fundingItem.version = version } attachFundingInfo(fundingItem, funding) return { node, fundingItem, } }) return directDepsWithFunding.reduce( (res, { node, fundingItem }) => { if (!fundingItem || fundingItem.length === 0 || !node) { return res } // recurse const transitiveDependencies = node.edgesOut && node.edgesOut.size > 0 && getFundingDependencies(node) // if we're only counting items there's no need // to add all the data to the resulting object if (countOnly) { return null } if (hasDependencies(transitiveDependencies)) { fundingItem.dependencies = retrieveDependencies(transitiveDependencies) } if (isValidFunding(fundingItem.funding)) { res[node.package.name] = fundingItem } else if (hasDependencies(fundingItem.dependencies)) { res[_trailingDependencies] = Object.assign( empty(), res[_trailingDependencies], fundingItem.dependencies ) } return res }, countOnly ? null : empty()) } const treeDependencies = getFundingDependencies(tree) const result = { length: packageWithFundingCount, } if (!countOnly) { const name = (tree && tree.package && tree.package.name) || (tree && tree.name) result.name = name || (tree && tree.path) if (tree && tree.package && tree.package.version) { result.version = tree.package.version } if (tree && tree.package && tree.package.funding) { result.funding = normalizeFunding(tree.package.funding) } result.dependencies = retrieveDependencies(treeDependencies) } return result } async function read (opts) { const arb = new Arborist(opts) const tree = await arb.loadActual(opts) return readTree(tree, opts) } module.exports = { read, readTree, normalizeFunding, isValidFunding, } PK ~\tlibnpmfund/LICENSEnu[The ISC License Copyright (c) npm Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\j==libnpmfund/README.mdnu[# libnpmfund [![npm version](https://img.shields.io/npm/v/libnpmfund.svg)](https://npm.im/libnpmfund) [![license](https://img.shields.io/npm/l/libnpmfund.svg)](https://npm.im/libnpmfund) [![CI - libnpmfund](https://github.com/npm/cli/actions/workflows/ci-libnpmfund.yml/badge.svg)](https://github.com/npm/cli/actions/workflows/ci-libnpmfund.yml) [`libnpmfund`](https://github.com/npm/libnpmfund) is a Node.js library for retrieving **funding** information for packages installed using [`arborist`](https://github.com/npm/arborist). ## Table of Contents * [Example](#example) * [Install](#install) * [Contributing](#contributing) * [API](#api) * [LICENSE](#license) ## Example ```js const { read } = require('libnpmfund') const fundingInfo = await read() console.log( JSON.stringify(fundingInfo, null, 2) ) // => { length: 2, name: 'foo', version: '1.0.0', funding: { url: 'https://example.com' }, dependencies: { bar: { version: '1.0.0', funding: { url: 'http://collective.example.com' } } } } ``` ## Install `$ npm install libnpmfund` ### Contributing The npm team enthusiastically welcomes contributions and project participation! There's a bunch of things you can do if you want to contribute! The [Contributor Guide](https://github.com/npm/cli/blob/latest/CONTRIBUTING.md) outlines the process for community interaction and contribution. Please don't hesitate to jump in if you'd like to, or even ask us questions if something isn't clear. All participants and maintainers in this project are expected to follow the [npm Code of Conduct](https://www.npmjs.com/policies/conduct), and just generally be excellent to each other. Please refer to the [Changelog](CHANGELOG.md) for project history details, too. Happy hacking! ### API ##### `> fund.read([opts]) -> Promise` Reads **funding** info from a npm install and returns a promise for a tree object that only contains packages in which funding info is defined. Options: - `countOnly`: Uses the tree-traversal logic from **npm fund** but skips over any obj definition and just returns an obj containing `{ length }` - useful for things such as printing a `6 packages are looking for funding` msg. - `workspaces`: `Array` List of workspaces names to filter for, the result will only include a subset of the resulting tree that includes only the nodes that are children of the listed workspaces names. - `path`, `registry` and more [Arborist](https://github.com/npm/arborist/) options. ##### `> fund.readTree(tree, [opts]) -> Promise` Reads **funding** info from a given install tree and returns a tree object that only contains packages in which funding info is defined. - `tree`: An [`arborist`](https://github.com/npm/arborist) tree to be used, e.g: ```js const Arborist = require('@npmcli/arborist') const { readTree } = require('libnpmfund') const arb = new Arborist({ path: process.cwd() }) const tree = await arb.loadActual() return readTree(tree, { countOnly: false }) ``` Options: - `countOnly`: Uses the tree-traversal logic from **npm fund** but skips over any obj definition and just returns an obj containing `{ length }` - useful for things such as printing a `6 packages are looking for funding` msg. ##### `> fund.normalizeFunding(funding) -> Object` From a `funding` ``, retrieves normalized funding objects containing a `url` property. e.g: ```js normalizeFunding('http://example.com') // => { url: 'http://example.com' } ``` ##### `> fund.isValidFunding(funding) -> Boolean` Returns `` if `funding` is a valid funding object, e.g: ```js isValidFunding({ foo: 'not a valid funding obj' }) // => false isValidFunding('http://example.com') // => true ``` ## LICENSE [ISC](./LICENSE) PK ~\b%Izzisexe/windows.jsnu[module.exports = isexe isexe.sync = sync var fs = require('fs') function checkPathExt (path, options) { var pathext = options.pathExt !== undefined ? options.pathExt : process.env.PATHEXT if (!pathext) { return true } pathext = pathext.split(';') if (pathext.indexOf('') !== -1) { return true } for (var i = 0; i < pathext.length; i++) { var p = pathext[i].toLowerCase() if (p && path.substr(-p.length).toLowerCase() === p) { return true } } return false } function checkStat (stat, path, options) { if (!stat.isSymbolicLink() && !stat.isFile()) { return false } return checkPathExt(path, options) } function isexe (path, options, cb) { fs.stat(path, function (er, stat) { cb(er, er ? false : checkStat(stat, path, options)) }) } function sync (path, options) { return checkStat(fs.statSync(path), path, options) } PK ~\#0isexe/package.jsonnu[{ "_id": "isexe@2.0.0", "_inBundle": true, "_location": "/npm/isexe", "_phantomChildren": {}, "_requiredBy": [ "/npm/cross-spawn/which" ], "author": { "name": "Isaac Z. Schlueter", "email": "i@izs.me", "url": "http://blog.izs.me/" }, "bugs": { "url": "https://github.com/isaacs/isexe/issues" }, "description": "Minimal module to check if a file is executable.", "devDependencies": { "mkdirp": "^0.5.1", "rimraf": "^2.5.0", "tap": "^10.3.0" }, "directories": { "test": "test" }, "homepage": "https://github.com/isaacs/isexe#readme", "keywords": [], "license": "ISC", "main": "index.js", "name": "isexe", "repository": { "type": "git", "url": "git+https://github.com/isaacs/isexe.git" }, "scripts": { "postpublish": "git push origin --all; git push origin --tags", "postversion": "npm publish", "preversion": "npm test", "test": "tap test/*.js --100" }, "version": "2.0.0" } PK ~\8NS isexe/mode.jsnu[module.exports = isexe isexe.sync = sync var fs = require('fs') function isexe (path, options, cb) { fs.stat(path, function (er, stat) { cb(er, er ? false : checkStat(stat, options)) }) } function sync (path, options) { return checkStat(fs.statSync(path), options) } function checkStat (stat, options) { return stat.isFile() && checkMode(stat, options) } function checkMode (stat, options) { var mod = stat.mode var uid = stat.uid var gid = stat.gid var myUid = options.uid !== undefined ? options.uid : process.getuid && process.getuid() var myGid = options.gid !== undefined ? options.gid : process.getgid && process.getgid() var u = parseInt('100', 8) var g = parseInt('010', 8) var o = parseInt('001', 8) var ug = u | g var ret = (mod & o) || (mod & g) && gid === myGid || (mod & u) && uid === myUid || (mod & ug) && myUid === 0 return ret } PK ~\oaӄisexe/test/basic.jsnu[var t = require('tap') var fs = require('fs') var path = require('path') var fixture = path.resolve(__dirname, 'fixtures') var meow = fixture + '/meow.cat' var mine = fixture + '/mine.cat' var ours = fixture + '/ours.cat' var fail = fixture + '/fail.false' var noent = fixture + '/enoent.exe' var mkdirp = require('mkdirp') var rimraf = require('rimraf') var isWindows = process.platform === 'win32' var hasAccess = typeof fs.access === 'function' var winSkip = isWindows && 'windows' var accessSkip = !hasAccess && 'no fs.access function' var hasPromise = typeof Promise === 'function' var promiseSkip = !hasPromise && 'no global Promise' function reset () { delete require.cache[require.resolve('../')] return require('../') } t.test('setup fixtures', function (t) { rimraf.sync(fixture) mkdirp.sync(fixture) fs.writeFileSync(meow, '#!/usr/bin/env cat\nmeow\n') fs.chmodSync(meow, parseInt('0755', 8)) fs.writeFileSync(fail, '#!/usr/bin/env false\n') fs.chmodSync(fail, parseInt('0644', 8)) fs.writeFileSync(mine, '#!/usr/bin/env cat\nmine\n') fs.chmodSync(mine, parseInt('0744', 8)) fs.writeFileSync(ours, '#!/usr/bin/env cat\nours\n') fs.chmodSync(ours, parseInt('0754', 8)) t.end() }) t.test('promise', { skip: promiseSkip }, function (t) { var isexe = reset() t.test('meow async', function (t) { isexe(meow).then(function (is) { t.ok(is) t.end() }) }) t.test('fail async', function (t) { isexe(fail).then(function (is) { t.notOk(is) t.end() }) }) t.test('noent async', function (t) { isexe(noent).catch(function (er) { t.ok(er) t.end() }) }) t.test('noent ignore async', function (t) { isexe(noent, { ignoreErrors: true }).then(function (is) { t.notOk(is) t.end() }) }) t.end() }) t.test('no promise', function (t) { global.Promise = null var isexe = reset() t.throws('try to meow a promise', function () { isexe(meow) }) t.end() }) t.test('access', { skip: accessSkip || winSkip }, function (t) { runTest(t) }) t.test('mode', { skip: winSkip }, function (t) { delete fs.access delete fs.accessSync var isexe = reset() t.ok(isexe.sync(ours, { uid: 0, gid: 0 })) t.ok(isexe.sync(mine, { uid: 0, gid: 0 })) runTest(t) }) t.test('windows', function (t) { global.TESTING_WINDOWS = true var pathExt = '.EXE;.CAT;.CMD;.COM' t.test('pathExt option', function (t) { runTest(t, { pathExt: '.EXE;.CAT;.CMD;.COM' }) }) t.test('pathExt env', function (t) { process.env.PATHEXT = pathExt runTest(t) }) t.test('no pathExt', function (t) { // with a pathExt of '', any filename is fine. // so the "fail" one would still pass. runTest(t, { pathExt: '', skipFail: true }) }) t.test('pathext with empty entry', function (t) { // with a pathExt of '', any filename is fine. // so the "fail" one would still pass. runTest(t, { pathExt: ';' + pathExt, skipFail: true }) }) t.end() }) t.test('cleanup', function (t) { rimraf.sync(fixture) t.end() }) function runTest (t, options) { var isexe = reset() var optionsIgnore = Object.create(options || {}) optionsIgnore.ignoreErrors = true if (!options || !options.skipFail) { t.notOk(isexe.sync(fail, options)) } t.notOk(isexe.sync(noent, optionsIgnore)) if (!options) { t.ok(isexe.sync(meow)) } else { t.ok(isexe.sync(meow, options)) } t.ok(isexe.sync(mine, options)) t.ok(isexe.sync(ours, options)) t.throws(function () { isexe.sync(noent, options) }) t.test('meow async', function (t) { if (!options) { isexe(meow, function (er, is) { if (er) { throw er } t.ok(is) t.end() }) } else { isexe(meow, options, function (er, is) { if (er) { throw er } t.ok(is) t.end() }) } }) t.test('mine async', function (t) { isexe(mine, options, function (er, is) { if (er) { throw er } t.ok(is) t.end() }) }) t.test('ours async', function (t) { isexe(ours, options, function (er, is) { if (er) { throw er } t.ok(is) t.end() }) }) if (!options || !options.skipFail) { t.test('fail async', function (t) { isexe(fail, options, function (er, is) { if (er) { throw er } t.notOk(is) t.end() }) }) } t.test('noent async', function (t) { isexe(noent, options, function (er, is) { t.ok(er) t.notOk(is) t.end() }) }) t.test('noent ignore async', function (t) { isexe(noent, optionsIgnore, function (er, is) { if (er) { throw er } t.notOk(is) t.end() }) }) t.test('directory is not executable', function (t) { isexe(__dirname, options, function (er, is) { if (er) { throw er } t.notOk(is) t.end() }) }) t.end() } PK ~\aGW isexe/LICENSEnu[The ISC License Copyright (c) Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\isexe/index.jsnu[var fs = require('fs') var core if (process.platform === 'win32' || global.TESTING_WINDOWS) { core = require('./windows.js') } else { core = require('./mode.js') } module.exports = isexe isexe.sync = sync function isexe (path, options, cb) { if (typeof options === 'function') { cb = options options = {} } if (!cb) { if (typeof Promise !== 'function') { throw new TypeError('callback not provided') } return new Promise(function (resolve, reject) { isexe(path, options || {}, function (er, is) { if (er) { reject(er) } else { resolve(is) } }) }) } core(path, options || {}, function (er, is) { // ignore EACCES because that just means we aren't allowed to run it if (er) { if (er.code === 'EACCES' || options && options.ignoreErrors) { er = null is = false } } cb(er, is) }) } function sync (path, options) { // my kingdom for a filtered catch try { return core.sync(path, options || {}) } catch (er) { if (options && options.ignoreErrors || er.code === 'EACCES') { return false } else { throw er } } } PK ~\cr%% parse-conflict-json/package.jsonnu[{ "_id": "parse-conflict-json@3.0.1", "_inBundle": true, "_location": "/npm/parse-conflict-json", "_phantomChildren": {}, "_requiredBy": [ "/npm", "/npm/@npmcli/arborist" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/parse-conflict-json/issues" }, "dependencies": { "json-parse-even-better-errors": "^3.0.0", "just-diff": "^6.0.0", "just-diff-apply": "^5.2.0" }, "description": "Parse a JSON string that has git merge conflicts, resolving if possible", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.12.0", "tap": "^16.0.1" }, "engines": { "node": "^14.17.0 || ^16.13.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/parse-conflict-json#readme", "license": "ISC", "main": "lib", "name": "parse-conflict-json", "repository": { "type": "git", "url": "git+https://github.com/npm/parse-conflict-json.git" }, "scripts": { "lint": "eslint \"**/*.js\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "check-coverage": true, "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.12.0" }, "version": "3.0.1" } PK ~\OCi i parse-conflict-json/lib/index.jsnu[const parseJSON = require('json-parse-even-better-errors') const { diff } = require('just-diff') const { diffApply } = require('just-diff-apply') const globalObjectProperties = Object.getOwnPropertyNames(Object.prototype) const stripBOM = content => { content = content.toString() // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) // because the buffer-to-string conversion in `fs.readFileSync()` // translates it to FEFF, the UTF-16 BOM. if (content.charCodeAt(0) === 0xFEFF) { content = content.slice(1) } return content } const PARENT_RE = /\|{7,}/g const OURS_RE = /<{7,}/g const THEIRS_RE = /={7,}/g const END_RE = />{7,}/g const isDiff = str => str.match(OURS_RE) && str.match(THEIRS_RE) && str.match(END_RE) const parseConflictJSON = (str, reviver, prefer) => { prefer = prefer || 'ours' if (prefer !== 'theirs' && prefer !== 'ours') { throw new TypeError('prefer param must be "ours" or "theirs" if set') } str = stripBOM(str) if (!isDiff(str)) { return parseJSON(str) } const pieces = str.split(/[\n\r]+/g).reduce((acc, line) => { if (line.match(PARENT_RE)) { acc.state = 'parent' } else if (line.match(OURS_RE)) { acc.state = 'ours' } else if (line.match(THEIRS_RE)) { acc.state = 'theirs' } else if (line.match(END_RE)) { acc.state = 'top' } else { if (acc.state === 'top' || acc.state === 'ours') { acc.ours += line } if (acc.state === 'top' || acc.state === 'theirs') { acc.theirs += line } if (acc.state === 'top' || acc.state === 'parent') { acc.parent += line } } return acc }, { state: 'top', ours: '', theirs: '', parent: '', }) // this will throw if either piece is not valid JSON, that's intended const parent = parseJSON(pieces.parent, reviver) const ours = parseJSON(pieces.ours, reviver) const theirs = parseJSON(pieces.theirs, reviver) return prefer === 'ours' ? resolve(parent, ours, theirs) : resolve(parent, theirs, ours) } const isObj = obj => obj && typeof obj === 'object' const copyPath = (to, from, path, i) => { const p = path[i] if (isObj(to[p]) && isObj(from[p]) && Array.isArray(to[p]) === Array.isArray(from[p])) { return copyPath(to[p], from[p], path, i + 1) } to[p] = from[p] } // get the diff from parent->ours and applying our changes on top of theirs. // If they turned an object into a non-object, then put it back. const resolve = (parent, ours, theirs) => { const dours = diff(parent, ours) for (let i = 0; i < dours.length; i++) { if (globalObjectProperties.find(prop => dours[i].path.includes(prop))) { continue } try { diffApply(theirs, [dours[i]]) } catch (e) { copyPath(theirs, ours, dours[i].path, 0) } } return theirs } module.exports = Object.assign(parseConflictJSON, { isDiff }) PK ~\rparse-conflict-json/LICENSE.mdnu[ ISC License Copyright npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND NPM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NPM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\-minizlib/package.jsonnu[{ "_id": "minizlib@2.1.2", "_inBundle": true, "_location": "/npm/minizlib", "_phantomChildren": { "yallist": "4.0.0" }, "_requiredBy": [ "/npm/minipass-fetch", "/npm/npm-registry-fetch", "/npm/tar" ], "author": { "name": "Isaac Z. Schlueter", "email": "i@izs.me", "url": "http://blog.izs.me/" }, "bugs": { "url": "https://github.com/isaacs/minizlib/issues" }, "dependencies": { "minipass": "^3.0.0", "yallist": "^4.0.0" }, "description": "A small fast zlib stream built on [minipass](http://npm.im/minipass) and Node.js's zlib binding.", "devDependencies": { "tap": "^14.6.9" }, "engines": { "node": ">= 8" }, "files": [ "index.js", "constants.js" ], "homepage": "https://github.com/isaacs/minizlib#readme", "keywords": [ "zlib", "gzip", "gunzip", "deflate", "inflate", "compression", "zip", "unzip" ], "license": "MIT", "main": "index.js", "name": "minizlib", "repository": { "type": "git", "url": "git+https://github.com/isaacs/minizlib.git" }, "scripts": { "postpublish": "git push origin --all; git push origin --tags", "postversion": "npm publish", "preversion": "npm test", "test": "tap test/*.js --100 -J" }, "version": "2.1.2" } PK ~\>0+minizlib/node_modules/minipass/package.jsonnu[{ "_id": "minipass@3.3.6", "_inBundle": true, "_location": "/npm/minizlib/minipass", "_phantomChildren": {}, "_requiredBy": [ "/npm/minizlib" ], "author": { "name": "Isaac Z. Schlueter", "email": "i@izs.me", "url": "http://blog.izs.me/" }, "bugs": { "url": "https://github.com/isaacs/minipass/issues" }, "dependencies": { "yallist": "^4.0.0" }, "description": "minimal implementation of a PassThrough stream", "devDependencies": { "@types/node": "^17.0.41", "end-of-stream": "^1.4.0", "prettier": "^2.6.2", "tap": "^16.2.0", "through2": "^2.0.3", "ts-node": "^10.8.1", "typescript": "^4.7.3" }, "engines": { "node": ">=8" }, "files": [ "index.d.ts", "index.js" ], "homepage": "https://github.com/isaacs/minipass#readme", "keywords": [ "passthrough", "stream" ], "license": "ISC", "main": "index.js", "name": "minipass", "prettier": { "semi": false, "printWidth": 80, "tabWidth": 2, "useTabs": false, "singleQuote": true, "jsxSingleQuote": false, "bracketSameLine": true, "arrowParens": "avoid", "endOfLine": "lf" }, "repository": { "type": "git", "url": "git+https://github.com/isaacs/minipass.git" }, "scripts": { "postpublish": "git push origin --follow-tags", "postversion": "npm publish", "preversion": "npm test", "test": "tap" }, "tap": { "check-coverage": true }, "types": "index.d.ts", "version": "3.3.6" } PK ~\&minizlib/node_modules/minipass/LICENSEnu[The ISC License Copyright (c) 2017-2022 npm, Inc., Isaac Z. Schlueter, and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\-@@'minizlib/node_modules/minipass/index.jsnu['use strict' const proc = typeof process === 'object' && process ? process : { stdout: null, stderr: null, } const EE = require('events') const Stream = require('stream') const SD = require('string_decoder').StringDecoder const EOF = Symbol('EOF') const MAYBE_EMIT_END = Symbol('maybeEmitEnd') const EMITTED_END = Symbol('emittedEnd') const EMITTING_END = Symbol('emittingEnd') const EMITTED_ERROR = Symbol('emittedError') const CLOSED = Symbol('closed') const READ = Symbol('read') const FLUSH = Symbol('flush') const FLUSHCHUNK = Symbol('flushChunk') const ENCODING = Symbol('encoding') const DECODER = Symbol('decoder') const FLOWING = Symbol('flowing') const PAUSED = Symbol('paused') const RESUME = Symbol('resume') const BUFFERLENGTH = Symbol('bufferLength') const BUFFERPUSH = Symbol('bufferPush') const BUFFERSHIFT = Symbol('bufferShift') const OBJECTMODE = Symbol('objectMode') const DESTROYED = Symbol('destroyed') const EMITDATA = Symbol('emitData') const EMITEND = Symbol('emitEnd') const EMITEND2 = Symbol('emitEnd2') const ASYNC = Symbol('async') const defer = fn => Promise.resolve().then(fn) // TODO remove when Node v8 support drops const doIter = global._MP_NO_ITERATOR_SYMBOLS_ !== '1' const ASYNCITERATOR = doIter && Symbol.asyncIterator || Symbol('asyncIterator not implemented') const ITERATOR = doIter && Symbol.iterator || Symbol('iterator not implemented') // events that mean 'the stream is over' // these are treated specially, and re-emitted // if they are listened for after emitting. const isEndish = ev => ev === 'end' || ev === 'finish' || ev === 'prefinish' const isArrayBuffer = b => b instanceof ArrayBuffer || typeof b === 'object' && b.constructor && b.constructor.name === 'ArrayBuffer' && b.byteLength >= 0 const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b) class Pipe { constructor (src, dest, opts) { this.src = src this.dest = dest this.opts = opts this.ondrain = () => src[RESUME]() dest.on('drain', this.ondrain) } unpipe () { this.dest.removeListener('drain', this.ondrain) } // istanbul ignore next - only here for the prototype proxyErrors () {} end () { this.unpipe() if (this.opts.end) this.dest.end() } } class PipeProxyErrors extends Pipe { unpipe () { this.src.removeListener('error', this.proxyErrors) super.unpipe() } constructor (src, dest, opts) { super(src, dest, opts) this.proxyErrors = er => dest.emit('error', er) src.on('error', this.proxyErrors) } } module.exports = class Minipass extends Stream { constructor (options) { super() this[FLOWING] = false // whether we're explicitly paused this[PAUSED] = false this.pipes = [] this.buffer = [] this[OBJECTMODE] = options && options.objectMode || false if (this[OBJECTMODE]) this[ENCODING] = null else this[ENCODING] = options && options.encoding || null if (this[ENCODING] === 'buffer') this[ENCODING] = null this[ASYNC] = options && !!options.async || false this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null this[EOF] = false this[EMITTED_END] = false this[EMITTING_END] = false this[CLOSED] = false this[EMITTED_ERROR] = null this.writable = true this.readable = true this[BUFFERLENGTH] = 0 this[DESTROYED] = false } get bufferLength () { return this[BUFFERLENGTH] } get encoding () { return this[ENCODING] } set encoding (enc) { if (this[OBJECTMODE]) throw new Error('cannot set encoding in objectMode') if (this[ENCODING] && enc !== this[ENCODING] && (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH])) throw new Error('cannot change encoding') if (this[ENCODING] !== enc) { this[DECODER] = enc ? new SD(enc) : null if (this.buffer.length) this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk)) } this[ENCODING] = enc } setEncoding (enc) { this.encoding = enc } get objectMode () { return this[OBJECTMODE] } set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om } get ['async'] () { return this[ASYNC] } set ['async'] (a) { this[ASYNC] = this[ASYNC] || !!a } write (chunk, encoding, cb) { if (this[EOF]) throw new Error('write after end') if (this[DESTROYED]) { this.emit('error', Object.assign( new Error('Cannot call write after a stream was destroyed'), { code: 'ERR_STREAM_DESTROYED' } )) return true } if (typeof encoding === 'function') cb = encoding, encoding = 'utf8' if (!encoding) encoding = 'utf8' const fn = this[ASYNC] ? defer : f => f() // convert array buffers and typed array views into buffers // at some point in the future, we may want to do the opposite! // leave strings and buffers as-is // anything else switches us into object mode if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { if (isArrayBufferView(chunk)) chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) else if (isArrayBuffer(chunk)) chunk = Buffer.from(chunk) else if (typeof chunk !== 'string') // use the setter so we throw if we have encoding set this.objectMode = true } // handle object mode up front, since it's simpler // this yields better performance, fewer checks later. if (this[OBJECTMODE]) { /* istanbul ignore if - maybe impossible? */ if (this.flowing && this[BUFFERLENGTH] !== 0) this[FLUSH](true) if (this.flowing) this.emit('data', chunk) else this[BUFFERPUSH](chunk) if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } // at this point the chunk is a buffer or string // don't buffer it up or send it to the decoder if (!chunk.length) { if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } // fast-path writing strings of same encoding to a stream with // an empty buffer, skipping the buffer/decoder dance if (typeof chunk === 'string' && // unless it is a string already ready for us to use !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) { chunk = Buffer.from(chunk, encoding) } if (Buffer.isBuffer(chunk) && this[ENCODING]) chunk = this[DECODER].write(chunk) // Note: flushing CAN potentially switch us into not-flowing mode if (this.flowing && this[BUFFERLENGTH] !== 0) this[FLUSH](true) if (this.flowing) this.emit('data', chunk) else this[BUFFERPUSH](chunk) if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } read (n) { if (this[DESTROYED]) return null if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) { this[MAYBE_EMIT_END]() return null } if (this[OBJECTMODE]) n = null if (this.buffer.length > 1 && !this[OBJECTMODE]) { if (this.encoding) this.buffer = [this.buffer.join('')] else this.buffer = [Buffer.concat(this.buffer, this[BUFFERLENGTH])] } const ret = this[READ](n || null, this.buffer[0]) this[MAYBE_EMIT_END]() return ret } [READ] (n, chunk) { if (n === chunk.length || n === null) this[BUFFERSHIFT]() else { this.buffer[0] = chunk.slice(n) chunk = chunk.slice(0, n) this[BUFFERLENGTH] -= n } this.emit('data', chunk) if (!this.buffer.length && !this[EOF]) this.emit('drain') return chunk } end (chunk, encoding, cb) { if (typeof chunk === 'function') cb = chunk, chunk = null if (typeof encoding === 'function') cb = encoding, encoding = 'utf8' if (chunk) this.write(chunk, encoding) if (cb) this.once('end', cb) this[EOF] = true this.writable = false // if we haven't written anything, then go ahead and emit, // even if we're not reading. // we'll re-emit if a new 'end' listener is added anyway. // This makes MP more suitable to write-only use cases. if (this.flowing || !this[PAUSED]) this[MAYBE_EMIT_END]() return this } // don't let the internal resume be overwritten [RESUME] () { if (this[DESTROYED]) return this[PAUSED] = false this[FLOWING] = true this.emit('resume') if (this.buffer.length) this[FLUSH]() else if (this[EOF]) this[MAYBE_EMIT_END]() else this.emit('drain') } resume () { return this[RESUME]() } pause () { this[FLOWING] = false this[PAUSED] = true } get destroyed () { return this[DESTROYED] } get flowing () { return this[FLOWING] } get paused () { return this[PAUSED] } [BUFFERPUSH] (chunk) { if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1 else this[BUFFERLENGTH] += chunk.length this.buffer.push(chunk) } [BUFFERSHIFT] () { if (this.buffer.length) { if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1 else this[BUFFERLENGTH] -= this.buffer[0].length } return this.buffer.shift() } [FLUSH] (noDrain) { do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]())) if (!noDrain && !this.buffer.length && !this[EOF]) this.emit('drain') } [FLUSHCHUNK] (chunk) { return chunk ? (this.emit('data', chunk), this.flowing) : false } pipe (dest, opts) { if (this[DESTROYED]) return const ended = this[EMITTED_END] opts = opts || {} if (dest === proc.stdout || dest === proc.stderr) opts.end = false else opts.end = opts.end !== false opts.proxyErrors = !!opts.proxyErrors // piping an ended stream ends immediately if (ended) { if (opts.end) dest.end() } else { this.pipes.push(!opts.proxyErrors ? new Pipe(this, dest, opts) : new PipeProxyErrors(this, dest, opts)) if (this[ASYNC]) defer(() => this[RESUME]()) else this[RESUME]() } return dest } unpipe (dest) { const p = this.pipes.find(p => p.dest === dest) if (p) { this.pipes.splice(this.pipes.indexOf(p), 1) p.unpipe() } } addListener (ev, fn) { return this.on(ev, fn) } on (ev, fn) { const ret = super.on(ev, fn) if (ev === 'data' && !this.pipes.length && !this.flowing) this[RESUME]() else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) super.emit('readable') else if (isEndish(ev) && this[EMITTED_END]) { super.emit(ev) this.removeAllListeners(ev) } else if (ev === 'error' && this[EMITTED_ERROR]) { if (this[ASYNC]) defer(() => fn.call(this, this[EMITTED_ERROR])) else fn.call(this, this[EMITTED_ERROR]) } return ret } get emittedEnd () { return this[EMITTED_END] } [MAYBE_EMIT_END] () { if (!this[EMITTING_END] && !this[EMITTED_END] && !this[DESTROYED] && this.buffer.length === 0 && this[EOF]) { this[EMITTING_END] = true this.emit('end') this.emit('prefinish') this.emit('finish') if (this[CLOSED]) this.emit('close') this[EMITTING_END] = false } } emit (ev, data, ...extra) { // error and close are only events allowed after calling destroy() if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED]) return else if (ev === 'data') { return !data ? false : this[ASYNC] ? defer(() => this[EMITDATA](data)) : this[EMITDATA](data) } else if (ev === 'end') { return this[EMITEND]() } else if (ev === 'close') { this[CLOSED] = true // don't emit close before 'end' and 'finish' if (!this[EMITTED_END] && !this[DESTROYED]) return const ret = super.emit('close') this.removeAllListeners('close') return ret } else if (ev === 'error') { this[EMITTED_ERROR] = data const ret = super.emit('error', data) this[MAYBE_EMIT_END]() return ret } else if (ev === 'resume') { const ret = super.emit('resume') this[MAYBE_EMIT_END]() return ret } else if (ev === 'finish' || ev === 'prefinish') { const ret = super.emit(ev) this.removeAllListeners(ev) return ret } // Some other unknown event const ret = super.emit(ev, data, ...extra) this[MAYBE_EMIT_END]() return ret } [EMITDATA] (data) { for (const p of this.pipes) { if (p.dest.write(data) === false) this.pause() } const ret = super.emit('data', data) this[MAYBE_EMIT_END]() return ret } [EMITEND] () { if (this[EMITTED_END]) return this[EMITTED_END] = true this.readable = false if (this[ASYNC]) defer(() => this[EMITEND2]()) else this[EMITEND2]() } [EMITEND2] () { if (this[DECODER]) { const data = this[DECODER].end() if (data) { for (const p of this.pipes) { p.dest.write(data) } super.emit('data', data) } } for (const p of this.pipes) { p.end() } const ret = super.emit('end') this.removeAllListeners('end') return ret } // const all = await stream.collect() collect () { const buf = [] if (!this[OBJECTMODE]) buf.dataLength = 0 // set the promise first, in case an error is raised // by triggering the flow here. const p = this.promise() this.on('data', c => { buf.push(c) if (!this[OBJECTMODE]) buf.dataLength += c.length }) return p.then(() => buf) } // const data = await stream.concat() concat () { return this[OBJECTMODE] ? Promise.reject(new Error('cannot concat in objectMode')) : this.collect().then(buf => this[OBJECTMODE] ? Promise.reject(new Error('cannot concat in objectMode')) : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength)) } // stream.promise().then(() => done, er => emitted error) promise () { return new Promise((resolve, reject) => { this.on(DESTROYED, () => reject(new Error('stream destroyed'))) this.on('error', er => reject(er)) this.on('end', () => resolve()) }) } // for await (let chunk of stream) [ASYNCITERATOR] () { const next = () => { const res = this.read() if (res !== null) return Promise.resolve({ done: false, value: res }) if (this[EOF]) return Promise.resolve({ done: true }) let resolve = null let reject = null const onerr = er => { this.removeListener('data', ondata) this.removeListener('end', onend) reject(er) } const ondata = value => { this.removeListener('error', onerr) this.removeListener('end', onend) this.pause() resolve({ value: value, done: !!this[EOF] }) } const onend = () => { this.removeListener('error', onerr) this.removeListener('data', ondata) resolve({ done: true }) } const ondestroy = () => onerr(new Error('stream destroyed')) return new Promise((res, rej) => { reject = rej resolve = res this.once(DESTROYED, ondestroy) this.once('error', onerr) this.once('end', onend) this.once('data', ondata) }) } return { next } } // for (let chunk of stream) [ITERATOR] () { const next = () => { const value = this.read() const done = value === null return { value, done } } return { next } } destroy (er) { if (this[DESTROYED]) { if (er) this.emit('error', er) else this.emit(DESTROYED) return this } this[DESTROYED] = true // throw away all buffered data, it's never coming out this.buffer.length = 0 this[BUFFERLENGTH] = 0 if (typeof this.close === 'function' && !this[CLOSED]) this.close() if (er) this.emit('error', er) else // if no error to emit, still reject pending promises this.emit(DESTROYED) return this } static isStream (s) { return !!s && (s instanceof Minipass || s instanceof Stream || s instanceof EE && ( typeof s.pipe === 'function' || // readable (typeof s.write === 'function' && typeof s.end === 'function') // writable )) } } PK ~\=minizlib/LICENSEnu[Minizlib was created by Isaac Z. Schlueter. It is a derivative work of the Node.js project. """ Copyright Isaac Z. Schlueter and Contributors Copyright Node.js contributors. All rights reserved. Copyright Joyent, Inc. and other Node contributors. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ PK ~\LjKZ$$minizlib/index.jsnu['use strict' const assert = require('assert') const Buffer = require('buffer').Buffer const realZlib = require('zlib') const constants = exports.constants = require('./constants.js') const Minipass = require('minipass') const OriginalBufferConcat = Buffer.concat const _superWrite = Symbol('_superWrite') class ZlibError extends Error { constructor (err) { super('zlib: ' + err.message) this.code = err.code this.errno = err.errno /* istanbul ignore if */ if (!this.code) this.code = 'ZLIB_ERROR' this.message = 'zlib: ' + err.message Error.captureStackTrace(this, this.constructor) } get name () { return 'ZlibError' } } // the Zlib class they all inherit from // This thing manages the queue of requests, and returns // true or false if there is anything in the queue when // you call the .write() method. const _opts = Symbol('opts') const _flushFlag = Symbol('flushFlag') const _finishFlushFlag = Symbol('finishFlushFlag') const _fullFlushFlag = Symbol('fullFlushFlag') const _handle = Symbol('handle') const _onError = Symbol('onError') const _sawError = Symbol('sawError') const _level = Symbol('level') const _strategy = Symbol('strategy') const _ended = Symbol('ended') const _defaultFullFlush = Symbol('_defaultFullFlush') class ZlibBase extends Minipass { constructor (opts, mode) { if (!opts || typeof opts !== 'object') throw new TypeError('invalid options for ZlibBase constructor') super(opts) this[_sawError] = false this[_ended] = false this[_opts] = opts this[_flushFlag] = opts.flush this[_finishFlushFlag] = opts.finishFlush // this will throw if any options are invalid for the class selected try { this[_handle] = new realZlib[mode](opts) } catch (er) { // make sure that all errors get decorated properly throw new ZlibError(er) } this[_onError] = (err) => { // no sense raising multiple errors, since we abort on the first one. if (this[_sawError]) return this[_sawError] = true // there is no way to cleanly recover. // continuing only obscures problems. this.close() this.emit('error', err) } this[_handle].on('error', er => this[_onError](new ZlibError(er))) this.once('end', () => this.close) } close () { if (this[_handle]) { this[_handle].close() this[_handle] = null this.emit('close') } } reset () { if (!this[_sawError]) { assert(this[_handle], 'zlib binding closed') return this[_handle].reset() } } flush (flushFlag) { if (this.ended) return if (typeof flushFlag !== 'number') flushFlag = this[_fullFlushFlag] this.write(Object.assign(Buffer.alloc(0), { [_flushFlag]: flushFlag })) } end (chunk, encoding, cb) { if (chunk) this.write(chunk, encoding) this.flush(this[_finishFlushFlag]) this[_ended] = true return super.end(null, null, cb) } get ended () { return this[_ended] } write (chunk, encoding, cb) { // process the chunk using the sync process // then super.write() all the outputted chunks if (typeof encoding === 'function') cb = encoding, encoding = 'utf8' if (typeof chunk === 'string') chunk = Buffer.from(chunk, encoding) if (this[_sawError]) return assert(this[_handle], 'zlib binding closed') // _processChunk tries to .close() the native handle after it's done, so we // intercept that by temporarily making it a no-op. const nativeHandle = this[_handle]._handle const originalNativeClose = nativeHandle.close nativeHandle.close = () => {} const originalClose = this[_handle].close this[_handle].close = () => {} // It also calls `Buffer.concat()` at the end, which may be convenient // for some, but which we are not interested in as it slows us down. Buffer.concat = (args) => args let result try { const flushFlag = typeof chunk[_flushFlag] === 'number' ? chunk[_flushFlag] : this[_flushFlag] result = this[_handle]._processChunk(chunk, flushFlag) // if we don't throw, reset it back how it was Buffer.concat = OriginalBufferConcat } catch (err) { // or if we do, put Buffer.concat() back before we emit error // Error events call into user code, which may call Buffer.concat() Buffer.concat = OriginalBufferConcat this[_onError](new ZlibError(err)) } finally { if (this[_handle]) { // Core zlib resets `_handle` to null after attempting to close the // native handle. Our no-op handler prevented actual closure, but we // need to restore the `._handle` property. this[_handle]._handle = nativeHandle nativeHandle.close = originalNativeClose this[_handle].close = originalClose // `_processChunk()` adds an 'error' listener. If we don't remove it // after each call, these handlers start piling up. this[_handle].removeAllListeners('error') // make sure OUR error listener is still attached tho } } if (this[_handle]) this[_handle].on('error', er => this[_onError](new ZlibError(er))) let writeReturn if (result) { if (Array.isArray(result) && result.length > 0) { // The first buffer is always `handle._outBuffer`, which would be // re-used for later invocations; so, we always have to copy that one. writeReturn = this[_superWrite](Buffer.from(result[0])) for (let i = 1; i < result.length; i++) { writeReturn = this[_superWrite](result[i]) } } else { writeReturn = this[_superWrite](Buffer.from(result)) } } if (cb) cb() return writeReturn } [_superWrite] (data) { return super.write(data) } } class Zlib extends ZlibBase { constructor (opts, mode) { opts = opts || {} opts.flush = opts.flush || constants.Z_NO_FLUSH opts.finishFlush = opts.finishFlush || constants.Z_FINISH super(opts, mode) this[_fullFlushFlag] = constants.Z_FULL_FLUSH this[_level] = opts.level this[_strategy] = opts.strategy } params (level, strategy) { if (this[_sawError]) return if (!this[_handle]) throw new Error('cannot switch params when binding is closed') // no way to test this without also not supporting params at all /* istanbul ignore if */ if (!this[_handle].params) throw new Error('not supported in this implementation') if (this[_level] !== level || this[_strategy] !== strategy) { this.flush(constants.Z_SYNC_FLUSH) assert(this[_handle], 'zlib binding closed') // .params() calls .flush(), but the latter is always async in the // core zlib. We override .flush() temporarily to intercept that and // flush synchronously. const origFlush = this[_handle].flush this[_handle].flush = (flushFlag, cb) => { this.flush(flushFlag) cb() } try { this[_handle].params(level, strategy) } finally { this[_handle].flush = origFlush } /* istanbul ignore else */ if (this[_handle]) { this[_level] = level this[_strategy] = strategy } } } } // minimal 2-byte header class Deflate extends Zlib { constructor (opts) { super(opts, 'Deflate') } } class Inflate extends Zlib { constructor (opts) { super(opts, 'Inflate') } } // gzip - bigger header, same deflate compression const _portable = Symbol('_portable') class Gzip extends Zlib { constructor (opts) { super(opts, 'Gzip') this[_portable] = opts && !!opts.portable } [_superWrite] (data) { if (!this[_portable]) return super[_superWrite](data) // we'll always get the header emitted in one first chunk // overwrite the OS indicator byte with 0xFF this[_portable] = false data[9] = 255 return super[_superWrite](data) } } class Gunzip extends Zlib { constructor (opts) { super(opts, 'Gunzip') } } // raw - no header class DeflateRaw extends Zlib { constructor (opts) { super(opts, 'DeflateRaw') } } class InflateRaw extends Zlib { constructor (opts) { super(opts, 'InflateRaw') } } // auto-detect header. class Unzip extends Zlib { constructor (opts) { super(opts, 'Unzip') } } class Brotli extends ZlibBase { constructor (opts, mode) { opts = opts || {} opts.flush = opts.flush || constants.BROTLI_OPERATION_PROCESS opts.finishFlush = opts.finishFlush || constants.BROTLI_OPERATION_FINISH super(opts, mode) this[_fullFlushFlag] = constants.BROTLI_OPERATION_FLUSH } } class BrotliCompress extends Brotli { constructor (opts) { super(opts, 'BrotliCompress') } } class BrotliDecompress extends Brotli { constructor (opts) { super(opts, 'BrotliDecompress') } } exports.Deflate = Deflate exports.Inflate = Inflate exports.Gzip = Gzip exports.Gunzip = Gunzip exports.DeflateRaw = DeflateRaw exports.InflateRaw = InflateRaw exports.Unzip = Unzip /* istanbul ignore else */ if (typeof realZlib.BrotliCompress === 'function') { exports.BrotliCompress = BrotliCompress exports.BrotliDecompress = BrotliDecompress } else { exports.BrotliCompress = exports.BrotliDecompress = class { constructor () { throw new Error('Brotli is not supported in this version of Node.js') } } } PK ~\minizlib/constants.jsnu[// Update with any zlib constants that are added or changed in the future. // Node v6 didn't export this, so we just hard code the version and rely // on all the other hard-coded values from zlib v4736. When node v6 // support drops, we can just export the realZlibConstants object. const realZlibConstants = require('zlib').constants || /* istanbul ignore next */ { ZLIB_VERNUM: 4736 } module.exports = Object.freeze(Object.assign(Object.create(null), { Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4, Z_BLOCK: 5, Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, Z_MEM_ERROR: -4, Z_BUF_ERROR: -5, Z_VERSION_ERROR: -6, Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9, Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4, Z_DEFAULT_STRATEGY: 0, DEFLATE: 1, INFLATE: 2, GZIP: 3, GUNZIP: 4, DEFLATERAW: 5, INFLATERAW: 6, UNZIP: 7, BROTLI_DECODE: 8, BROTLI_ENCODE: 9, Z_MIN_WINDOWBITS: 8, Z_MAX_WINDOWBITS: 15, Z_DEFAULT_WINDOWBITS: 15, Z_MIN_CHUNK: 64, Z_MAX_CHUNK: Infinity, Z_DEFAULT_CHUNK: 16384, Z_MIN_MEMLEVEL: 1, Z_MAX_MEMLEVEL: 9, Z_DEFAULT_MEMLEVEL: 8, Z_MIN_LEVEL: -1, Z_MAX_LEVEL: 9, Z_DEFAULT_LEVEL: -1, BROTLI_OPERATION_PROCESS: 0, BROTLI_OPERATION_FLUSH: 1, BROTLI_OPERATION_FINISH: 2, BROTLI_OPERATION_EMIT_METADATA: 3, BROTLI_MODE_GENERIC: 0, BROTLI_MODE_TEXT: 1, BROTLI_MODE_FONT: 2, BROTLI_DEFAULT_MODE: 0, BROTLI_MIN_QUALITY: 0, BROTLI_MAX_QUALITY: 11, BROTLI_DEFAULT_QUALITY: 11, BROTLI_MIN_WINDOW_BITS: 10, BROTLI_MAX_WINDOW_BITS: 24, BROTLI_LARGE_MAX_WINDOW_BITS: 30, BROTLI_DEFAULT_WINDOW: 22, BROTLI_MIN_INPUT_BLOCK_BITS: 16, BROTLI_MAX_INPUT_BLOCK_BITS: 24, BROTLI_PARAM_MODE: 0, BROTLI_PARAM_QUALITY: 1, BROTLI_PARAM_LGWIN: 2, BROTLI_PARAM_LGBLOCK: 3, BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4, BROTLI_PARAM_SIZE_HINT: 5, BROTLI_PARAM_LARGE_WINDOW: 6, BROTLI_PARAM_NPOSTFIX: 7, BROTLI_PARAM_NDIRECT: 8, BROTLI_DECODER_RESULT_ERROR: 0, BROTLI_DECODER_RESULT_SUCCESS: 1, BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2, BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3, BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0, BROTLI_DECODER_PARAM_LARGE_WINDOW: 1, BROTLI_DECODER_NO_ERROR: 0, BROTLI_DECODER_SUCCESS: 1, BROTLI_DECODER_NEEDS_MORE_INPUT: 2, BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3, BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1, BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2, BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3, BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4, BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5, BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6, BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7, BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8, BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9, BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10, BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11, BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12, BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13, BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14, BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15, BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16, BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19, BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20, BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21, BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22, BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25, BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26, BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27, BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30, BROTLI_DECODER_ERROR_UNREACHABLE: -31, }, realZlibConstants)) PK ~\ۗMkk@pkgjs/parseargs/utils.jsnu['use strict'; const { ArrayPrototypeFind, ObjectEntries, ObjectPrototypeHasOwnProperty: ObjectHasOwn, StringPrototypeCharAt, StringPrototypeIncludes, StringPrototypeStartsWith, } = require('./internal/primordials'); const { validateObject, } = require('./internal/validators'); // These are internal utilities to make the parsing logic easier to read, and // add lots of detail for the curious. They are in a separate file to allow // unit testing, although that is not essential (this could be rolled into // main file and just tested implicitly via API). // // These routines are for internal use, not for export to client. /** * Return the named property, but only if it is an own property. */ function objectGetOwn(obj, prop) { if (ObjectHasOwn(obj, prop)) return obj[prop]; } /** * Return the named options property, but only if it is an own property. */ function optionsGetOwn(options, longOption, prop) { if (ObjectHasOwn(options, longOption)) return objectGetOwn(options[longOption], prop); } /** * Determines if the argument may be used as an option value. * @example * isOptionValue('V') // returns true * isOptionValue('-v') // returns true (greedy) * isOptionValue('--foo') // returns true (greedy) * isOptionValue(undefined) // returns false */ function isOptionValue(value) { if (value == null) return false; // Open Group Utility Conventions are that an option-argument // is the argument after the option, and may start with a dash. return true; // greedy! } /** * Detect whether there is possible confusion and user may have omitted * the option argument, like `--port --verbose` when `port` of type:string. * In strict mode we throw errors if value is option-like. */ function isOptionLikeValue(value) { if (value == null) return false; return value.length > 1 && StringPrototypeCharAt(value, 0) === '-'; } /** * Determines if `arg` is just a short option. * @example '-f' */ function isLoneShortOption(arg) { return arg.length === 2 && StringPrototypeCharAt(arg, 0) === '-' && StringPrototypeCharAt(arg, 1) !== '-'; } /** * Determines if `arg` is a lone long option. * @example * isLoneLongOption('a') // returns false * isLoneLongOption('-a') // returns false * isLoneLongOption('--foo') // returns true * isLoneLongOption('--foo=bar') // returns false */ function isLoneLongOption(arg) { return arg.length > 2 && StringPrototypeStartsWith(arg, '--') && !StringPrototypeIncludes(arg, '=', 3); } /** * Determines if `arg` is a long option and value in the same argument. * @example * isLongOptionAndValue('--foo') // returns false * isLongOptionAndValue('--foo=bar') // returns true */ function isLongOptionAndValue(arg) { return arg.length > 2 && StringPrototypeStartsWith(arg, '--') && StringPrototypeIncludes(arg, '=', 3); } /** * Determines if `arg` is a short option group. * * See Guideline 5 of the [Open Group Utility Conventions](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html). * One or more options without option-arguments, followed by at most one * option that takes an option-argument, should be accepted when grouped * behind one '-' delimiter. * @example * isShortOptionGroup('-a', {}) // returns false * isShortOptionGroup('-ab', {}) // returns true * // -fb is an option and a value, not a short option group * isShortOptionGroup('-fb', { * options: { f: { type: 'string' } } * }) // returns false * isShortOptionGroup('-bf', { * options: { f: { type: 'string' } } * }) // returns true * // -bfb is an edge case, return true and caller sorts it out * isShortOptionGroup('-bfb', { * options: { f: { type: 'string' } } * }) // returns true */ function isShortOptionGroup(arg, options) { if (arg.length <= 2) return false; if (StringPrototypeCharAt(arg, 0) !== '-') return false; if (StringPrototypeCharAt(arg, 1) === '-') return false; const firstShort = StringPrototypeCharAt(arg, 1); const longOption = findLongOptionForShort(firstShort, options); return optionsGetOwn(options, longOption, 'type') !== 'string'; } /** * Determine if arg is a short string option followed by its value. * @example * isShortOptionAndValue('-a', {}); // returns false * isShortOptionAndValue('-ab', {}); // returns false * isShortOptionAndValue('-fFILE', { * options: { foo: { short: 'f', type: 'string' }} * }) // returns true */ function isShortOptionAndValue(arg, options) { validateObject(options, 'options'); if (arg.length <= 2) return false; if (StringPrototypeCharAt(arg, 0) !== '-') return false; if (StringPrototypeCharAt(arg, 1) === '-') return false; const shortOption = StringPrototypeCharAt(arg, 1); const longOption = findLongOptionForShort(shortOption, options); return optionsGetOwn(options, longOption, 'type') === 'string'; } /** * Find the long option associated with a short option. Looks for a configured * `short` and returns the short option itself if a long option is not found. * @example * findLongOptionForShort('a', {}) // returns 'a' * findLongOptionForShort('b', { * options: { bar: { short: 'b' } } * }) // returns 'bar' */ function findLongOptionForShort(shortOption, options) { validateObject(options, 'options'); const longOptionEntry = ArrayPrototypeFind( ObjectEntries(options), ({ 1: optionConfig }) => objectGetOwn(optionConfig, 'short') === shortOption ); return longOptionEntry?.[0] ?? shortOption; } /** * Check if the given option includes a default value * and that option has not been set by the input args. * * @param {string} longOption - long option name e.g. 'foo' * @param {object} optionConfig - the option configuration properties * @param {object} values - option values returned in `values` by parseArgs */ function useDefaultValueOption(longOption, optionConfig, values) { return objectGetOwn(optionConfig, 'default') !== undefined && values[longOption] === undefined; } module.exports = { findLongOptionForShort, isLoneLongOption, isLoneShortOption, isLongOptionAndValue, isOptionValue, isOptionLikeValue, isShortOptionAndValue, isShortOptionGroup, useDefaultValueOption, objectGetOwn, optionsGetOwn, }; PK ~\Wuj**@pkgjs/parseargs/package.jsonnu[{ "_id": "@pkgjs/parseargs@0.11.0", "_inBundle": true, "_location": "/npm/@pkgjs/parseargs", "_phantomChildren": {}, "_requiredBy": [ "/npm/jackspeak" ], "author": "", "bugs": { "url": "https://github.com/pkgjs/parseargs/issues" }, "description": "Polyfill of future proposal for `util.parseArgs()`", "devDependencies": { "c8": "^7.10.0", "eslint": "^8.2.0", "eslint-plugin-node-core": "github:iansu/eslint-plugin-node-core", "tape": "^5.2.2" }, "engines": { "node": ">=14" }, "exports": { ".": "./index.js", "./package.json": "./package.json" }, "homepage": "https://github.com/pkgjs/parseargs#readme", "keywords": [], "license": "MIT", "main": "index.js", "name": "@pkgjs/parseargs", "repository": { "type": "git", "url": "git+ssh://git@github.com/pkgjs/parseargs.git" }, "scripts": { "coverage": "c8 --check-coverage tape 'test/*.js'", "fix": "npm run posttest -- --fix", "posttest": "eslint .", "test": "c8 tape 'test/*.js'" }, "version": "0.11.0" } PK ~\'t!@pkgjs/parseargs/internal/util.jsnu['use strict'; // This is a placeholder for util.js in node.js land. const { ObjectCreate, ObjectFreeze, } = require('./primordials'); const kEmptyObject = ObjectFreeze(ObjectCreate(null)); module.exports = { kEmptyObject, }; PK ~\%"'@pkgjs/parseargs/internal/validators.jsnu['use strict'; // This file is a proxy of the original file located at: // https://github.com/nodejs/node/blob/main/lib/internal/validators.js // Every addition or modification to this file must be evaluated // during the PR review. const { ArrayIsArray, ArrayPrototypeIncludes, ArrayPrototypeJoin, } = require('./primordials'); const { codes: { ERR_INVALID_ARG_TYPE } } = require('./errors'); function validateString(value, name) { if (typeof value !== 'string') { throw new ERR_INVALID_ARG_TYPE(name, 'String', value); } } function validateUnion(value, name, union) { if (!ArrayPrototypeIncludes(union, value)) { throw new ERR_INVALID_ARG_TYPE(name, `('${ArrayPrototypeJoin(union, '|')}')`, value); } } function validateBoolean(value, name) { if (typeof value !== 'boolean') { throw new ERR_INVALID_ARG_TYPE(name, 'Boolean', value); } } function validateArray(value, name) { if (!ArrayIsArray(value)) { throw new ERR_INVALID_ARG_TYPE(name, 'Array', value); } } function validateStringArray(value, name) { validateArray(value, name); for (let i = 0; i < value.length; i++) { validateString(value[i], `${name}[${i}]`); } } function validateBooleanArray(value, name) { validateArray(value, name); for (let i = 0; i < value.length; i++) { validateBoolean(value[i], `${name}[${i}]`); } } /** * @param {unknown} value * @param {string} name * @param {{ * allowArray?: boolean, * allowFunction?: boolean, * nullable?: boolean * }} [options] */ function validateObject(value, name, options) { const useDefaultOptions = options == null; const allowArray = useDefaultOptions ? false : options.allowArray; const allowFunction = useDefaultOptions ? false : options.allowFunction; const nullable = useDefaultOptions ? false : options.nullable; if ((!nullable && value === null) || (!allowArray && ArrayIsArray(value)) || (typeof value !== 'object' && ( !allowFunction || typeof value !== 'function' ))) { throw new ERR_INVALID_ARG_TYPE(name, 'Object', value); } } module.exports = { validateArray, validateObject, validateString, validateStringArray, validateUnion, validateBoolean, validateBooleanArray, }; PK ~\ם#@pkgjs/parseargs/internal/errors.jsnu['use strict'; class ERR_INVALID_ARG_TYPE extends TypeError { constructor(name, expected, actual) { super(`${name} must be ${expected} got ${actual}`); this.code = 'ERR_INVALID_ARG_TYPE'; } } class ERR_INVALID_ARG_VALUE extends TypeError { constructor(arg1, arg2, expected) { super(`The property ${arg1} ${expected}. Received '${arg2}'`); this.code = 'ERR_INVALID_ARG_VALUE'; } } class ERR_PARSE_ARGS_INVALID_OPTION_VALUE extends Error { constructor(message) { super(message); this.code = 'ERR_PARSE_ARGS_INVALID_OPTION_VALUE'; } } class ERR_PARSE_ARGS_UNKNOWN_OPTION extends Error { constructor(option, allowPositionals) { const suggestDashDash = allowPositionals ? `. To specify a positional argument starting with a '-', place it at the end of the command after '--', as in '-- ${JSON.stringify(option)}` : ''; super(`Unknown option '${option}'${suggestDashDash}`); this.code = 'ERR_PARSE_ARGS_UNKNOWN_OPTION'; } } class ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL extends Error { constructor(positional) { super(`Unexpected argument '${positional}'. This command does not take positional arguments`); this.code = 'ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL'; } } module.exports = { codes: { ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE, ERR_PARSE_ARGS_INVALID_OPTION_VALUE, ERR_PARSE_ARGS_UNKNOWN_OPTION, ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL, } }; PK ~\Y..(@pkgjs/parseargs/internal/primordials.jsnu[/* This file is copied from https://github.com/nodejs/node/blob/v14.19.3/lib/internal/per_context/primordials.js under the following license: Copyright Node.js contributors. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ 'use strict'; /* eslint-disable node-core/prefer-primordials */ // This file subclasses and stores the JS builtins that come from the VM // so that Node.js's builtin modules do not need to later look these up from // the global proxy, which can be mutated by users. // Use of primordials have sometimes a dramatic impact on performance, please // benchmark all changes made in performance-sensitive areas of the codebase. // See: https://github.com/nodejs/node/pull/38248 const primordials = {}; const { defineProperty: ReflectDefineProperty, getOwnPropertyDescriptor: ReflectGetOwnPropertyDescriptor, ownKeys: ReflectOwnKeys, } = Reflect; // `uncurryThis` is equivalent to `func => Function.prototype.call.bind(func)`. // It is using `bind.bind(call)` to avoid using `Function.prototype.bind` // and `Function.prototype.call` after it may have been mutated by users. const { apply, bind, call } = Function.prototype; const uncurryThis = bind.bind(call); primordials.uncurryThis = uncurryThis; // `applyBind` is equivalent to `func => Function.prototype.apply.bind(func)`. // It is using `bind.bind(apply)` to avoid using `Function.prototype.bind` // and `Function.prototype.apply` after it may have been mutated by users. const applyBind = bind.bind(apply); primordials.applyBind = applyBind; // Methods that accept a variable number of arguments, and thus it's useful to // also create `${prefix}${key}Apply`, which uses `Function.prototype.apply`, // instead of `Function.prototype.call`, and thus doesn't require iterator // destructuring. const varargsMethods = [ // 'ArrayPrototypeConcat' is omitted, because it performs the spread // on its own for arrays and array-likes with a truthy // @@isConcatSpreadable symbol property. 'ArrayOf', 'ArrayPrototypePush', 'ArrayPrototypeUnshift', // 'FunctionPrototypeCall' is omitted, since there's 'ReflectApply' // and 'FunctionPrototypeApply'. 'MathHypot', 'MathMax', 'MathMin', 'StringPrototypeConcat', 'TypedArrayOf', ]; function getNewKey(key) { return typeof key === 'symbol' ? `Symbol${key.description[7].toUpperCase()}${key.description.slice(8)}` : `${key[0].toUpperCase()}${key.slice(1)}`; } function copyAccessor(dest, prefix, key, { enumerable, get, set }) { ReflectDefineProperty(dest, `${prefix}Get${key}`, { value: uncurryThis(get), enumerable }); if (set !== undefined) { ReflectDefineProperty(dest, `${prefix}Set${key}`, { value: uncurryThis(set), enumerable }); } } function copyPropsRenamed(src, dest, prefix) { for (const key of ReflectOwnKeys(src)) { const newKey = getNewKey(key); const desc = ReflectGetOwnPropertyDescriptor(src, key); if ('get' in desc) { copyAccessor(dest, prefix, newKey, desc); } else { const name = `${prefix}${newKey}`; ReflectDefineProperty(dest, name, desc); if (varargsMethods.includes(name)) { ReflectDefineProperty(dest, `${name}Apply`, { // `src` is bound as the `this` so that the static `this` points // to the object it was defined on, // e.g.: `ArrayOfApply` gets a `this` of `Array`: value: applyBind(desc.value, src), }); } } } } function copyPropsRenamedBound(src, dest, prefix) { for (const key of ReflectOwnKeys(src)) { const newKey = getNewKey(key); const desc = ReflectGetOwnPropertyDescriptor(src, key); if ('get' in desc) { copyAccessor(dest, prefix, newKey, desc); } else { const { value } = desc; if (typeof value === 'function') { desc.value = value.bind(src); } const name = `${prefix}${newKey}`; ReflectDefineProperty(dest, name, desc); if (varargsMethods.includes(name)) { ReflectDefineProperty(dest, `${name}Apply`, { value: applyBind(value, src), }); } } } } function copyPrototype(src, dest, prefix) { for (const key of ReflectOwnKeys(src)) { const newKey = getNewKey(key); const desc = ReflectGetOwnPropertyDescriptor(src, key); if ('get' in desc) { copyAccessor(dest, prefix, newKey, desc); } else { const { value } = desc; if (typeof value === 'function') { desc.value = uncurryThis(value); } const name = `${prefix}${newKey}`; ReflectDefineProperty(dest, name, desc); if (varargsMethods.includes(name)) { ReflectDefineProperty(dest, `${name}Apply`, { value: applyBind(value), }); } } } } // Create copies of configurable value properties of the global object [ 'Proxy', 'globalThis', ].forEach((name) => { // eslint-disable-next-line no-restricted-globals primordials[name] = globalThis[name]; }); // Create copies of URI handling functions [ decodeURI, decodeURIComponent, encodeURI, encodeURIComponent, ].forEach((fn) => { primordials[fn.name] = fn; }); // Create copies of the namespace objects [ 'JSON', 'Math', 'Proxy', 'Reflect', ].forEach((name) => { // eslint-disable-next-line no-restricted-globals copyPropsRenamed(global[name], primordials, name); }); // Create copies of intrinsic objects [ 'Array', 'ArrayBuffer', 'BigInt', 'BigInt64Array', 'BigUint64Array', 'Boolean', 'DataView', 'Date', 'Error', 'EvalError', 'Float32Array', 'Float64Array', 'Function', 'Int16Array', 'Int32Array', 'Int8Array', 'Map', 'Number', 'Object', 'RangeError', 'ReferenceError', 'RegExp', 'Set', 'String', 'Symbol', 'SyntaxError', 'TypeError', 'URIError', 'Uint16Array', 'Uint32Array', 'Uint8Array', 'Uint8ClampedArray', 'WeakMap', 'WeakSet', ].forEach((name) => { // eslint-disable-next-line no-restricted-globals const original = global[name]; primordials[name] = original; copyPropsRenamed(original, primordials, name); copyPrototype(original.prototype, primordials, `${name}Prototype`); }); // Create copies of intrinsic objects that require a valid `this` to call // static methods. // Refs: https://www.ecma-international.org/ecma-262/#sec-promise.all [ 'Promise', ].forEach((name) => { // eslint-disable-next-line no-restricted-globals const original = global[name]; primordials[name] = original; copyPropsRenamedBound(original, primordials, name); copyPrototype(original.prototype, primordials, `${name}Prototype`); }); // Create copies of abstract intrinsic objects that are not directly exposed // on the global object. // Refs: https://tc39.es/ecma262/#sec-%typedarray%-intrinsic-object [ { name: 'TypedArray', original: Reflect.getPrototypeOf(Uint8Array) }, { name: 'ArrayIterator', original: { prototype: Reflect.getPrototypeOf(Array.prototype[Symbol.iterator]()), } }, { name: 'StringIterator', original: { prototype: Reflect.getPrototypeOf(String.prototype[Symbol.iterator]()), } }, ].forEach(({ name, original }) => { primordials[name] = original; // The static %TypedArray% methods require a valid `this`, but can't be bound, // as they need a subclass constructor as the receiver: copyPrototype(original, primordials, name); copyPrototype(original.prototype, primordials, `${name}Prototype`); }); /* eslint-enable node-core/prefer-primordials */ const { ArrayPrototypeForEach, FunctionPrototypeCall, Map, ObjectFreeze, ObjectSetPrototypeOf, Set, SymbolIterator, WeakMap, WeakSet, } = primordials; // Because these functions are used by `makeSafe`, which is exposed // on the `primordials` object, it's important to use const references // to the primordials that they use: const createSafeIterator = (factory, next) => { class SafeIterator { constructor(iterable) { this._iterator = factory(iterable); } next() { return next(this._iterator); } [SymbolIterator]() { return this; } } ObjectSetPrototypeOf(SafeIterator.prototype, null); ObjectFreeze(SafeIterator.prototype); ObjectFreeze(SafeIterator); return SafeIterator; }; primordials.SafeArrayIterator = createSafeIterator( primordials.ArrayPrototypeSymbolIterator, primordials.ArrayIteratorPrototypeNext ); primordials.SafeStringIterator = createSafeIterator( primordials.StringPrototypeSymbolIterator, primordials.StringIteratorPrototypeNext ); const copyProps = (src, dest) => { ArrayPrototypeForEach(ReflectOwnKeys(src), (key) => { if (!ReflectGetOwnPropertyDescriptor(dest, key)) { ReflectDefineProperty( dest, key, ReflectGetOwnPropertyDescriptor(src, key)); } }); }; const makeSafe = (unsafe, safe) => { if (SymbolIterator in unsafe.prototype) { const dummy = new unsafe(); let next; // We can reuse the same `next` method. ArrayPrototypeForEach(ReflectOwnKeys(unsafe.prototype), (key) => { if (!ReflectGetOwnPropertyDescriptor(safe.prototype, key)) { const desc = ReflectGetOwnPropertyDescriptor(unsafe.prototype, key); if ( typeof desc.value === 'function' && desc.value.length === 0 && SymbolIterator in (FunctionPrototypeCall(desc.value, dummy) ?? {}) ) { const createIterator = uncurryThis(desc.value); next = next ?? uncurryThis(createIterator(dummy).next); const SafeIterator = createSafeIterator(createIterator, next); desc.value = function() { return new SafeIterator(this); }; } ReflectDefineProperty(safe.prototype, key, desc); } }); } else { copyProps(unsafe.prototype, safe.prototype); } copyProps(unsafe, safe); ObjectSetPrototypeOf(safe.prototype, null); ObjectFreeze(safe.prototype); ObjectFreeze(safe); return safe; }; primordials.makeSafe = makeSafe; // Subclass the constructors because we need to use their prototype // methods later. // Defining the `constructor` is necessary here to avoid the default // constructor which uses the user-mutable `%ArrayIteratorPrototype%.next`. primordials.SafeMap = makeSafe( Map, class SafeMap extends Map { constructor(i) { super(i); } // eslint-disable-line no-useless-constructor } ); primordials.SafeWeakMap = makeSafe( WeakMap, class SafeWeakMap extends WeakMap { constructor(i) { super(i); } // eslint-disable-line no-useless-constructor } ); primordials.SafeSet = makeSafe( Set, class SafeSet extends Set { constructor(i) { super(i); } // eslint-disable-line no-useless-constructor } ); primordials.SafeWeakSet = makeSafe( WeakSet, class SafeWeakSet extends WeakSet { constructor(i) { super(i); } // eslint-disable-line no-useless-constructor } ); ObjectSetPrototypeOf(primordials, null); ObjectFreeze(primordials); module.exports = primordials; PK ~\]{],],@pkgjs/parseargs/LICENSEnu[ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. PK ~\5:Un22@pkgjs/parseargs/index.jsnu['use strict'; const { ArrayPrototypeForEach, ArrayPrototypeIncludes, ArrayPrototypeMap, ArrayPrototypePush, ArrayPrototypePushApply, ArrayPrototypeShift, ArrayPrototypeSlice, ArrayPrototypeUnshiftApply, ObjectEntries, ObjectPrototypeHasOwnProperty: ObjectHasOwn, StringPrototypeCharAt, StringPrototypeIndexOf, StringPrototypeSlice, StringPrototypeStartsWith, } = require('./internal/primordials'); const { validateArray, validateBoolean, validateBooleanArray, validateObject, validateString, validateStringArray, validateUnion, } = require('./internal/validators'); const { kEmptyObject, } = require('./internal/util'); const { findLongOptionForShort, isLoneLongOption, isLoneShortOption, isLongOptionAndValue, isOptionValue, isOptionLikeValue, isShortOptionAndValue, isShortOptionGroup, useDefaultValueOption, objectGetOwn, optionsGetOwn, } = require('./utils'); const { codes: { ERR_INVALID_ARG_VALUE, ERR_PARSE_ARGS_INVALID_OPTION_VALUE, ERR_PARSE_ARGS_UNKNOWN_OPTION, ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL, }, } = require('./internal/errors'); function getMainArgs() { // Work out where to slice process.argv for user supplied arguments. // Check node options for scenarios where user CLI args follow executable. const execArgv = process.execArgv; if (ArrayPrototypeIncludes(execArgv, '-e') || ArrayPrototypeIncludes(execArgv, '--eval') || ArrayPrototypeIncludes(execArgv, '-p') || ArrayPrototypeIncludes(execArgv, '--print')) { return ArrayPrototypeSlice(process.argv, 1); } // Normally first two arguments are executable and script, then CLI arguments return ArrayPrototypeSlice(process.argv, 2); } /** * In strict mode, throw for possible usage errors like --foo --bar * * @param {object} token - from tokens as available from parseArgs */ function checkOptionLikeValue(token) { if (!token.inlineValue && isOptionLikeValue(token.value)) { // Only show short example if user used short option. const example = StringPrototypeStartsWith(token.rawName, '--') ? `'${token.rawName}=-XYZ'` : `'--${token.name}=-XYZ' or '${token.rawName}-XYZ'`; const errorMessage = `Option '${token.rawName}' argument is ambiguous. Did you forget to specify the option argument for '${token.rawName}'? To specify an option argument starting with a dash use ${example}.`; throw new ERR_PARSE_ARGS_INVALID_OPTION_VALUE(errorMessage); } } /** * In strict mode, throw for usage errors. * * @param {object} config - from config passed to parseArgs * @param {object} token - from tokens as available from parseArgs */ function checkOptionUsage(config, token) { if (!ObjectHasOwn(config.options, token.name)) { throw new ERR_PARSE_ARGS_UNKNOWN_OPTION( token.rawName, config.allowPositionals); } const short = optionsGetOwn(config.options, token.name, 'short'); const shortAndLong = `${short ? `-${short}, ` : ''}--${token.name}`; const type = optionsGetOwn(config.options, token.name, 'type'); if (type === 'string' && typeof token.value !== 'string') { throw new ERR_PARSE_ARGS_INVALID_OPTION_VALUE(`Option '${shortAndLong} ' argument missing`); } // (Idiomatic test for undefined||null, expecting undefined.) if (type === 'boolean' && token.value != null) { throw new ERR_PARSE_ARGS_INVALID_OPTION_VALUE(`Option '${shortAndLong}' does not take an argument`); } } /** * Store the option value in `values`. * * @param {string} longOption - long option name e.g. 'foo' * @param {string|undefined} optionValue - value from user args * @param {object} options - option configs, from parseArgs({ options }) * @param {object} values - option values returned in `values` by parseArgs */ function storeOption(longOption, optionValue, options, values) { if (longOption === '__proto__') { return; // No. Just no. } // We store based on the option value rather than option type, // preserving the users intent for author to deal with. const newValue = optionValue ?? true; if (optionsGetOwn(options, longOption, 'multiple')) { // Always store value in array, including for boolean. // values[longOption] starts out not present, // first value is added as new array [newValue], // subsequent values are pushed to existing array. // (note: values has null prototype, so simpler usage) if (values[longOption]) { ArrayPrototypePush(values[longOption], newValue); } else { values[longOption] = [newValue]; } } else { values[longOption] = newValue; } } /** * Store the default option value in `values`. * * @param {string} longOption - long option name e.g. 'foo' * @param {string * | boolean * | string[] * | boolean[]} optionValue - default value from option config * @param {object} values - option values returned in `values` by parseArgs */ function storeDefaultOption(longOption, optionValue, values) { if (longOption === '__proto__') { return; // No. Just no. } values[longOption] = optionValue; } /** * Process args and turn into identified tokens: * - option (along with value, if any) * - positional * - option-terminator * * @param {string[]} args - from parseArgs({ args }) or mainArgs * @param {object} options - option configs, from parseArgs({ options }) */ function argsToTokens(args, options) { const tokens = []; let index = -1; let groupCount = 0; const remainingArgs = ArrayPrototypeSlice(args); while (remainingArgs.length > 0) { const arg = ArrayPrototypeShift(remainingArgs); const nextArg = remainingArgs[0]; if (groupCount > 0) groupCount--; else index++; // Check if `arg` is an options terminator. // Guideline 10 in https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html if (arg === '--') { // Everything after a bare '--' is considered a positional argument. ArrayPrototypePush(tokens, { kind: 'option-terminator', index }); ArrayPrototypePushApply( tokens, ArrayPrototypeMap(remainingArgs, (arg) => { return { kind: 'positional', index: ++index, value: arg }; }) ); break; // Finished processing args, leave while loop. } if (isLoneShortOption(arg)) { // e.g. '-f' const shortOption = StringPrototypeCharAt(arg, 1); const longOption = findLongOptionForShort(shortOption, options); let value; let inlineValue; if (optionsGetOwn(options, longOption, 'type') === 'string' && isOptionValue(nextArg)) { // e.g. '-f', 'bar' value = ArrayPrototypeShift(remainingArgs); inlineValue = false; } ArrayPrototypePush( tokens, { kind: 'option', name: longOption, rawName: arg, index, value, inlineValue }); if (value != null) ++index; continue; } if (isShortOptionGroup(arg, options)) { // Expand -fXzy to -f -X -z -y const expanded = []; for (let index = 1; index < arg.length; index++) { const shortOption = StringPrototypeCharAt(arg, index); const longOption = findLongOptionForShort(shortOption, options); if (optionsGetOwn(options, longOption, 'type') !== 'string' || index === arg.length - 1) { // Boolean option, or last short in group. Well formed. ArrayPrototypePush(expanded, `-${shortOption}`); } else { // String option in middle. Yuck. // Expand -abfFILE to -a -b -fFILE ArrayPrototypePush(expanded, `-${StringPrototypeSlice(arg, index)}`); break; // finished short group } } ArrayPrototypeUnshiftApply(remainingArgs, expanded); groupCount = expanded.length; continue; } if (isShortOptionAndValue(arg, options)) { // e.g. -fFILE const shortOption = StringPrototypeCharAt(arg, 1); const longOption = findLongOptionForShort(shortOption, options); const value = StringPrototypeSlice(arg, 2); ArrayPrototypePush( tokens, { kind: 'option', name: longOption, rawName: `-${shortOption}`, index, value, inlineValue: true }); continue; } if (isLoneLongOption(arg)) { // e.g. '--foo' const longOption = StringPrototypeSlice(arg, 2); let value; let inlineValue; if (optionsGetOwn(options, longOption, 'type') === 'string' && isOptionValue(nextArg)) { // e.g. '--foo', 'bar' value = ArrayPrototypeShift(remainingArgs); inlineValue = false; } ArrayPrototypePush( tokens, { kind: 'option', name: longOption, rawName: arg, index, value, inlineValue }); if (value != null) ++index; continue; } if (isLongOptionAndValue(arg)) { // e.g. --foo=bar const equalIndex = StringPrototypeIndexOf(arg, '='); const longOption = StringPrototypeSlice(arg, 2, equalIndex); const value = StringPrototypeSlice(arg, equalIndex + 1); ArrayPrototypePush( tokens, { kind: 'option', name: longOption, rawName: `--${longOption}`, index, value, inlineValue: true }); continue; } ArrayPrototypePush(tokens, { kind: 'positional', index, value: arg }); } return tokens; } const parseArgs = (config = kEmptyObject) => { const args = objectGetOwn(config, 'args') ?? getMainArgs(); const strict = objectGetOwn(config, 'strict') ?? true; const allowPositionals = objectGetOwn(config, 'allowPositionals') ?? !strict; const returnTokens = objectGetOwn(config, 'tokens') ?? false; const options = objectGetOwn(config, 'options') ?? { __proto__: null }; // Bundle these up for passing to strict-mode checks. const parseConfig = { args, strict, options, allowPositionals }; // Validate input configuration. validateArray(args, 'args'); validateBoolean(strict, 'strict'); validateBoolean(allowPositionals, 'allowPositionals'); validateBoolean(returnTokens, 'tokens'); validateObject(options, 'options'); ArrayPrototypeForEach( ObjectEntries(options), ({ 0: longOption, 1: optionConfig }) => { validateObject(optionConfig, `options.${longOption}`); // type is required const optionType = objectGetOwn(optionConfig, 'type'); validateUnion(optionType, `options.${longOption}.type`, ['string', 'boolean']); if (ObjectHasOwn(optionConfig, 'short')) { const shortOption = optionConfig.short; validateString(shortOption, `options.${longOption}.short`); if (shortOption.length !== 1) { throw new ERR_INVALID_ARG_VALUE( `options.${longOption}.short`, shortOption, 'must be a single character' ); } } const multipleOption = objectGetOwn(optionConfig, 'multiple'); if (ObjectHasOwn(optionConfig, 'multiple')) { validateBoolean(multipleOption, `options.${longOption}.multiple`); } const defaultValue = objectGetOwn(optionConfig, 'default'); if (defaultValue !== undefined) { let validator; switch (optionType) { case 'string': validator = multipleOption ? validateStringArray : validateString; break; case 'boolean': validator = multipleOption ? validateBooleanArray : validateBoolean; break; } validator(defaultValue, `options.${longOption}.default`); } } ); // Phase 1: identify tokens const tokens = argsToTokens(args, options); // Phase 2: process tokens into parsed option values and positionals const result = { values: { __proto__: null }, positionals: [], }; if (returnTokens) { result.tokens = tokens; } ArrayPrototypeForEach(tokens, (token) => { if (token.kind === 'option') { if (strict) { checkOptionUsage(parseConfig, token); checkOptionLikeValue(token); } storeOption(token.name, token.value, options, result.values); } else if (token.kind === 'positional') { if (!allowPositionals) { throw new ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL(token.value); } ArrayPrototypePush(result.positionals, token.value); } }); // Phase 3: fill in default values for missing args ArrayPrototypeForEach(ObjectEntries(options), ({ 0: longOption, 1: optionConfig }) => { const mustSetDefault = useDefaultValueOption(longOption, optionConfig, result.values); if (mustSetDefault) { storeDefaultOption(longOption, objectGetOwn(optionConfig, 'default'), result.values); } }); return result; }; module.exports = { parseArgs, }; PK ~\-@pkgjs/parseargs/examples/is-default-value.jsnu['use strict'; // This example shows how to understand if a default value is used or not. // 1. const { parseArgs } = require('node:util'); // from node // 2. const { parseArgs } = require('@pkgjs/parseargs'); // from package const { parseArgs } = require('..'); // in repo const options = { file: { short: 'f', type: 'string', default: 'FOO' }, }; const { values, tokens } = parseArgs({ options, tokens: true }); const isFileDefault = !tokens.some((token) => token.kind === 'option' && token.name === 'file' ); console.log(values); console.log(`Is the file option [${values.file}] the default value? ${isFileDefault}`); // Try the following: // node is-default-value.js // node is-default-value.js -f FILE // node is-default-value.js --file FILE PK ~\x-tt-@pkgjs/parseargs/examples/ordered-options.mjsnu[// This is an example of using tokens to add a custom behaviour. // // This adds a option order check so that --some-unstable-option // may only be used after --enable-experimental-options // // Note: this is not a common behaviour, the order of different options // does not usually matter. import { parseArgs } from '../index.js'; function findTokenIndex(tokens, target) { return tokens.findIndex((token) => token.kind === 'option' && token.name === target ); } const experimentalName = 'enable-experimental-options'; const unstableName = 'some-unstable-option'; const options = { [experimentalName]: { type: 'boolean' }, [unstableName]: { type: 'boolean' }, }; const { values, tokens } = parseArgs({ options, tokens: true }); const experimentalIndex = findTokenIndex(tokens, experimentalName); const unstableIndex = findTokenIndex(tokens, unstableName); if (unstableIndex !== -1 && ((experimentalIndex === -1) || (unstableIndex < experimentalIndex))) { throw new Error(`'--${experimentalName}' must be specified before '--${unstableName}'`); } console.log(values); /* eslint-disable max-len */ // Try the following: // node ordered-options.mjs // node ordered-options.mjs --some-unstable-option // node ordered-options.mjs --some-unstable-option --enable-experimental-options // node ordered-options.mjs --enable-experimental-options --some-unstable-option PK ~\!//.@pkgjs/parseargs/examples/limit-long-syntax.jsnu['use strict'; // This is an example of using tokens to add a custom behaviour. // // Require the use of `=` for long options and values by blocking // the use of space separated values. // So allow `--foo=bar`, and not allow `--foo bar`. // // Note: this is not a common behaviour, most CLIs allow both forms. // 1. const { parseArgs } = require('node:util'); // from node // 2. const { parseArgs } = require('@pkgjs/parseargs'); // from package const { parseArgs } = require('..'); // in repo const options = { file: { short: 'f', type: 'string' }, log: { type: 'string' }, }; const { values, tokens } = parseArgs({ options, tokens: true }); const badToken = tokens.find((token) => token.kind === 'option' && token.value != null && token.rawName.startsWith('--') && !token.inlineValue ); if (badToken) { throw new Error(`Option value for '${badToken.rawName}' must be inline, like '${badToken.rawName}=VALUE'`); } console.log(values); // Try the following: // node limit-long-syntax.js -f FILE --log=LOG // node limit-long-syntax.js --file FILE PK ~\k0@pkgjs/parseargs/examples/no-repeated-options.jsnu['use strict'; // This is an example of using tokens to add a custom behaviour. // // Throw an error if an option is used more than once. // 1. const { parseArgs } = require('node:util'); // from node // 2. const { parseArgs } = require('@pkgjs/parseargs'); // from package const { parseArgs } = require('..'); // in repo const options = { ding: { type: 'boolean', short: 'd' }, beep: { type: 'boolean', short: 'b' } }; const { values, tokens } = parseArgs({ options, tokens: true }); const seenBefore = new Set(); tokens.forEach((token) => { if (token.kind !== 'option') return; if (seenBefore.has(token.name)) { throw new Error(`option '${token.name}' used multiple times`); } seenBefore.add(token.name); }); console.log(values); // Try the following: // node no-repeated-options --ding --beep // node no-repeated-options --beep -b // node no-repeated-options -ddd PK ~\%l.@pkgjs/parseargs/examples/simple-hard-coded.jsnu['use strict'; // This example is used in the documentation. // 1. const { parseArgs } = require('node:util'); // from node // 2. const { parseArgs } = require('@pkgjs/parseargs'); // from package const { parseArgs } = require('..'); // in repo const args = ['-f', '--bar', 'b']; const options = { foo: { type: 'boolean', short: 'f' }, bar: { type: 'string' } }; const { values, positionals } = parseArgs({ args, options }); console.log(values, positionals); // Try the following: // node simple-hard-coded.js PK ~\D}""#@pkgjs/parseargs/examples/negate.jsnu['use strict'; // This example is used in the documentation. // How might I add my own support for --no-foo? // 1. const { parseArgs } = require('node:util'); // from node // 2. const { parseArgs } = require('@pkgjs/parseargs'); // from package const { parseArgs } = require('..'); // in repo const options = { 'color': { type: 'boolean' }, 'no-color': { type: 'boolean' }, 'logfile': { type: 'string' }, 'no-logfile': { type: 'boolean' }, }; const { values, tokens } = parseArgs({ options, tokens: true }); // Reprocess the option tokens and overwrite the returned values. tokens .filter((token) => token.kind === 'option') .forEach((token) => { if (token.name.startsWith('no-')) { // Store foo:false for --no-foo const positiveName = token.name.slice(3); values[positiveName] = false; delete values[token.name]; } else { // Resave value so last one wins if both --foo and --no-foo. values[token.name] = token.value ?? true; } }); const color = values.color; const logfile = values.logfile ?? 'default.log'; console.log({ logfile, color }); // Try the following: // node negate.js // node negate.js --no-logfile --no-color // negate.js --logfile=test.log --color // node negate.js --no-logfile --logfile=test.log --color --no-color PK ~\Z :-util-deprecate/package.jsonnu[{ "_id": "util-deprecate@1.0.2", "_inBundle": true, "_location": "/npm/util-deprecate", "_phantomChildren": {}, "_requiredBy": [ "/npm/postcss-selector-parser" ], "author": { "name": "Nathan Rajlich", "email": "nathan@tootallnate.net", "url": "http://n8.io/" }, "browser": "browser.js", "bugs": { "url": "https://github.com/TooTallNate/util-deprecate/issues" }, "description": "The Node.js `util.deprecate()` function with browser support", "homepage": "https://github.com/TooTallNate/util-deprecate", "keywords": [ "util", "deprecate", "browserify", "browser", "node" ], "license": "MIT", "main": "node.js", "name": "util-deprecate", "repository": { "type": "git", "url": "git://github.com/TooTallNate/util-deprecate.git" }, "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "version": "1.0.2" } PK ~\Gutil-deprecate/History.mdnu[ 1.0.2 / 2015-10-07 ================== * use try/catch when checking `localStorage` (#3, @kumavis) 1.0.1 / 2014-11-25 ================== * browser: use `console.warn()` for deprecation calls * browser: more jsdocs 1.0.0 / 2014-04-30 ================== * initial commit PK ~\ ƠNNutil-deprecate/LICENSEnu[(The MIT License) Copyright (c) 2014 Nathan Rajlich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\y2{{util-deprecate/node.jsnu[ /** * For Node.js, simply re-export the core `util.deprecate` function. */ module.exports = require('util').deprecate; PK ~\/NNutil-deprecate/browser.jsnu[ /** * Module exports. */ module.exports = deprecate; /** * Mark that a method should not be used. * Returns a modified function which warns once by default. * * If `localStorage.noDeprecation = true` is set, then it is a no-op. * * If `localStorage.throwDeprecation = true` is set, then deprecated functions * will throw an Error when invoked. * * If `localStorage.traceDeprecation = true` is set, then deprecated functions * will invoke `console.trace()` instead of `console.error()`. * * @param {Function} fn - the function to deprecate * @param {String} msg - the string to print to the console when `fn` is invoked * @returns {Function} a new "deprecated" version of `fn` * @api public */ function deprecate (fn, msg) { if (config('noDeprecation')) { return fn; } var warned = false; function deprecated() { if (!warned) { if (config('throwDeprecation')) { throw new Error(msg); } else if (config('traceDeprecation')) { console.trace(msg); } else { console.warn(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; } /** * Checks `localStorage` for boolean values for the given `name`. * * @param {String} name * @returns {Boolean} * @api private */ function config (name) { // accessing global.localStorage can trigger a DOMException in sandboxed iframes try { if (!global.localStorage) return false; } catch (_) { return false; } var val = global.localStorage[name]; if (null == val) return false; return String(val).toLowerCase() === 'true'; } PK ~\3SSinit-package-json/package.jsonnu[{ "_id": "init-package-json@6.0.3", "_inBundle": true, "_location": "/npm/init-package-json", "_phantomChildren": {}, "_requiredBy": [ "/npm" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/init-package-json/issues" }, "dependencies": { "@npmcli/package-json": "^5.0.0", "npm-package-arg": "^11.0.0", "promzard": "^1.0.0", "read": "^3.0.1", "semver": "^7.3.5", "validate-npm-package-license": "^3.0.4", "validate-npm-package-name": "^5.0.0" }, "description": "A node module to get your node module started", "devDependencies": { "@npmcli/config": "^8.2.0", "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.22.0", "tap": "^16.0.1" }, "engines": { "node": "^16.14.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/init-package-json#readme", "keywords": [ "init", "package.json", "package", "helper", "wizard", "wizerd", "prompt", "start" ], "license": "ISC", "main": "lib/init-package-json.js", "name": "init-package-json", "repository": { "type": "git", "url": "git+https://github.com/npm/init-package-json.git" }, "scripts": { "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "test-ignore": "fixtures/", "nyc-arg": [ "--exclude", "tap-snapshots/**" ], "timeout": 300 }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.22.0", "publish": true }, "version": "6.0.3" } PK ~\5Q&init-package-json/lib/default-input.jsnu[/* globals config, dirname, package, basename, yes, prompt */ const fs = require('fs/promises') const path = require('path') const validateLicense = require('validate-npm-package-license') const validateName = require('validate-npm-package-name') const npa = require('npm-package-arg') const semver = require('semver') // more popular packages should go here, maybe? const isTestPkg = (p) => !!p.match(/^(expresso|mocha|tap|coffee-script|coco|streamline)$/) const invalid = (msg) => Object.assign(new Error(msg), { notValid: true }) const readDeps = (test, excluded) => async () => { const dirs = await fs.readdir('node_modules').catch(() => null) if (!dirs) { return } const deps = {} for (const dir of dirs) { if (dir.match(/^\./) || test !== isTestPkg(dir) || excluded[dir]) { continue } const dp = path.join(dirname, 'node_modules', dir, 'package.json') const p = await fs.readFile(dp, 'utf8').then((d) => JSON.parse(d)).catch(() => null) if (!p || !p.version || p?._requiredBy?.some((r) => r === '#USER')) { continue } deps[dir] = config.get('save-exact') ? p.version : config.get('save-prefix') + p.version } return deps } const getConfig = (key) => { // dots take precedence over dashes const def = config?.defaults?.[`init.${key}`] const val = config.get(`init.${key}`) return (val !== def && val) ? val : config.get(`init-${key.replace(/\./g, '-')}`) } const getName = () => { const rawName = package.name || basename let name = rawName .replace(/^node-|[.-]js$/g, '') .replace(/\s+/g, ' ') .replace(/ /g, '-') .toLowerCase() let spec try { spec = npa(name) } catch { spec = {} } let scope = config.get('scope') if (scope) { if (scope.charAt(0) !== '@') { scope = '@' + scope } if (spec.scope) { name = scope + '/' + spec.name.split('/')[1] } else { name = scope + '/' + name } } return name } const name = getName() exports.name = yes ? name : prompt('package name', name, (data) => { const its = validateName(data) if (its.validForNewPackages) { return data } const errors = (its.errors || []).concat(its.warnings || []) return invalid(`Sorry, ${errors.join(' and ')}.`) }) const version = package.version || getConfig('version') || '1.0.0' exports.version = yes ? version : prompt('version', version, (v) => { if (semver.valid(v)) { return v } return invalid(`Invalid version: "${v}"`) }) if (!package.description) { exports.description = yes ? '' : prompt('description') } if (!package.main) { exports.main = async () => { const files = await fs.readdir(dirname) .then(list => list.filter((f) => f.match(/\.js$/))) .catch(() => []) let index if (files.includes('index.js')) { index = 'index.js' } else if (files.includes('main.js')) { index = 'main.js' } else if (files.includes(basename + '.js')) { index = basename + '.js' } else { index = files[0] || 'index.js' } return yes ? index : prompt('entry point', index) } } if (!package.bin) { exports.bin = async () => { try { const d = await fs.readdir(path.resolve(dirname, 'bin')) // just take the first js file we find there, or nada let r = d.find(f => f.match(/\.js$/)) if (r) { r = `bin/${r}` } return r } catch { // no bins } } } exports.directories = async () => { const dirs = await fs.readdir(dirname) const res = dirs.reduce((acc, d) => { if (/^examples?$/.test(d)) { acc.example = d } else if (/^tests?$/.test(d)) { acc.test = d } else if (/^docs?$/.test(d)) { acc.doc = d } else if (d === 'man') { acc.man = d } else if (d === 'lib') { acc.lib = d } return acc }, {}) return Object.keys(res).length === 0 ? undefined : res } if (!package.dependencies) { exports.dependencies = readDeps(false, package.devDependencies || {}) } if (!package.devDependencies) { exports.devDependencies = readDeps(true, package.dependencies || {}) } // MUST have a test script! if (!package.scripts) { const scripts = package.scripts || {} const notest = 'echo "Error: no test specified" && exit 1' exports.scripts = async () => { const d = await fs.readdir(path.join(dirname, 'node_modules')).catch(() => []) // check to see what framework is in use, if any let command if (!scripts.test || scripts.test === notest) { const commands = { tap: 'tap test/*.js', expresso: 'expresso test', mocha: 'mocha', } for (const [k, v] of Object.entries(commands)) { if (d.includes(k)) { command = v } } } const promptArgs = ['test command', (t) => t || notest] if (command) { promptArgs.splice(1, 0, command) } scripts.test = yes ? command || notest : prompt(...promptArgs) return scripts } } if (!package.repository) { exports.repository = async () => { const gconf = await fs.readFile('.git/config', 'utf8').catch(() => '') const lines = gconf.split(/\r?\n/) let url const i = lines.indexOf('[remote "origin"]') if (i !== -1) { url = gconf[i + 1] if (!url.match(/^\s*url =/)) { url = gconf[i + 2] } if (!url.match(/^\s*url =/)) { url = null } else { url = url.replace(/^\s*url = /, '') } } if (url && url.match(/^git@github.com:/)) { url = url.replace(/^git@github.com:/, 'https://github.com/') } return yes ? url || '' : prompt('git repository', url || undefined) } } if (!package.keywords) { exports.keywords = yes ? '' : prompt('keywords', (data) => { if (!data) { return } if (Array.isArray(data)) { data = data.join(' ') } if (typeof data !== 'string') { return data } return data.split(/[\s,]+/) }) } if (!package.author) { const authorName = getConfig('author.name') exports.author = authorName ? { name: authorName, email: getConfig('author.email'), url: getConfig('author.url'), } : yes ? '' : prompt('author') } const license = package.license || getConfig('license') || 'ISC' exports.license = yes ? license : prompt('license', license, (data) => { const its = validateLicense(data) if (its.validForNewPackages) { return data } const errors = (its.errors || []).concat(its.warnings || []) return invalid(`Sorry, ${errors.join(' and ')}.`) }) PK ~\ bG))*init-package-json/lib/init-package-json.jsnu[ const promzard = require('promzard') const path = require('path') const semver = require('semver') const { read } = require('read') const util = require('util') const PackageJson = require('@npmcli/package-json') const def = require.resolve('./default-input.js') const extras = [ 'bundleDependencies', 'gypfile', 'serverjs', 'scriptpath', 'readme', 'bin', 'githead', 'fillTypes', 'normalizeData', ] const isYes = (c) => !!(c.get('yes') || c.get('y') || c.get('force') || c.get('f')) const getConfig = (c) => { // accept either a plain-jane object, or a config object with a "get" method. if (typeof c.get !== 'function') { const data = c return { get: (k) => data[k], toJSON: () => data, } } return c } // Coverage disabled because this is just walking back the fixPeople // normalization from the normalizeData step and we don't need to re-test all // of those paths. /* istanbul ignore next */ const stringifyPerson = (p) => { const { name, url, web, email, mail } = p const u = url || web const e = email || mail return `${name}${e ? ` <${e}>` : ''}${u ? ` (${u})` : ''}` } async function init (dir, // TODO test for non-default definitions /* istanbul ignore next */ input = def, c = {}) { const config = getConfig(c) const yes = isYes(config) const packageFile = path.resolve(dir, 'package.json') // read what's already there to inform our prompts const pkg = await PackageJson.load(dir, { create: true }) await pkg.normalize() if (!semver.valid(pkg.content.version)) { delete pkg.content.version } // make sure that the input is valid. if not, use the default const pzData = await promzard(path.resolve(input), { yes, config, filename: packageFile, dirname: dir, basename: path.basename(dir), package: pkg.content, }, { backupFile: def }) for (const [k, v] of Object.entries(pzData)) { if (v != null) { pkg.content[k] = v } } await pkg.normalize({ steps: extras }) // turn the objects back into somewhat more humane strings. // "normalizeData" does this and there isn't a way to choose which of those steps happen if (pkg.content.author) { pkg.content.author = stringifyPerson(pkg.content.author) } // no need for the readme now. delete pkg.content.readme delete pkg.content.readmeFilename // really don't want to have this lying around in the file delete pkg.content._id // ditto delete pkg.content.gitHead // if the repo is empty, remove it. if (!pkg.content.repository) { delete pkg.content.repository } // readJson filters out empty descriptions, but init-package-json // traditionally leaves them alone if (!pkg.content.description) { pkg.content.description = pzData.description } // optionalDependencies don't need to be repeated in two places if (pkg.content.dependencies) { if (pkg.content.optionalDependencies) { for (const name of Object.keys(pkg.content.optionalDependencies)) { delete pkg.content.dependencies[name] } } if (Object.keys(pkg.content.dependencies).length === 0) { delete pkg.content.dependencies } } const stringified = JSON.stringify(pkg.content, null, 2) + '\n' const msg = util.format('%s:\n\n%s\n', packageFile, stringified) if (yes) { await pkg.save() if (!config.get('silent')) { // eslint-disable-next-line no-console console.log(`Wrote to ${msg}`) } return pkg.content } // eslint-disable-next-line no-console console.log(`About to write to ${msg}`) const ok = await read({ prompt: 'Is this OK? ', default: 'yes' }) if (!ok || !ok.toLowerCase().startsWith('y')) { // eslint-disable-next-line no-console console.log('Aborted.') return } await pkg.save() return pkg.content } module.exports = init module.exports.yes = isYes PK ~\- init-package-json/LICENSE.mdnu[ISC License Copyright npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND NPM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NPM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\T##tar/package.jsonnu[{ "_id": "tar@6.2.1", "_inBundle": true, "_location": "/npm/tar", "_phantomChildren": { "yallist": "4.0.0" }, "_requiredBy": [ "/npm", "/npm/cacache", "/npm/libnpmdiff", "/npm/node-gyp", "/npm/pacote" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/isaacs/node-tar/issues" }, "dependencies": { "chownr": "^2.0.0", "fs-minipass": "^2.0.0", "minipass": "^5.0.0", "minizlib": "^2.1.1", "mkdirp": "^1.0.3", "yallist": "^4.0.0" }, "description": "tar for node", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.11.0", "chmodr": "^1.2.0", "end-of-stream": "^1.4.3", "events-to-array": "^2.0.3", "mutate-fs": "^2.1.1", "nock": "^13.2.9", "rimraf": "^3.0.2", "tap": "^16.0.1" }, "engines": { "node": ">=10" }, "files": [ "bin/", "lib/", "index.js" ], "homepage": "https://github.com/isaacs/node-tar#readme", "license": "ISC", "name": "tar", "repository": { "type": "git", "url": "git+https://github.com/isaacs/node-tar.git" }, "scripts": { "genparse": "node scripts/generate-parse-fixtures.js", "snap": "tap", "test": "tap" }, "tap": { "coverage-map": "map.js", "timeout": 0, "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.11.0", "content": "scripts/template-oss", "engines": ">=10", "distPaths": [ "index.js" ], "allowPaths": [ "/index.js" ], "ciVersions": [ "10.x", "12.x", "14.x", "16.x", "18.x" ] }, "version": "6.2.1" } PK ~\&tar/node_modules/minipass/package.jsonnu[{ "_id": "minipass@5.0.0", "_inBundle": true, "_location": "/npm/tar/minipass", "_phantomChildren": {}, "_requiredBy": [ "/npm/tar" ], "author": { "name": "Isaac Z. Schlueter", "email": "i@izs.me", "url": "http://blog.izs.me/" }, "bugs": { "url": "https://github.com/isaacs/minipass/issues" }, "description": "minimal implementation of a PassThrough stream", "devDependencies": { "@types/node": "^17.0.41", "end-of-stream": "^1.4.0", "node-abort-controller": "^3.1.1", "prettier": "^2.6.2", "tap": "^16.2.0", "through2": "^2.0.3", "ts-node": "^10.8.1", "typedoc": "^0.23.24", "typescript": "^4.7.3" }, "engines": { "node": ">=8" }, "exports": { ".": { "import": { "types": "./index.d.ts", "default": "./index.mjs" }, "require": { "types": "./index.d.ts", "default": "./index.js" } }, "./package.json": "./package.json" }, "files": [ "index.d.ts", "index.js", "index.mjs" ], "homepage": "https://github.com/isaacs/minipass#readme", "keywords": [ "passthrough", "stream" ], "license": "ISC", "main": "./index.js", "module": "./index.mjs", "name": "minipass", "prettier": { "semi": false, "printWidth": 80, "tabWidth": 2, "useTabs": false, "singleQuote": true, "jsxSingleQuote": false, "bracketSameLine": true, "arrowParens": "avoid", "endOfLine": "lf" }, "repository": { "type": "git", "url": "git+https://github.com/isaacs/minipass.git" }, "scripts": { "format": "prettier --write . --loglevel warn", "postpublish": "git push origin --follow-tags", "postversion": "npm publish", "prepare": "node ./scripts/transpile-to-esm.js", "presnap": "npm run prepare", "pretest": "npm run prepare", "preversion": "npm test", "snap": "tap", "test": "tap", "typedoc": "typedoc ./index.d.ts" }, "tap": { "check-coverage": true }, "types": "./index.d.ts", "version": "5.0.0" } PK ~\Ҁ!tar/node_modules/minipass/LICENSEnu[The ISC License Copyright (c) 2017-2023 npm, Inc., Isaac Z. Schlueter, and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\31JwHwH"tar/node_modules/minipass/index.jsnu['use strict' const proc = typeof process === 'object' && process ? process : { stdout: null, stderr: null, } const EE = require('events') const Stream = require('stream') const stringdecoder = require('string_decoder') const SD = stringdecoder.StringDecoder const EOF = Symbol('EOF') const MAYBE_EMIT_END = Symbol('maybeEmitEnd') const EMITTED_END = Symbol('emittedEnd') const EMITTING_END = Symbol('emittingEnd') const EMITTED_ERROR = Symbol('emittedError') const CLOSED = Symbol('closed') const READ = Symbol('read') const FLUSH = Symbol('flush') const FLUSHCHUNK = Symbol('flushChunk') const ENCODING = Symbol('encoding') const DECODER = Symbol('decoder') const FLOWING = Symbol('flowing') const PAUSED = Symbol('paused') const RESUME = Symbol('resume') const BUFFER = Symbol('buffer') const PIPES = Symbol('pipes') const BUFFERLENGTH = Symbol('bufferLength') const BUFFERPUSH = Symbol('bufferPush') const BUFFERSHIFT = Symbol('bufferShift') const OBJECTMODE = Symbol('objectMode') // internal event when stream is destroyed const DESTROYED = Symbol('destroyed') // internal event when stream has an error const ERROR = Symbol('error') const EMITDATA = Symbol('emitData') const EMITEND = Symbol('emitEnd') const EMITEND2 = Symbol('emitEnd2') const ASYNC = Symbol('async') const ABORT = Symbol('abort') const ABORTED = Symbol('aborted') const SIGNAL = Symbol('signal') const defer = fn => Promise.resolve().then(fn) // TODO remove when Node v8 support drops const doIter = global._MP_NO_ITERATOR_SYMBOLS_ !== '1' const ASYNCITERATOR = (doIter && Symbol.asyncIterator) || Symbol('asyncIterator not implemented') const ITERATOR = (doIter && Symbol.iterator) || Symbol('iterator not implemented') // events that mean 'the stream is over' // these are treated specially, and re-emitted // if they are listened for after emitting. const isEndish = ev => ev === 'end' || ev === 'finish' || ev === 'prefinish' const isArrayBuffer = b => b instanceof ArrayBuffer || (typeof b === 'object' && b.constructor && b.constructor.name === 'ArrayBuffer' && b.byteLength >= 0) const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b) class Pipe { constructor(src, dest, opts) { this.src = src this.dest = dest this.opts = opts this.ondrain = () => src[RESUME]() dest.on('drain', this.ondrain) } unpipe() { this.dest.removeListener('drain', this.ondrain) } // istanbul ignore next - only here for the prototype proxyErrors() {} end() { this.unpipe() if (this.opts.end) this.dest.end() } } class PipeProxyErrors extends Pipe { unpipe() { this.src.removeListener('error', this.proxyErrors) super.unpipe() } constructor(src, dest, opts) { super(src, dest, opts) this.proxyErrors = er => dest.emit('error', er) src.on('error', this.proxyErrors) } } class Minipass extends Stream { constructor(options) { super() this[FLOWING] = false // whether we're explicitly paused this[PAUSED] = false this[PIPES] = [] this[BUFFER] = [] this[OBJECTMODE] = (options && options.objectMode) || false if (this[OBJECTMODE]) this[ENCODING] = null else this[ENCODING] = (options && options.encoding) || null if (this[ENCODING] === 'buffer') this[ENCODING] = null this[ASYNC] = (options && !!options.async) || false this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null this[EOF] = false this[EMITTED_END] = false this[EMITTING_END] = false this[CLOSED] = false this[EMITTED_ERROR] = null this.writable = true this.readable = true this[BUFFERLENGTH] = 0 this[DESTROYED] = false if (options && options.debugExposeBuffer === true) { Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] }) } if (options && options.debugExposePipes === true) { Object.defineProperty(this, 'pipes', { get: () => this[PIPES] }) } this[SIGNAL] = options && options.signal this[ABORTED] = false if (this[SIGNAL]) { this[SIGNAL].addEventListener('abort', () => this[ABORT]()) if (this[SIGNAL].aborted) { this[ABORT]() } } } get bufferLength() { return this[BUFFERLENGTH] } get encoding() { return this[ENCODING] } set encoding(enc) { if (this[OBJECTMODE]) throw new Error('cannot set encoding in objectMode') if ( this[ENCODING] && enc !== this[ENCODING] && ((this[DECODER] && this[DECODER].lastNeed) || this[BUFFERLENGTH]) ) throw new Error('cannot change encoding') if (this[ENCODING] !== enc) { this[DECODER] = enc ? new SD(enc) : null if (this[BUFFER].length) this[BUFFER] = this[BUFFER].map(chunk => this[DECODER].write(chunk)) } this[ENCODING] = enc } setEncoding(enc) { this.encoding = enc } get objectMode() { return this[OBJECTMODE] } set objectMode(om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om } get ['async']() { return this[ASYNC] } set ['async'](a) { this[ASYNC] = this[ASYNC] || !!a } // drop everything and get out of the flow completely [ABORT]() { this[ABORTED] = true this.emit('abort', this[SIGNAL].reason) this.destroy(this[SIGNAL].reason) } get aborted() { return this[ABORTED] } set aborted(_) {} write(chunk, encoding, cb) { if (this[ABORTED]) return false if (this[EOF]) throw new Error('write after end') if (this[DESTROYED]) { this.emit( 'error', Object.assign( new Error('Cannot call write after a stream was destroyed'), { code: 'ERR_STREAM_DESTROYED' } ) ) return true } if (typeof encoding === 'function') (cb = encoding), (encoding = 'utf8') if (!encoding) encoding = 'utf8' const fn = this[ASYNC] ? defer : f => f() // convert array buffers and typed array views into buffers // at some point in the future, we may want to do the opposite! // leave strings and buffers as-is // anything else switches us into object mode if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { if (isArrayBufferView(chunk)) chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) else if (isArrayBuffer(chunk)) chunk = Buffer.from(chunk) else if (typeof chunk !== 'string') // use the setter so we throw if we have encoding set this.objectMode = true } // handle object mode up front, since it's simpler // this yields better performance, fewer checks later. if (this[OBJECTMODE]) { /* istanbul ignore if - maybe impossible? */ if (this.flowing && this[BUFFERLENGTH] !== 0) this[FLUSH](true) if (this.flowing) this.emit('data', chunk) else this[BUFFERPUSH](chunk) if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } // at this point the chunk is a buffer or string // don't buffer it up or send it to the decoder if (!chunk.length) { if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } // fast-path writing strings of same encoding to a stream with // an empty buffer, skipping the buffer/decoder dance if ( typeof chunk === 'string' && // unless it is a string already ready for us to use !(encoding === this[ENCODING] && !this[DECODER].lastNeed) ) { chunk = Buffer.from(chunk, encoding) } if (Buffer.isBuffer(chunk) && this[ENCODING]) chunk = this[DECODER].write(chunk) // Note: flushing CAN potentially switch us into not-flowing mode if (this.flowing && this[BUFFERLENGTH] !== 0) this[FLUSH](true) if (this.flowing) this.emit('data', chunk) else this[BUFFERPUSH](chunk) if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } read(n) { if (this[DESTROYED]) return null if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) { this[MAYBE_EMIT_END]() return null } if (this[OBJECTMODE]) n = null if (this[BUFFER].length > 1 && !this[OBJECTMODE]) { if (this.encoding) this[BUFFER] = [this[BUFFER].join('')] else this[BUFFER] = [Buffer.concat(this[BUFFER], this[BUFFERLENGTH])] } const ret = this[READ](n || null, this[BUFFER][0]) this[MAYBE_EMIT_END]() return ret } [READ](n, chunk) { if (n === chunk.length || n === null) this[BUFFERSHIFT]() else { this[BUFFER][0] = chunk.slice(n) chunk = chunk.slice(0, n) this[BUFFERLENGTH] -= n } this.emit('data', chunk) if (!this[BUFFER].length && !this[EOF]) this.emit('drain') return chunk } end(chunk, encoding, cb) { if (typeof chunk === 'function') (cb = chunk), (chunk = null) if (typeof encoding === 'function') (cb = encoding), (encoding = 'utf8') if (chunk) this.write(chunk, encoding) if (cb) this.once('end', cb) this[EOF] = true this.writable = false // if we haven't written anything, then go ahead and emit, // even if we're not reading. // we'll re-emit if a new 'end' listener is added anyway. // This makes MP more suitable to write-only use cases. if (this.flowing || !this[PAUSED]) this[MAYBE_EMIT_END]() return this } // don't let the internal resume be overwritten [RESUME]() { if (this[DESTROYED]) return this[PAUSED] = false this[FLOWING] = true this.emit('resume') if (this[BUFFER].length) this[FLUSH]() else if (this[EOF]) this[MAYBE_EMIT_END]() else this.emit('drain') } resume() { return this[RESUME]() } pause() { this[FLOWING] = false this[PAUSED] = true } get destroyed() { return this[DESTROYED] } get flowing() { return this[FLOWING] } get paused() { return this[PAUSED] } [BUFFERPUSH](chunk) { if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1 else this[BUFFERLENGTH] += chunk.length this[BUFFER].push(chunk) } [BUFFERSHIFT]() { if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1 else this[BUFFERLENGTH] -= this[BUFFER][0].length return this[BUFFER].shift() } [FLUSH](noDrain) { do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]()) && this[BUFFER].length) if (!noDrain && !this[BUFFER].length && !this[EOF]) this.emit('drain') } [FLUSHCHUNK](chunk) { this.emit('data', chunk) return this.flowing } pipe(dest, opts) { if (this[DESTROYED]) return const ended = this[EMITTED_END] opts = opts || {} if (dest === proc.stdout || dest === proc.stderr) opts.end = false else opts.end = opts.end !== false opts.proxyErrors = !!opts.proxyErrors // piping an ended stream ends immediately if (ended) { if (opts.end) dest.end() } else { this[PIPES].push( !opts.proxyErrors ? new Pipe(this, dest, opts) : new PipeProxyErrors(this, dest, opts) ) if (this[ASYNC]) defer(() => this[RESUME]()) else this[RESUME]() } return dest } unpipe(dest) { const p = this[PIPES].find(p => p.dest === dest) if (p) { this[PIPES].splice(this[PIPES].indexOf(p), 1) p.unpipe() } } addListener(ev, fn) { return this.on(ev, fn) } on(ev, fn) { const ret = super.on(ev, fn) if (ev === 'data' && !this[PIPES].length && !this.flowing) this[RESUME]() else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) super.emit('readable') else if (isEndish(ev) && this[EMITTED_END]) { super.emit(ev) this.removeAllListeners(ev) } else if (ev === 'error' && this[EMITTED_ERROR]) { if (this[ASYNC]) defer(() => fn.call(this, this[EMITTED_ERROR])) else fn.call(this, this[EMITTED_ERROR]) } return ret } get emittedEnd() { return this[EMITTED_END] } [MAYBE_EMIT_END]() { if ( !this[EMITTING_END] && !this[EMITTED_END] && !this[DESTROYED] && this[BUFFER].length === 0 && this[EOF] ) { this[EMITTING_END] = true this.emit('end') this.emit('prefinish') this.emit('finish') if (this[CLOSED]) this.emit('close') this[EMITTING_END] = false } } emit(ev, data, ...extra) { // error and close are only events allowed after calling destroy() if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED]) return else if (ev === 'data') { return !this[OBJECTMODE] && !data ? false : this[ASYNC] ? defer(() => this[EMITDATA](data)) : this[EMITDATA](data) } else if (ev === 'end') { return this[EMITEND]() } else if (ev === 'close') { this[CLOSED] = true // don't emit close before 'end' and 'finish' if (!this[EMITTED_END] && !this[DESTROYED]) return const ret = super.emit('close') this.removeAllListeners('close') return ret } else if (ev === 'error') { this[EMITTED_ERROR] = data super.emit(ERROR, data) const ret = !this[SIGNAL] || this.listeners('error').length ? super.emit('error', data) : false this[MAYBE_EMIT_END]() return ret } else if (ev === 'resume') { const ret = super.emit('resume') this[MAYBE_EMIT_END]() return ret } else if (ev === 'finish' || ev === 'prefinish') { const ret = super.emit(ev) this.removeAllListeners(ev) return ret } // Some other unknown event const ret = super.emit(ev, data, ...extra) this[MAYBE_EMIT_END]() return ret } [EMITDATA](data) { for (const p of this[PIPES]) { if (p.dest.write(data) === false) this.pause() } const ret = super.emit('data', data) this[MAYBE_EMIT_END]() return ret } [EMITEND]() { if (this[EMITTED_END]) return this[EMITTED_END] = true this.readable = false if (this[ASYNC]) defer(() => this[EMITEND2]()) else this[EMITEND2]() } [EMITEND2]() { if (this[DECODER]) { const data = this[DECODER].end() if (data) { for (const p of this[PIPES]) { p.dest.write(data) } super.emit('data', data) } } for (const p of this[PIPES]) { p.end() } const ret = super.emit('end') this.removeAllListeners('end') return ret } // const all = await stream.collect() collect() { const buf = [] if (!this[OBJECTMODE]) buf.dataLength = 0 // set the promise first, in case an error is raised // by triggering the flow here. const p = this.promise() this.on('data', c => { buf.push(c) if (!this[OBJECTMODE]) buf.dataLength += c.length }) return p.then(() => buf) } // const data = await stream.concat() concat() { return this[OBJECTMODE] ? Promise.reject(new Error('cannot concat in objectMode')) : this.collect().then(buf => this[OBJECTMODE] ? Promise.reject(new Error('cannot concat in objectMode')) : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength) ) } // stream.promise().then(() => done, er => emitted error) promise() { return new Promise((resolve, reject) => { this.on(DESTROYED, () => reject(new Error('stream destroyed'))) this.on('error', er => reject(er)) this.on('end', () => resolve()) }) } // for await (let chunk of stream) [ASYNCITERATOR]() { let stopped = false const stop = () => { this.pause() stopped = true return Promise.resolve({ done: true }) } const next = () => { if (stopped) return stop() const res = this.read() if (res !== null) return Promise.resolve({ done: false, value: res }) if (this[EOF]) return stop() let resolve = null let reject = null const onerr = er => { this.removeListener('data', ondata) this.removeListener('end', onend) this.removeListener(DESTROYED, ondestroy) stop() reject(er) } const ondata = value => { this.removeListener('error', onerr) this.removeListener('end', onend) this.removeListener(DESTROYED, ondestroy) this.pause() resolve({ value: value, done: !!this[EOF] }) } const onend = () => { this.removeListener('error', onerr) this.removeListener('data', ondata) this.removeListener(DESTROYED, ondestroy) stop() resolve({ done: true }) } const ondestroy = () => onerr(new Error('stream destroyed')) return new Promise((res, rej) => { reject = rej resolve = res this.once(DESTROYED, ondestroy) this.once('error', onerr) this.once('end', onend) this.once('data', ondata) }) } return { next, throw: stop, return: stop, [ASYNCITERATOR]() { return this }, } } // for (let chunk of stream) [ITERATOR]() { let stopped = false const stop = () => { this.pause() this.removeListener(ERROR, stop) this.removeListener(DESTROYED, stop) this.removeListener('end', stop) stopped = true return { done: true } } const next = () => { if (stopped) return stop() const value = this.read() return value === null ? stop() : { value } } this.once('end', stop) this.once(ERROR, stop) this.once(DESTROYED, stop) return { next, throw: stop, return: stop, [ITERATOR]() { return this }, } } destroy(er) { if (this[DESTROYED]) { if (er) this.emit('error', er) else this.emit(DESTROYED) return this } this[DESTROYED] = true // throw away all buffered data, it's never coming out this[BUFFER].length = 0 this[BUFFERLENGTH] = 0 if (typeof this.close === 'function' && !this[CLOSED]) this.close() if (er) this.emit('error', er) // if no error to emit, still reject pending promises else this.emit(DESTROYED) return this } static isStream(s) { return ( !!s && (s instanceof Minipass || s instanceof Stream || (s instanceof EE && // readable (typeof s.pipe === 'function' || // writable (typeof s.write === 'function' && typeof s.end === 'function')))) ) } } exports.Minipass = Minipass PK ~\ BTHTH#tar/node_modules/minipass/index.mjsnu['use strict' const proc = typeof process === 'object' && process ? process : { stdout: null, stderr: null, } import EE from 'events' import Stream from 'stream' import stringdecoder from 'string_decoder' const SD = stringdecoder.StringDecoder const EOF = Symbol('EOF') const MAYBE_EMIT_END = Symbol('maybeEmitEnd') const EMITTED_END = Symbol('emittedEnd') const EMITTING_END = Symbol('emittingEnd') const EMITTED_ERROR = Symbol('emittedError') const CLOSED = Symbol('closed') const READ = Symbol('read') const FLUSH = Symbol('flush') const FLUSHCHUNK = Symbol('flushChunk') const ENCODING = Symbol('encoding') const DECODER = Symbol('decoder') const FLOWING = Symbol('flowing') const PAUSED = Symbol('paused') const RESUME = Symbol('resume') const BUFFER = Symbol('buffer') const PIPES = Symbol('pipes') const BUFFERLENGTH = Symbol('bufferLength') const BUFFERPUSH = Symbol('bufferPush') const BUFFERSHIFT = Symbol('bufferShift') const OBJECTMODE = Symbol('objectMode') // internal event when stream is destroyed const DESTROYED = Symbol('destroyed') // internal event when stream has an error const ERROR = Symbol('error') const EMITDATA = Symbol('emitData') const EMITEND = Symbol('emitEnd') const EMITEND2 = Symbol('emitEnd2') const ASYNC = Symbol('async') const ABORT = Symbol('abort') const ABORTED = Symbol('aborted') const SIGNAL = Symbol('signal') const defer = fn => Promise.resolve().then(fn) // TODO remove when Node v8 support drops const doIter = global._MP_NO_ITERATOR_SYMBOLS_ !== '1' const ASYNCITERATOR = (doIter && Symbol.asyncIterator) || Symbol('asyncIterator not implemented') const ITERATOR = (doIter && Symbol.iterator) || Symbol('iterator not implemented') // events that mean 'the stream is over' // these are treated specially, and re-emitted // if they are listened for after emitting. const isEndish = ev => ev === 'end' || ev === 'finish' || ev === 'prefinish' const isArrayBuffer = b => b instanceof ArrayBuffer || (typeof b === 'object' && b.constructor && b.constructor.name === 'ArrayBuffer' && b.byteLength >= 0) const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b) class Pipe { constructor(src, dest, opts) { this.src = src this.dest = dest this.opts = opts this.ondrain = () => src[RESUME]() dest.on('drain', this.ondrain) } unpipe() { this.dest.removeListener('drain', this.ondrain) } // istanbul ignore next - only here for the prototype proxyErrors() {} end() { this.unpipe() if (this.opts.end) this.dest.end() } } class PipeProxyErrors extends Pipe { unpipe() { this.src.removeListener('error', this.proxyErrors) super.unpipe() } constructor(src, dest, opts) { super(src, dest, opts) this.proxyErrors = er => dest.emit('error', er) src.on('error', this.proxyErrors) } } export class Minipass extends Stream { constructor(options) { super() this[FLOWING] = false // whether we're explicitly paused this[PAUSED] = false this[PIPES] = [] this[BUFFER] = [] this[OBJECTMODE] = (options && options.objectMode) || false if (this[OBJECTMODE]) this[ENCODING] = null else this[ENCODING] = (options && options.encoding) || null if (this[ENCODING] === 'buffer') this[ENCODING] = null this[ASYNC] = (options && !!options.async) || false this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null this[EOF] = false this[EMITTED_END] = false this[EMITTING_END] = false this[CLOSED] = false this[EMITTED_ERROR] = null this.writable = true this.readable = true this[BUFFERLENGTH] = 0 this[DESTROYED] = false if (options && options.debugExposeBuffer === true) { Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] }) } if (options && options.debugExposePipes === true) { Object.defineProperty(this, 'pipes', { get: () => this[PIPES] }) } this[SIGNAL] = options && options.signal this[ABORTED] = false if (this[SIGNAL]) { this[SIGNAL].addEventListener('abort', () => this[ABORT]()) if (this[SIGNAL].aborted) { this[ABORT]() } } } get bufferLength() { return this[BUFFERLENGTH] } get encoding() { return this[ENCODING] } set encoding(enc) { if (this[OBJECTMODE]) throw new Error('cannot set encoding in objectMode') if ( this[ENCODING] && enc !== this[ENCODING] && ((this[DECODER] && this[DECODER].lastNeed) || this[BUFFERLENGTH]) ) throw new Error('cannot change encoding') if (this[ENCODING] !== enc) { this[DECODER] = enc ? new SD(enc) : null if (this[BUFFER].length) this[BUFFER] = this[BUFFER].map(chunk => this[DECODER].write(chunk)) } this[ENCODING] = enc } setEncoding(enc) { this.encoding = enc } get objectMode() { return this[OBJECTMODE] } set objectMode(om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om } get ['async']() { return this[ASYNC] } set ['async'](a) { this[ASYNC] = this[ASYNC] || !!a } // drop everything and get out of the flow completely [ABORT]() { this[ABORTED] = true this.emit('abort', this[SIGNAL].reason) this.destroy(this[SIGNAL].reason) } get aborted() { return this[ABORTED] } set aborted(_) {} write(chunk, encoding, cb) { if (this[ABORTED]) return false if (this[EOF]) throw new Error('write after end') if (this[DESTROYED]) { this.emit( 'error', Object.assign( new Error('Cannot call write after a stream was destroyed'), { code: 'ERR_STREAM_DESTROYED' } ) ) return true } if (typeof encoding === 'function') (cb = encoding), (encoding = 'utf8') if (!encoding) encoding = 'utf8' const fn = this[ASYNC] ? defer : f => f() // convert array buffers and typed array views into buffers // at some point in the future, we may want to do the opposite! // leave strings and buffers as-is // anything else switches us into object mode if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { if (isArrayBufferView(chunk)) chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) else if (isArrayBuffer(chunk)) chunk = Buffer.from(chunk) else if (typeof chunk !== 'string') // use the setter so we throw if we have encoding set this.objectMode = true } // handle object mode up front, since it's simpler // this yields better performance, fewer checks later. if (this[OBJECTMODE]) { /* istanbul ignore if - maybe impossible? */ if (this.flowing && this[BUFFERLENGTH] !== 0) this[FLUSH](true) if (this.flowing) this.emit('data', chunk) else this[BUFFERPUSH](chunk) if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } // at this point the chunk is a buffer or string // don't buffer it up or send it to the decoder if (!chunk.length) { if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } // fast-path writing strings of same encoding to a stream with // an empty buffer, skipping the buffer/decoder dance if ( typeof chunk === 'string' && // unless it is a string already ready for us to use !(encoding === this[ENCODING] && !this[DECODER].lastNeed) ) { chunk = Buffer.from(chunk, encoding) } if (Buffer.isBuffer(chunk) && this[ENCODING]) chunk = this[DECODER].write(chunk) // Note: flushing CAN potentially switch us into not-flowing mode if (this.flowing && this[BUFFERLENGTH] !== 0) this[FLUSH](true) if (this.flowing) this.emit('data', chunk) else this[BUFFERPUSH](chunk) if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } read(n) { if (this[DESTROYED]) return null if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) { this[MAYBE_EMIT_END]() return null } if (this[OBJECTMODE]) n = null if (this[BUFFER].length > 1 && !this[OBJECTMODE]) { if (this.encoding) this[BUFFER] = [this[BUFFER].join('')] else this[BUFFER] = [Buffer.concat(this[BUFFER], this[BUFFERLENGTH])] } const ret = this[READ](n || null, this[BUFFER][0]) this[MAYBE_EMIT_END]() return ret } [READ](n, chunk) { if (n === chunk.length || n === null) this[BUFFERSHIFT]() else { this[BUFFER][0] = chunk.slice(n) chunk = chunk.slice(0, n) this[BUFFERLENGTH] -= n } this.emit('data', chunk) if (!this[BUFFER].length && !this[EOF]) this.emit('drain') return chunk } end(chunk, encoding, cb) { if (typeof chunk === 'function') (cb = chunk), (chunk = null) if (typeof encoding === 'function') (cb = encoding), (encoding = 'utf8') if (chunk) this.write(chunk, encoding) if (cb) this.once('end', cb) this[EOF] = true this.writable = false // if we haven't written anything, then go ahead and emit, // even if we're not reading. // we'll re-emit if a new 'end' listener is added anyway. // This makes MP more suitable to write-only use cases. if (this.flowing || !this[PAUSED]) this[MAYBE_EMIT_END]() return this } // don't let the internal resume be overwritten [RESUME]() { if (this[DESTROYED]) return this[PAUSED] = false this[FLOWING] = true this.emit('resume') if (this[BUFFER].length) this[FLUSH]() else if (this[EOF]) this[MAYBE_EMIT_END]() else this.emit('drain') } resume() { return this[RESUME]() } pause() { this[FLOWING] = false this[PAUSED] = true } get destroyed() { return this[DESTROYED] } get flowing() { return this[FLOWING] } get paused() { return this[PAUSED] } [BUFFERPUSH](chunk) { if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1 else this[BUFFERLENGTH] += chunk.length this[BUFFER].push(chunk) } [BUFFERSHIFT]() { if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1 else this[BUFFERLENGTH] -= this[BUFFER][0].length return this[BUFFER].shift() } [FLUSH](noDrain) { do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]()) && this[BUFFER].length) if (!noDrain && !this[BUFFER].length && !this[EOF]) this.emit('drain') } [FLUSHCHUNK](chunk) { this.emit('data', chunk) return this.flowing } pipe(dest, opts) { if (this[DESTROYED]) return const ended = this[EMITTED_END] opts = opts || {} if (dest === proc.stdout || dest === proc.stderr) opts.end = false else opts.end = opts.end !== false opts.proxyErrors = !!opts.proxyErrors // piping an ended stream ends immediately if (ended) { if (opts.end) dest.end() } else { this[PIPES].push( !opts.proxyErrors ? new Pipe(this, dest, opts) : new PipeProxyErrors(this, dest, opts) ) if (this[ASYNC]) defer(() => this[RESUME]()) else this[RESUME]() } return dest } unpipe(dest) { const p = this[PIPES].find(p => p.dest === dest) if (p) { this[PIPES].splice(this[PIPES].indexOf(p), 1) p.unpipe() } } addListener(ev, fn) { return this.on(ev, fn) } on(ev, fn) { const ret = super.on(ev, fn) if (ev === 'data' && !this[PIPES].length && !this.flowing) this[RESUME]() else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) super.emit('readable') else if (isEndish(ev) && this[EMITTED_END]) { super.emit(ev) this.removeAllListeners(ev) } else if (ev === 'error' && this[EMITTED_ERROR]) { if (this[ASYNC]) defer(() => fn.call(this, this[EMITTED_ERROR])) else fn.call(this, this[EMITTED_ERROR]) } return ret } get emittedEnd() { return this[EMITTED_END] } [MAYBE_EMIT_END]() { if ( !this[EMITTING_END] && !this[EMITTED_END] && !this[DESTROYED] && this[BUFFER].length === 0 && this[EOF] ) { this[EMITTING_END] = true this.emit('end') this.emit('prefinish') this.emit('finish') if (this[CLOSED]) this.emit('close') this[EMITTING_END] = false } } emit(ev, data, ...extra) { // error and close are only events allowed after calling destroy() if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED]) return else if (ev === 'data') { return !this[OBJECTMODE] && !data ? false : this[ASYNC] ? defer(() => this[EMITDATA](data)) : this[EMITDATA](data) } else if (ev === 'end') { return this[EMITEND]() } else if (ev === 'close') { this[CLOSED] = true // don't emit close before 'end' and 'finish' if (!this[EMITTED_END] && !this[DESTROYED]) return const ret = super.emit('close') this.removeAllListeners('close') return ret } else if (ev === 'error') { this[EMITTED_ERROR] = data super.emit(ERROR, data) const ret = !this[SIGNAL] || this.listeners('error').length ? super.emit('error', data) : false this[MAYBE_EMIT_END]() return ret } else if (ev === 'resume') { const ret = super.emit('resume') this[MAYBE_EMIT_END]() return ret } else if (ev === 'finish' || ev === 'prefinish') { const ret = super.emit(ev) this.removeAllListeners(ev) return ret } // Some other unknown event const ret = super.emit(ev, data, ...extra) this[MAYBE_EMIT_END]() return ret } [EMITDATA](data) { for (const p of this[PIPES]) { if (p.dest.write(data) === false) this.pause() } const ret = super.emit('data', data) this[MAYBE_EMIT_END]() return ret } [EMITEND]() { if (this[EMITTED_END]) return this[EMITTED_END] = true this.readable = false if (this[ASYNC]) defer(() => this[EMITEND2]()) else this[EMITEND2]() } [EMITEND2]() { if (this[DECODER]) { const data = this[DECODER].end() if (data) { for (const p of this[PIPES]) { p.dest.write(data) } super.emit('data', data) } } for (const p of this[PIPES]) { p.end() } const ret = super.emit('end') this.removeAllListeners('end') return ret } // const all = await stream.collect() collect() { const buf = [] if (!this[OBJECTMODE]) buf.dataLength = 0 // set the promise first, in case an error is raised // by triggering the flow here. const p = this.promise() this.on('data', c => { buf.push(c) if (!this[OBJECTMODE]) buf.dataLength += c.length }) return p.then(() => buf) } // const data = await stream.concat() concat() { return this[OBJECTMODE] ? Promise.reject(new Error('cannot concat in objectMode')) : this.collect().then(buf => this[OBJECTMODE] ? Promise.reject(new Error('cannot concat in objectMode')) : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength) ) } // stream.promise().then(() => done, er => emitted error) promise() { return new Promise((resolve, reject) => { this.on(DESTROYED, () => reject(new Error('stream destroyed'))) this.on('error', er => reject(er)) this.on('end', () => resolve()) }) } // for await (let chunk of stream) [ASYNCITERATOR]() { let stopped = false const stop = () => { this.pause() stopped = true return Promise.resolve({ done: true }) } const next = () => { if (stopped) return stop() const res = this.read() if (res !== null) return Promise.resolve({ done: false, value: res }) if (this[EOF]) return stop() let resolve = null let reject = null const onerr = er => { this.removeListener('data', ondata) this.removeListener('end', onend) this.removeListener(DESTROYED, ondestroy) stop() reject(er) } const ondata = value => { this.removeListener('error', onerr) this.removeListener('end', onend) this.removeListener(DESTROYED, ondestroy) this.pause() resolve({ value: value, done: !!this[EOF] }) } const onend = () => { this.removeListener('error', onerr) this.removeListener('data', ondata) this.removeListener(DESTROYED, ondestroy) stop() resolve({ done: true }) } const ondestroy = () => onerr(new Error('stream destroyed')) return new Promise((res, rej) => { reject = rej resolve = res this.once(DESTROYED, ondestroy) this.once('error', onerr) this.once('end', onend) this.once('data', ondata) }) } return { next, throw: stop, return: stop, [ASYNCITERATOR]() { return this }, } } // for (let chunk of stream) [ITERATOR]() { let stopped = false const stop = () => { this.pause() this.removeListener(ERROR, stop) this.removeListener(DESTROYED, stop) this.removeListener('end', stop) stopped = true return { done: true } } const next = () => { if (stopped) return stop() const value = this.read() return value === null ? stop() : { value } } this.once('end', stop) this.once(ERROR, stop) this.once(DESTROYED, stop) return { next, throw: stop, return: stop, [ITERATOR]() { return this }, } } destroy(er) { if (this[DESTROYED]) { if (er) this.emit('error', er) else this.emit(DESTROYED) return this } this[DESTROYED] = true // throw away all buffered data, it's never coming out this[BUFFER].length = 0 this[BUFFERLENGTH] = 0 if (typeof this.close === 'function' && !this[CLOSED]) this.close() if (er) this.emit('error', er) // if no error to emit, still reject pending promises else this.emit(DESTROYED) return this } static isStream(s) { return ( !!s && (s instanceof Minipass || s instanceof Stream || (s instanceof EE && // readable (typeof s.pipe === 'function' || // writable (typeof s.write === 'function' && typeof s.end === 'function')))) ) } } PK ~\APBB)tar/node_modules/fs-minipass/package.jsonnu[{ "_id": "fs-minipass@2.1.0", "_inBundle": true, "_location": "/npm/tar/fs-minipass", "_phantomChildren": { "yallist": "4.0.0" }, "_requiredBy": [ "/npm/tar" ], "author": { "name": "Isaac Z. Schlueter", "email": "i@izs.me", "url": "http://blog.izs.me/" }, "bugs": { "url": "https://github.com/npm/fs-minipass/issues" }, "dependencies": { "minipass": "^3.0.0" }, "description": "fs read and write streams based on minipass", "devDependencies": { "mutate-fs": "^2.0.1", "tap": "^14.6.4" }, "engines": { "node": ">= 8" }, "files": [ "index.js" ], "homepage": "https://github.com/npm/fs-minipass#readme", "keywords": [], "license": "ISC", "main": "index.js", "name": "fs-minipass", "repository": { "type": "git", "url": "git+https://github.com/npm/fs-minipass.git" }, "scripts": { "postpublish": "git push origin --follow-tags", "postversion": "npm publish", "preversion": "npm test", "test": "tap" }, "tap": { "check-coverage": true }, "version": "2.1.0" } PK ~\|i?tar/node_modules/fs-minipass/node_modules/minipass/package.jsonnu[{ "_id": "minipass@3.3.6", "_inBundle": true, "_location": "/npm/tar/fs-minipass/minipass", "_phantomChildren": {}, "_requiredBy": [ "/npm/tar/fs-minipass" ], "author": { "name": "Isaac Z. Schlueter", "email": "i@izs.me", "url": "http://blog.izs.me/" }, "bugs": { "url": "https://github.com/isaacs/minipass/issues" }, "dependencies": { "yallist": "^4.0.0" }, "description": "minimal implementation of a PassThrough stream", "devDependencies": { "@types/node": "^17.0.41", "end-of-stream": "^1.4.0", "prettier": "^2.6.2", "tap": "^16.2.0", "through2": "^2.0.3", "ts-node": "^10.8.1", "typescript": "^4.7.3" }, "engines": { "node": ">=8" }, "files": [ "index.d.ts", "index.js" ], "homepage": "https://github.com/isaacs/minipass#readme", "keywords": [ "passthrough", "stream" ], "license": "ISC", "main": "index.js", "name": "minipass", "prettier": { "semi": false, "printWidth": 80, "tabWidth": 2, "useTabs": false, "singleQuote": true, "jsxSingleQuote": false, "bracketSameLine": true, "arrowParens": "avoid", "endOfLine": "lf" }, "repository": { "type": "git", "url": "git+https://github.com/isaacs/minipass.git" }, "scripts": { "postpublish": "git push origin --follow-tags", "postversion": "npm publish", "preversion": "npm test", "test": "tap" }, "tap": { "check-coverage": true }, "types": "index.d.ts", "version": "3.3.6" } PK ~\:tar/node_modules/fs-minipass/node_modules/minipass/LICENSEnu[The ISC License Copyright (c) 2017-2022 npm, Inc., Isaac Z. Schlueter, and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\-@@;tar/node_modules/fs-minipass/node_modules/minipass/index.jsnu['use strict' const proc = typeof process === 'object' && process ? process : { stdout: null, stderr: null, } const EE = require('events') const Stream = require('stream') const SD = require('string_decoder').StringDecoder const EOF = Symbol('EOF') const MAYBE_EMIT_END = Symbol('maybeEmitEnd') const EMITTED_END = Symbol('emittedEnd') const EMITTING_END = Symbol('emittingEnd') const EMITTED_ERROR = Symbol('emittedError') const CLOSED = Symbol('closed') const READ = Symbol('read') const FLUSH = Symbol('flush') const FLUSHCHUNK = Symbol('flushChunk') const ENCODING = Symbol('encoding') const DECODER = Symbol('decoder') const FLOWING = Symbol('flowing') const PAUSED = Symbol('paused') const RESUME = Symbol('resume') const BUFFERLENGTH = Symbol('bufferLength') const BUFFERPUSH = Symbol('bufferPush') const BUFFERSHIFT = Symbol('bufferShift') const OBJECTMODE = Symbol('objectMode') const DESTROYED = Symbol('destroyed') const EMITDATA = Symbol('emitData') const EMITEND = Symbol('emitEnd') const EMITEND2 = Symbol('emitEnd2') const ASYNC = Symbol('async') const defer = fn => Promise.resolve().then(fn) // TODO remove when Node v8 support drops const doIter = global._MP_NO_ITERATOR_SYMBOLS_ !== '1' const ASYNCITERATOR = doIter && Symbol.asyncIterator || Symbol('asyncIterator not implemented') const ITERATOR = doIter && Symbol.iterator || Symbol('iterator not implemented') // events that mean 'the stream is over' // these are treated specially, and re-emitted // if they are listened for after emitting. const isEndish = ev => ev === 'end' || ev === 'finish' || ev === 'prefinish' const isArrayBuffer = b => b instanceof ArrayBuffer || typeof b === 'object' && b.constructor && b.constructor.name === 'ArrayBuffer' && b.byteLength >= 0 const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b) class Pipe { constructor (src, dest, opts) { this.src = src this.dest = dest this.opts = opts this.ondrain = () => src[RESUME]() dest.on('drain', this.ondrain) } unpipe () { this.dest.removeListener('drain', this.ondrain) } // istanbul ignore next - only here for the prototype proxyErrors () {} end () { this.unpipe() if (this.opts.end) this.dest.end() } } class PipeProxyErrors extends Pipe { unpipe () { this.src.removeListener('error', this.proxyErrors) super.unpipe() } constructor (src, dest, opts) { super(src, dest, opts) this.proxyErrors = er => dest.emit('error', er) src.on('error', this.proxyErrors) } } module.exports = class Minipass extends Stream { constructor (options) { super() this[FLOWING] = false // whether we're explicitly paused this[PAUSED] = false this.pipes = [] this.buffer = [] this[OBJECTMODE] = options && options.objectMode || false if (this[OBJECTMODE]) this[ENCODING] = null else this[ENCODING] = options && options.encoding || null if (this[ENCODING] === 'buffer') this[ENCODING] = null this[ASYNC] = options && !!options.async || false this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null this[EOF] = false this[EMITTED_END] = false this[EMITTING_END] = false this[CLOSED] = false this[EMITTED_ERROR] = null this.writable = true this.readable = true this[BUFFERLENGTH] = 0 this[DESTROYED] = false } get bufferLength () { return this[BUFFERLENGTH] } get encoding () { return this[ENCODING] } set encoding (enc) { if (this[OBJECTMODE]) throw new Error('cannot set encoding in objectMode') if (this[ENCODING] && enc !== this[ENCODING] && (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH])) throw new Error('cannot change encoding') if (this[ENCODING] !== enc) { this[DECODER] = enc ? new SD(enc) : null if (this.buffer.length) this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk)) } this[ENCODING] = enc } setEncoding (enc) { this.encoding = enc } get objectMode () { return this[OBJECTMODE] } set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om } get ['async'] () { return this[ASYNC] } set ['async'] (a) { this[ASYNC] = this[ASYNC] || !!a } write (chunk, encoding, cb) { if (this[EOF]) throw new Error('write after end') if (this[DESTROYED]) { this.emit('error', Object.assign( new Error('Cannot call write after a stream was destroyed'), { code: 'ERR_STREAM_DESTROYED' } )) return true } if (typeof encoding === 'function') cb = encoding, encoding = 'utf8' if (!encoding) encoding = 'utf8' const fn = this[ASYNC] ? defer : f => f() // convert array buffers and typed array views into buffers // at some point in the future, we may want to do the opposite! // leave strings and buffers as-is // anything else switches us into object mode if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { if (isArrayBufferView(chunk)) chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) else if (isArrayBuffer(chunk)) chunk = Buffer.from(chunk) else if (typeof chunk !== 'string') // use the setter so we throw if we have encoding set this.objectMode = true } // handle object mode up front, since it's simpler // this yields better performance, fewer checks later. if (this[OBJECTMODE]) { /* istanbul ignore if - maybe impossible? */ if (this.flowing && this[BUFFERLENGTH] !== 0) this[FLUSH](true) if (this.flowing) this.emit('data', chunk) else this[BUFFERPUSH](chunk) if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } // at this point the chunk is a buffer or string // don't buffer it up or send it to the decoder if (!chunk.length) { if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } // fast-path writing strings of same encoding to a stream with // an empty buffer, skipping the buffer/decoder dance if (typeof chunk === 'string' && // unless it is a string already ready for us to use !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) { chunk = Buffer.from(chunk, encoding) } if (Buffer.isBuffer(chunk) && this[ENCODING]) chunk = this[DECODER].write(chunk) // Note: flushing CAN potentially switch us into not-flowing mode if (this.flowing && this[BUFFERLENGTH] !== 0) this[FLUSH](true) if (this.flowing) this.emit('data', chunk) else this[BUFFERPUSH](chunk) if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } read (n) { if (this[DESTROYED]) return null if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) { this[MAYBE_EMIT_END]() return null } if (this[OBJECTMODE]) n = null if (this.buffer.length > 1 && !this[OBJECTMODE]) { if (this.encoding) this.buffer = [this.buffer.join('')] else this.buffer = [Buffer.concat(this.buffer, this[BUFFERLENGTH])] } const ret = this[READ](n || null, this.buffer[0]) this[MAYBE_EMIT_END]() return ret } [READ] (n, chunk) { if (n === chunk.length || n === null) this[BUFFERSHIFT]() else { this.buffer[0] = chunk.slice(n) chunk = chunk.slice(0, n) this[BUFFERLENGTH] -= n } this.emit('data', chunk) if (!this.buffer.length && !this[EOF]) this.emit('drain') return chunk } end (chunk, encoding, cb) { if (typeof chunk === 'function') cb = chunk, chunk = null if (typeof encoding === 'function') cb = encoding, encoding = 'utf8' if (chunk) this.write(chunk, encoding) if (cb) this.once('end', cb) this[EOF] = true this.writable = false // if we haven't written anything, then go ahead and emit, // even if we're not reading. // we'll re-emit if a new 'end' listener is added anyway. // This makes MP more suitable to write-only use cases. if (this.flowing || !this[PAUSED]) this[MAYBE_EMIT_END]() return this } // don't let the internal resume be overwritten [RESUME] () { if (this[DESTROYED]) return this[PAUSED] = false this[FLOWING] = true this.emit('resume') if (this.buffer.length) this[FLUSH]() else if (this[EOF]) this[MAYBE_EMIT_END]() else this.emit('drain') } resume () { return this[RESUME]() } pause () { this[FLOWING] = false this[PAUSED] = true } get destroyed () { return this[DESTROYED] } get flowing () { return this[FLOWING] } get paused () { return this[PAUSED] } [BUFFERPUSH] (chunk) { if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1 else this[BUFFERLENGTH] += chunk.length this.buffer.push(chunk) } [BUFFERSHIFT] () { if (this.buffer.length) { if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1 else this[BUFFERLENGTH] -= this.buffer[0].length } return this.buffer.shift() } [FLUSH] (noDrain) { do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]())) if (!noDrain && !this.buffer.length && !this[EOF]) this.emit('drain') } [FLUSHCHUNK] (chunk) { return chunk ? (this.emit('data', chunk), this.flowing) : false } pipe (dest, opts) { if (this[DESTROYED]) return const ended = this[EMITTED_END] opts = opts || {} if (dest === proc.stdout || dest === proc.stderr) opts.end = false else opts.end = opts.end !== false opts.proxyErrors = !!opts.proxyErrors // piping an ended stream ends immediately if (ended) { if (opts.end) dest.end() } else { this.pipes.push(!opts.proxyErrors ? new Pipe(this, dest, opts) : new PipeProxyErrors(this, dest, opts)) if (this[ASYNC]) defer(() => this[RESUME]()) else this[RESUME]() } return dest } unpipe (dest) { const p = this.pipes.find(p => p.dest === dest) if (p) { this.pipes.splice(this.pipes.indexOf(p), 1) p.unpipe() } } addListener (ev, fn) { return this.on(ev, fn) } on (ev, fn) { const ret = super.on(ev, fn) if (ev === 'data' && !this.pipes.length && !this.flowing) this[RESUME]() else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) super.emit('readable') else if (isEndish(ev) && this[EMITTED_END]) { super.emit(ev) this.removeAllListeners(ev) } else if (ev === 'error' && this[EMITTED_ERROR]) { if (this[ASYNC]) defer(() => fn.call(this, this[EMITTED_ERROR])) else fn.call(this, this[EMITTED_ERROR]) } return ret } get emittedEnd () { return this[EMITTED_END] } [MAYBE_EMIT_END] () { if (!this[EMITTING_END] && !this[EMITTED_END] && !this[DESTROYED] && this.buffer.length === 0 && this[EOF]) { this[EMITTING_END] = true this.emit('end') this.emit('prefinish') this.emit('finish') if (this[CLOSED]) this.emit('close') this[EMITTING_END] = false } } emit (ev, data, ...extra) { // error and close are only events allowed after calling destroy() if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED]) return else if (ev === 'data') { return !data ? false : this[ASYNC] ? defer(() => this[EMITDATA](data)) : this[EMITDATA](data) } else if (ev === 'end') { return this[EMITEND]() } else if (ev === 'close') { this[CLOSED] = true // don't emit close before 'end' and 'finish' if (!this[EMITTED_END] && !this[DESTROYED]) return const ret = super.emit('close') this.removeAllListeners('close') return ret } else if (ev === 'error') { this[EMITTED_ERROR] = data const ret = super.emit('error', data) this[MAYBE_EMIT_END]() return ret } else if (ev === 'resume') { const ret = super.emit('resume') this[MAYBE_EMIT_END]() return ret } else if (ev === 'finish' || ev === 'prefinish') { const ret = super.emit(ev) this.removeAllListeners(ev) return ret } // Some other unknown event const ret = super.emit(ev, data, ...extra) this[MAYBE_EMIT_END]() return ret } [EMITDATA] (data) { for (const p of this.pipes) { if (p.dest.write(data) === false) this.pause() } const ret = super.emit('data', data) this[MAYBE_EMIT_END]() return ret } [EMITEND] () { if (this[EMITTED_END]) return this[EMITTED_END] = true this.readable = false if (this[ASYNC]) defer(() => this[EMITEND2]()) else this[EMITEND2]() } [EMITEND2] () { if (this[DECODER]) { const data = this[DECODER].end() if (data) { for (const p of this.pipes) { p.dest.write(data) } super.emit('data', data) } } for (const p of this.pipes) { p.end() } const ret = super.emit('end') this.removeAllListeners('end') return ret } // const all = await stream.collect() collect () { const buf = [] if (!this[OBJECTMODE]) buf.dataLength = 0 // set the promise first, in case an error is raised // by triggering the flow here. const p = this.promise() this.on('data', c => { buf.push(c) if (!this[OBJECTMODE]) buf.dataLength += c.length }) return p.then(() => buf) } // const data = await stream.concat() concat () { return this[OBJECTMODE] ? Promise.reject(new Error('cannot concat in objectMode')) : this.collect().then(buf => this[OBJECTMODE] ? Promise.reject(new Error('cannot concat in objectMode')) : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength)) } // stream.promise().then(() => done, er => emitted error) promise () { return new Promise((resolve, reject) => { this.on(DESTROYED, () => reject(new Error('stream destroyed'))) this.on('error', er => reject(er)) this.on('end', () => resolve()) }) } // for await (let chunk of stream) [ASYNCITERATOR] () { const next = () => { const res = this.read() if (res !== null) return Promise.resolve({ done: false, value: res }) if (this[EOF]) return Promise.resolve({ done: true }) let resolve = null let reject = null const onerr = er => { this.removeListener('data', ondata) this.removeListener('end', onend) reject(er) } const ondata = value => { this.removeListener('error', onerr) this.removeListener('end', onend) this.pause() resolve({ value: value, done: !!this[EOF] }) } const onend = () => { this.removeListener('error', onerr) this.removeListener('data', ondata) resolve({ done: true }) } const ondestroy = () => onerr(new Error('stream destroyed')) return new Promise((res, rej) => { reject = rej resolve = res this.once(DESTROYED, ondestroy) this.once('error', onerr) this.once('end', onend) this.once('data', ondata) }) } return { next } } // for (let chunk of stream) [ITERATOR] () { const next = () => { const value = this.read() const done = value === null return { value, done } } return { next } } destroy (er) { if (this[DESTROYED]) { if (er) this.emit('error', er) else this.emit(DESTROYED) return this } this[DESTROYED] = true // throw away all buffered data, it's never coming out this.buffer.length = 0 this[BUFFERLENGTH] = 0 if (typeof this.close === 'function' && !this[CLOSED]) this.close() if (er) this.emit('error', er) else // if no error to emit, still reject pending promises this.emit(DESTROYED) return this } static isStream (s) { return !!s && (s instanceof Minipass || s instanceof Stream || s instanceof EE && ( typeof s.pipe === 'function' || // readable (typeof s.write === 'function' && typeof s.end === 'function') // writable )) } } PK ~\aGW$tar/node_modules/fs-minipass/LICENSEnu[The ISC License Copyright (c) Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\t3''%tar/node_modules/fs-minipass/index.jsnu['use strict' const MiniPass = require('minipass') const EE = require('events').EventEmitter const fs = require('fs') let writev = fs.writev /* istanbul ignore next */ if (!writev) { // This entire block can be removed if support for earlier than Node.js // 12.9.0 is not needed. const binding = process.binding('fs') const FSReqWrap = binding.FSReqWrap || binding.FSReqCallback writev = (fd, iovec, pos, cb) => { const done = (er, bw) => cb(er, bw, iovec) const req = new FSReqWrap() req.oncomplete = done binding.writeBuffers(fd, iovec, pos, req) } } const _autoClose = Symbol('_autoClose') const _close = Symbol('_close') const _ended = Symbol('_ended') const _fd = Symbol('_fd') const _finished = Symbol('_finished') const _flags = Symbol('_flags') const _flush = Symbol('_flush') const _handleChunk = Symbol('_handleChunk') const _makeBuf = Symbol('_makeBuf') const _mode = Symbol('_mode') const _needDrain = Symbol('_needDrain') const _onerror = Symbol('_onerror') const _onopen = Symbol('_onopen') const _onread = Symbol('_onread') const _onwrite = Symbol('_onwrite') const _open = Symbol('_open') const _path = Symbol('_path') const _pos = Symbol('_pos') const _queue = Symbol('_queue') const _read = Symbol('_read') const _readSize = Symbol('_readSize') const _reading = Symbol('_reading') const _remain = Symbol('_remain') const _size = Symbol('_size') const _write = Symbol('_write') const _writing = Symbol('_writing') const _defaultFlag = Symbol('_defaultFlag') const _errored = Symbol('_errored') class ReadStream extends MiniPass { constructor (path, opt) { opt = opt || {} super(opt) this.readable = true this.writable = false if (typeof path !== 'string') throw new TypeError('path must be a string') this[_errored] = false this[_fd] = typeof opt.fd === 'number' ? opt.fd : null this[_path] = path this[_readSize] = opt.readSize || 16*1024*1024 this[_reading] = false this[_size] = typeof opt.size === 'number' ? opt.size : Infinity this[_remain] = this[_size] this[_autoClose] = typeof opt.autoClose === 'boolean' ? opt.autoClose : true if (typeof this[_fd] === 'number') this[_read]() else this[_open]() } get fd () { return this[_fd] } get path () { return this[_path] } write () { throw new TypeError('this is a readable stream') } end () { throw new TypeError('this is a readable stream') } [_open] () { fs.open(this[_path], 'r', (er, fd) => this[_onopen](er, fd)) } [_onopen] (er, fd) { if (er) this[_onerror](er) else { this[_fd] = fd this.emit('open', fd) this[_read]() } } [_makeBuf] () { return Buffer.allocUnsafe(Math.min(this[_readSize], this[_remain])) } [_read] () { if (!this[_reading]) { this[_reading] = true const buf = this[_makeBuf]() /* istanbul ignore if */ if (buf.length === 0) return process.nextTick(() => this[_onread](null, 0, buf)) fs.read(this[_fd], buf, 0, buf.length, null, (er, br, buf) => this[_onread](er, br, buf)) } } [_onread] (er, br, buf) { this[_reading] = false if (er) this[_onerror](er) else if (this[_handleChunk](br, buf)) this[_read]() } [_close] () { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd] this[_fd] = null fs.close(fd, er => er ? this.emit('error', er) : this.emit('close')) } } [_onerror] (er) { this[_reading] = true this[_close]() this.emit('error', er) } [_handleChunk] (br, buf) { let ret = false // no effect if infinite this[_remain] -= br if (br > 0) ret = super.write(br < buf.length ? buf.slice(0, br) : buf) if (br === 0 || this[_remain] <= 0) { ret = false this[_close]() super.end() } return ret } emit (ev, data) { switch (ev) { case 'prefinish': case 'finish': break case 'drain': if (typeof this[_fd] === 'number') this[_read]() break case 'error': if (this[_errored]) return this[_errored] = true return super.emit(ev, data) default: return super.emit(ev, data) } } } class ReadStreamSync extends ReadStream { [_open] () { let threw = true try { this[_onopen](null, fs.openSync(this[_path], 'r')) threw = false } finally { if (threw) this[_close]() } } [_read] () { let threw = true try { if (!this[_reading]) { this[_reading] = true do { const buf = this[_makeBuf]() /* istanbul ignore next */ const br = buf.length === 0 ? 0 : fs.readSync(this[_fd], buf, 0, buf.length, null) if (!this[_handleChunk](br, buf)) break } while (true) this[_reading] = false } threw = false } finally { if (threw) this[_close]() } } [_close] () { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd] this[_fd] = null fs.closeSync(fd) this.emit('close') } } } class WriteStream extends EE { constructor (path, opt) { opt = opt || {} super(opt) this.readable = false this.writable = true this[_errored] = false this[_writing] = false this[_ended] = false this[_needDrain] = false this[_queue] = [] this[_path] = path this[_fd] = typeof opt.fd === 'number' ? opt.fd : null this[_mode] = opt.mode === undefined ? 0o666 : opt.mode this[_pos] = typeof opt.start === 'number' ? opt.start : null this[_autoClose] = typeof opt.autoClose === 'boolean' ? opt.autoClose : true // truncating makes no sense when writing into the middle const defaultFlag = this[_pos] !== null ? 'r+' : 'w' this[_defaultFlag] = opt.flags === undefined this[_flags] = this[_defaultFlag] ? defaultFlag : opt.flags if (this[_fd] === null) this[_open]() } emit (ev, data) { if (ev === 'error') { if (this[_errored]) return this[_errored] = true } return super.emit(ev, data) } get fd () { return this[_fd] } get path () { return this[_path] } [_onerror] (er) { this[_close]() this[_writing] = true this.emit('error', er) } [_open] () { fs.open(this[_path], this[_flags], this[_mode], (er, fd) => this[_onopen](er, fd)) } [_onopen] (er, fd) { if (this[_defaultFlag] && this[_flags] === 'r+' && er && er.code === 'ENOENT') { this[_flags] = 'w' this[_open]() } else if (er) this[_onerror](er) else { this[_fd] = fd this.emit('open', fd) this[_flush]() } } end (buf, enc) { if (buf) this.write(buf, enc) this[_ended] = true // synthetic after-write logic, where drain/finish live if (!this[_writing] && !this[_queue].length && typeof this[_fd] === 'number') this[_onwrite](null, 0) return this } write (buf, enc) { if (typeof buf === 'string') buf = Buffer.from(buf, enc) if (this[_ended]) { this.emit('error', new Error('write() after end()')) return false } if (this[_fd] === null || this[_writing] || this[_queue].length) { this[_queue].push(buf) this[_needDrain] = true return false } this[_writing] = true this[_write](buf) return true } [_write] (buf) { fs.write(this[_fd], buf, 0, buf.length, this[_pos], (er, bw) => this[_onwrite](er, bw)) } [_onwrite] (er, bw) { if (er) this[_onerror](er) else { if (this[_pos] !== null) this[_pos] += bw if (this[_queue].length) this[_flush]() else { this[_writing] = false if (this[_ended] && !this[_finished]) { this[_finished] = true this[_close]() this.emit('finish') } else if (this[_needDrain]) { this[_needDrain] = false this.emit('drain') } } } } [_flush] () { if (this[_queue].length === 0) { if (this[_ended]) this[_onwrite](null, 0) } else if (this[_queue].length === 1) this[_write](this[_queue].pop()) else { const iovec = this[_queue] this[_queue] = [] writev(this[_fd], iovec, this[_pos], (er, bw) => this[_onwrite](er, bw)) } } [_close] () { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd] this[_fd] = null fs.close(fd, er => er ? this.emit('error', er) : this.emit('close')) } } } class WriteStreamSync extends WriteStream { [_open] () { let fd // only wrap in a try{} block if we know we'll retry, to avoid // the rethrow obscuring the error's source frame in most cases. if (this[_defaultFlag] && this[_flags] === 'r+') { try { fd = fs.openSync(this[_path], this[_flags], this[_mode]) } catch (er) { if (er.code === 'ENOENT') { this[_flags] = 'w' return this[_open]() } else throw er } } else fd = fs.openSync(this[_path], this[_flags], this[_mode]) this[_onopen](null, fd) } [_close] () { if (this[_autoClose] && typeof this[_fd] === 'number') { const fd = this[_fd] this[_fd] = null fs.closeSync(fd) this.emit('close') } } [_write] (buf) { // throw the original, but try to close if it fails let threw = true try { this[_onwrite](null, fs.writeSync(this[_fd], buf, 0, buf.length, this[_pos])) threw = false } finally { if (threw) try { this[_close]() } catch (_) {} } } } exports.ReadStream = ReadStream exports.ReadStreamSync = ReadStreamSync exports.WriteStream = WriteStream exports.WriteStreamSync = WriteStreamSync PK ~\:::tar/lib/path-reservations.jsnu[// A path exclusive reservation system // reserve([list, of, paths], fn) // When the fn is first in line for all its paths, it // is called with a cb that clears the reservation. // // Used by async unpack to avoid clobbering paths in use, // while still allowing maximal safe parallelization. const assert = require('assert') const normalize = require('./normalize-unicode.js') const stripSlashes = require('./strip-trailing-slashes.js') const { join } = require('path') const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform const isWindows = platform === 'win32' module.exports = () => { // path => [function or Set] // A Set object means a directory reservation // A fn is a direct reservation on that path const queues = new Map() // fn => {paths:[path,...], dirs:[path, ...]} const reservations = new Map() // return a set of parent dirs for a given path // '/a/b/c/d' -> ['/', '/a', '/a/b', '/a/b/c', '/a/b/c/d'] const getDirs = path => { const dirs = path.split('/').slice(0, -1).reduce((set, path) => { if (set.length) { path = join(set[set.length - 1], path) } set.push(path || '/') return set }, []) return dirs } // functions currently running const running = new Set() // return the queues for each path the function cares about // fn => {paths, dirs} const getQueues = fn => { const res = reservations.get(fn) /* istanbul ignore if - unpossible */ if (!res) { throw new Error('function does not have any path reservations') } return { paths: res.paths.map(path => queues.get(path)), dirs: [...res.dirs].map(path => queues.get(path)), } } // check if fn is first in line for all its paths, and is // included in the first set for all its dir queues const check = fn => { const { paths, dirs } = getQueues(fn) return paths.every(q => q[0] === fn) && dirs.every(q => q[0] instanceof Set && q[0].has(fn)) } // run the function if it's first in line and not already running const run = fn => { if (running.has(fn) || !check(fn)) { return false } running.add(fn) fn(() => clear(fn)) return true } const clear = fn => { if (!running.has(fn)) { return false } const { paths, dirs } = reservations.get(fn) const next = new Set() paths.forEach(path => { const q = queues.get(path) assert.equal(q[0], fn) if (q.length === 1) { queues.delete(path) } else { q.shift() if (typeof q[0] === 'function') { next.add(q[0]) } else { q[0].forEach(fn => next.add(fn)) } } }) dirs.forEach(dir => { const q = queues.get(dir) assert(q[0] instanceof Set) if (q[0].size === 1 && q.length === 1) { queues.delete(dir) } else if (q[0].size === 1) { q.shift() // must be a function or else the Set would've been reused next.add(q[0]) } else { q[0].delete(fn) } }) running.delete(fn) next.forEach(fn => run(fn)) return true } const reserve = (paths, fn) => { // collide on matches across case and unicode normalization // On windows, thanks to the magic of 8.3 shortnames, it is fundamentally // impossible to determine whether two paths refer to the same thing on // disk, without asking the kernel for a shortname. // So, we just pretend that every path matches every other path here, // effectively removing all parallelization on windows. paths = isWindows ? ['win32 parallelization disabled'] : paths.map(p => { // don't need normPath, because we skip this entirely for windows return stripSlashes(join(normalize(p))).toLowerCase() }) const dirs = new Set( paths.map(path => getDirs(path)).reduce((a, b) => a.concat(b)) ) reservations.set(fn, { dirs, paths }) paths.forEach(path => { const q = queues.get(path) if (!q) { queues.set(path, [fn]) } else { q.push(fn) } }) dirs.forEach(dir => { const q = queues.get(dir) if (!q) { queues.set(dir, [new Set([fn])]) } else if (q[q.length - 1] instanceof Set) { q[q.length - 1].add(fn) } else { q.push(new Set([fn])) } }) return run(fn) } return { check, reserve } } PK ~\n|@ddtar/lib/unpack.jsnu['use strict' // the PEND/UNPEND stuff tracks whether we're ready to emit end/close yet. // but the path reservations are required to avoid race conditions where // parallelized unpack ops may mess with one another, due to dependencies // (like a Link depending on its target) or destructive operations (like // clobbering an fs object to create one of a different type.) const assert = require('assert') const Parser = require('./parse.js') const fs = require('fs') const fsm = require('fs-minipass') const path = require('path') const mkdir = require('./mkdir.js') const wc = require('./winchars.js') const pathReservations = require('./path-reservations.js') const stripAbsolutePath = require('./strip-absolute-path.js') const normPath = require('./normalize-windows-path.js') const stripSlash = require('./strip-trailing-slashes.js') const normalize = require('./normalize-unicode.js') const ONENTRY = Symbol('onEntry') const CHECKFS = Symbol('checkFs') const CHECKFS2 = Symbol('checkFs2') const PRUNECACHE = Symbol('pruneCache') const ISREUSABLE = Symbol('isReusable') const MAKEFS = Symbol('makeFs') const FILE = Symbol('file') const DIRECTORY = Symbol('directory') const LINK = Symbol('link') const SYMLINK = Symbol('symlink') const HARDLINK = Symbol('hardlink') const UNSUPPORTED = Symbol('unsupported') const CHECKPATH = Symbol('checkPath') const MKDIR = Symbol('mkdir') const ONERROR = Symbol('onError') const PENDING = Symbol('pending') const PEND = Symbol('pend') const UNPEND = Symbol('unpend') const ENDED = Symbol('ended') const MAYBECLOSE = Symbol('maybeClose') const SKIP = Symbol('skip') const DOCHOWN = Symbol('doChown') const UID = Symbol('uid') const GID = Symbol('gid') const CHECKED_CWD = Symbol('checkedCwd') const crypto = require('crypto') const getFlag = require('./get-write-flag.js') const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform const isWindows = platform === 'win32' const DEFAULT_MAX_DEPTH = 1024 // Unlinks on Windows are not atomic. // // This means that if you have a file entry, followed by another // file entry with an identical name, and you cannot re-use the file // (because it's a hardlink, or because unlink:true is set, or it's // Windows, which does not have useful nlink values), then the unlink // will be committed to the disk AFTER the new file has been written // over the old one, deleting the new file. // // To work around this, on Windows systems, we rename the file and then // delete the renamed file. It's a sloppy kludge, but frankly, I do not // know of a better way to do this, given windows' non-atomic unlink // semantics. // // See: https://github.com/npm/node-tar/issues/183 /* istanbul ignore next */ const unlinkFile = (path, cb) => { if (!isWindows) { return fs.unlink(path, cb) } const name = path + '.DELETE.' + crypto.randomBytes(16).toString('hex') fs.rename(path, name, er => { if (er) { return cb(er) } fs.unlink(name, cb) }) } /* istanbul ignore next */ const unlinkFileSync = path => { if (!isWindows) { return fs.unlinkSync(path) } const name = path + '.DELETE.' + crypto.randomBytes(16).toString('hex') fs.renameSync(path, name) fs.unlinkSync(name) } // this.gid, entry.gid, this.processUid const uint32 = (a, b, c) => a === a >>> 0 ? a : b === b >>> 0 ? b : c // clear the cache if it's a case-insensitive unicode-squashing match. // we can't know if the current file system is case-sensitive or supports // unicode fully, so we check for similarity on the maximally compatible // representation. Err on the side of pruning, since all it's doing is // preventing lstats, and it's not the end of the world if we get a false // positive. // Note that on windows, we always drop the entire cache whenever a // symbolic link is encountered, because 8.3 filenames are impossible // to reason about, and collisions are hazards rather than just failures. const cacheKeyNormalize = path => stripSlash(normPath(normalize(path))) .toLowerCase() const pruneCache = (cache, abs) => { abs = cacheKeyNormalize(abs) for (const path of cache.keys()) { const pnorm = cacheKeyNormalize(path) if (pnorm === abs || pnorm.indexOf(abs + '/') === 0) { cache.delete(path) } } } const dropCache = cache => { for (const key of cache.keys()) { cache.delete(key) } } class Unpack extends Parser { constructor (opt) { if (!opt) { opt = {} } opt.ondone = _ => { this[ENDED] = true this[MAYBECLOSE]() } super(opt) this[CHECKED_CWD] = false this.reservations = pathReservations() this.transform = typeof opt.transform === 'function' ? opt.transform : null this.writable = true this.readable = false this[PENDING] = 0 this[ENDED] = false this.dirCache = opt.dirCache || new Map() if (typeof opt.uid === 'number' || typeof opt.gid === 'number') { // need both or neither if (typeof opt.uid !== 'number' || typeof opt.gid !== 'number') { throw new TypeError('cannot set owner without number uid and gid') } if (opt.preserveOwner) { throw new TypeError( 'cannot preserve owner in archive and also set owner explicitly') } this.uid = opt.uid this.gid = opt.gid this.setOwner = true } else { this.uid = null this.gid = null this.setOwner = false } // default true for root if (opt.preserveOwner === undefined && typeof opt.uid !== 'number') { this.preserveOwner = process.getuid && process.getuid() === 0 } else { this.preserveOwner = !!opt.preserveOwner } this.processUid = (this.preserveOwner || this.setOwner) && process.getuid ? process.getuid() : null this.processGid = (this.preserveOwner || this.setOwner) && process.getgid ? process.getgid() : null // prevent excessively deep nesting of subfolders // set to `Infinity` to remove this restriction this.maxDepth = typeof opt.maxDepth === 'number' ? opt.maxDepth : DEFAULT_MAX_DEPTH // mostly just for testing, but useful in some cases. // Forcibly trigger a chown on every entry, no matter what this.forceChown = opt.forceChown === true // turn > this[ONENTRY](entry)) } // a bad or damaged archive is a warning for Parser, but an error // when extracting. Mark those errors as unrecoverable, because // the Unpack contract cannot be met. warn (code, msg, data = {}) { if (code === 'TAR_BAD_ARCHIVE' || code === 'TAR_ABORT') { data.recoverable = false } return super.warn(code, msg, data) } [MAYBECLOSE] () { if (this[ENDED] && this[PENDING] === 0) { this.emit('prefinish') this.emit('finish') this.emit('end') } } [CHECKPATH] (entry) { const p = normPath(entry.path) const parts = p.split('/') if (this.strip) { if (parts.length < this.strip) { return false } if (entry.type === 'Link') { const linkparts = normPath(entry.linkpath).split('/') if (linkparts.length >= this.strip) { entry.linkpath = linkparts.slice(this.strip).join('/') } else { return false } } parts.splice(0, this.strip) entry.path = parts.join('/') } if (isFinite(this.maxDepth) && parts.length > this.maxDepth) { this.warn('TAR_ENTRY_ERROR', 'path excessively deep', { entry, path: p, depth: parts.length, maxDepth: this.maxDepth, }) return false } if (!this.preservePaths) { if (parts.includes('..') || isWindows && /^[a-z]:\.\.$/i.test(parts[0])) { this.warn('TAR_ENTRY_ERROR', `path contains '..'`, { entry, path: p, }) return false } // strip off the root const [root, stripped] = stripAbsolutePath(p) if (root) { entry.path = stripped this.warn('TAR_ENTRY_INFO', `stripping ${root} from absolute path`, { entry, path: p, }) } } if (path.isAbsolute(entry.path)) { entry.absolute = normPath(path.resolve(entry.path)) } else { entry.absolute = normPath(path.resolve(this.cwd, entry.path)) } // if we somehow ended up with a path that escapes the cwd, and we are // not in preservePaths mode, then something is fishy! This should have // been prevented above, so ignore this for coverage. /* istanbul ignore if - defense in depth */ if (!this.preservePaths && entry.absolute.indexOf(this.cwd + '/') !== 0 && entry.absolute !== this.cwd) { this.warn('TAR_ENTRY_ERROR', 'path escaped extraction target', { entry, path: normPath(entry.path), resolvedPath: entry.absolute, cwd: this.cwd, }) return false } // an archive can set properties on the extraction directory, but it // may not replace the cwd with a different kind of thing entirely. if (entry.absolute === this.cwd && entry.type !== 'Directory' && entry.type !== 'GNUDumpDir') { return false } // only encode : chars that aren't drive letter indicators if (this.win32) { const { root: aRoot } = path.win32.parse(entry.absolute) entry.absolute = aRoot + wc.encode(entry.absolute.slice(aRoot.length)) const { root: pRoot } = path.win32.parse(entry.path) entry.path = pRoot + wc.encode(entry.path.slice(pRoot.length)) } return true } [ONENTRY] (entry) { if (!this[CHECKPATH](entry)) { return entry.resume() } assert.equal(typeof entry.absolute, 'string') switch (entry.type) { case 'Directory': case 'GNUDumpDir': if (entry.mode) { entry.mode = entry.mode | 0o700 } // eslint-disable-next-line no-fallthrough case 'File': case 'OldFile': case 'ContiguousFile': case 'Link': case 'SymbolicLink': return this[CHECKFS](entry) case 'CharacterDevice': case 'BlockDevice': case 'FIFO': default: return this[UNSUPPORTED](entry) } } [ONERROR] (er, entry) { // Cwd has to exist, or else nothing works. That's serious. // Other errors are warnings, which raise the error in strict // mode, but otherwise continue on. if (er.name === 'CwdError') { this.emit('error', er) } else { this.warn('TAR_ENTRY_ERROR', er, { entry }) this[UNPEND]() entry.resume() } } [MKDIR] (dir, mode, cb) { mkdir(normPath(dir), { uid: this.uid, gid: this.gid, processUid: this.processUid, processGid: this.processGid, umask: this.processUmask, preserve: this.preservePaths, unlink: this.unlink, cache: this.dirCache, cwd: this.cwd, mode: mode, noChmod: this.noChmod, }, cb) } [DOCHOWN] (entry) { // in preserve owner mode, chown if the entry doesn't match process // in set owner mode, chown if setting doesn't match process return this.forceChown || this.preserveOwner && (typeof entry.uid === 'number' && entry.uid !== this.processUid || typeof entry.gid === 'number' && entry.gid !== this.processGid) || (typeof this.uid === 'number' && this.uid !== this.processUid || typeof this.gid === 'number' && this.gid !== this.processGid) } [UID] (entry) { return uint32(this.uid, entry.uid, this.processUid) } [GID] (entry) { return uint32(this.gid, entry.gid, this.processGid) } [FILE] (entry, fullyDone) { const mode = entry.mode & 0o7777 || this.fmode const stream = new fsm.WriteStream(entry.absolute, { flags: getFlag(entry.size), mode: mode, autoClose: false, }) stream.on('error', er => { if (stream.fd) { fs.close(stream.fd, () => {}) } // flush all the data out so that we aren't left hanging // if the error wasn't actually fatal. otherwise the parse // is blocked, and we never proceed. stream.write = () => true this[ONERROR](er, entry) fullyDone() }) let actions = 1 const done = er => { if (er) { /* istanbul ignore else - we should always have a fd by now */ if (stream.fd) { fs.close(stream.fd, () => {}) } this[ONERROR](er, entry) fullyDone() return } if (--actions === 0) { fs.close(stream.fd, er => { if (er) { this[ONERROR](er, entry) } else { this[UNPEND]() } fullyDone() }) } } stream.on('finish', _ => { // if futimes fails, try utimes // if utimes fails, fail with the original error // same for fchown/chown const abs = entry.absolute const fd = stream.fd if (entry.mtime && !this.noMtime) { actions++ const atime = entry.atime || new Date() const mtime = entry.mtime fs.futimes(fd, atime, mtime, er => er ? fs.utimes(abs, atime, mtime, er2 => done(er2 && er)) : done()) } if (this[DOCHOWN](entry)) { actions++ const uid = this[UID](entry) const gid = this[GID](entry) fs.fchown(fd, uid, gid, er => er ? fs.chown(abs, uid, gid, er2 => done(er2 && er)) : done()) } done() }) const tx = this.transform ? this.transform(entry) || entry : entry if (tx !== entry) { tx.on('error', er => { this[ONERROR](er, entry) fullyDone() }) entry.pipe(tx) } tx.pipe(stream) } [DIRECTORY] (entry, fullyDone) { const mode = entry.mode & 0o7777 || this.dmode this[MKDIR](entry.absolute, mode, er => { if (er) { this[ONERROR](er, entry) fullyDone() return } let actions = 1 const done = _ => { if (--actions === 0) { fullyDone() this[UNPEND]() entry.resume() } } if (entry.mtime && !this.noMtime) { actions++ fs.utimes(entry.absolute, entry.atime || new Date(), entry.mtime, done) } if (this[DOCHOWN](entry)) { actions++ fs.chown(entry.absolute, this[UID](entry), this[GID](entry), done) } done() }) } [UNSUPPORTED] (entry) { entry.unsupported = true this.warn('TAR_ENTRY_UNSUPPORTED', `unsupported entry type: ${entry.type}`, { entry }) entry.resume() } [SYMLINK] (entry, done) { this[LINK](entry, entry.linkpath, 'symlink', done) } [HARDLINK] (entry, done) { const linkpath = normPath(path.resolve(this.cwd, entry.linkpath)) this[LINK](entry, linkpath, 'link', done) } [PEND] () { this[PENDING]++ } [UNPEND] () { this[PENDING]-- this[MAYBECLOSE]() } [SKIP] (entry) { this[UNPEND]() entry.resume() } // Check if we can reuse an existing filesystem entry safely and // overwrite it, rather than unlinking and recreating // Windows doesn't report a useful nlink, so we just never reuse entries [ISREUSABLE] (entry, st) { return entry.type === 'File' && !this.unlink && st.isFile() && st.nlink <= 1 && !isWindows } // check if a thing is there, and if so, try to clobber it [CHECKFS] (entry) { this[PEND]() const paths = [entry.path] if (entry.linkpath) { paths.push(entry.linkpath) } this.reservations.reserve(paths, done => this[CHECKFS2](entry, done)) } [PRUNECACHE] (entry) { // if we are not creating a directory, and the path is in the dirCache, // then that means we are about to delete the directory we created // previously, and it is no longer going to be a directory, and neither // is any of its children. // If a symbolic link is encountered, all bets are off. There is no // reasonable way to sanitize the cache in such a way we will be able to // avoid having filesystem collisions. If this happens with a non-symlink // entry, it'll just fail to unpack, but a symlink to a directory, using an // 8.3 shortname or certain unicode attacks, can evade detection and lead // to arbitrary writes to anywhere on the system. if (entry.type === 'SymbolicLink') { dropCache(this.dirCache) } else if (entry.type !== 'Directory') { pruneCache(this.dirCache, entry.absolute) } } [CHECKFS2] (entry, fullyDone) { this[PRUNECACHE](entry) const done = er => { this[PRUNECACHE](entry) fullyDone(er) } const checkCwd = () => { this[MKDIR](this.cwd, this.dmode, er => { if (er) { this[ONERROR](er, entry) done() return } this[CHECKED_CWD] = true start() }) } const start = () => { if (entry.absolute !== this.cwd) { const parent = normPath(path.dirname(entry.absolute)) if (parent !== this.cwd) { return this[MKDIR](parent, this.dmode, er => { if (er) { this[ONERROR](er, entry) done() return } afterMakeParent() }) } } afterMakeParent() } const afterMakeParent = () => { fs.lstat(entry.absolute, (lstatEr, st) => { if (st && (this.keep || this.newer && st.mtime > entry.mtime)) { this[SKIP](entry) done() return } if (lstatEr || this[ISREUSABLE](entry, st)) { return this[MAKEFS](null, entry, done) } if (st.isDirectory()) { if (entry.type === 'Directory') { const needChmod = !this.noChmod && entry.mode && (st.mode & 0o7777) !== entry.mode const afterChmod = er => this[MAKEFS](er, entry, done) if (!needChmod) { return afterChmod() } return fs.chmod(entry.absolute, entry.mode, afterChmod) } // Not a dir entry, have to remove it. // NB: the only way to end up with an entry that is the cwd // itself, in such a way that == does not detect, is a // tricky windows absolute path with UNC or 8.3 parts (and // preservePaths:true, or else it will have been stripped). // In that case, the user has opted out of path protections // explicitly, so if they blow away the cwd, c'est la vie. if (entry.absolute !== this.cwd) { return fs.rmdir(entry.absolute, er => this[MAKEFS](er, entry, done)) } } // not a dir, and not reusable // don't remove if the cwd, we want that error if (entry.absolute === this.cwd) { return this[MAKEFS](null, entry, done) } unlinkFile(entry.absolute, er => this[MAKEFS](er, entry, done)) }) } if (this[CHECKED_CWD]) { start() } else { checkCwd() } } [MAKEFS] (er, entry, done) { if (er) { this[ONERROR](er, entry) done() return } switch (entry.type) { case 'File': case 'OldFile': case 'ContiguousFile': return this[FILE](entry, done) case 'Link': return this[HARDLINK](entry, done) case 'SymbolicLink': return this[SYMLINK](entry, done) case 'Directory': case 'GNUDumpDir': return this[DIRECTORY](entry, done) } } [LINK] (entry, linkpath, link, done) { // XXX: get the type ('symlink' or 'junction') for windows fs[link](linkpath, entry.absolute, er => { if (er) { this[ONERROR](er, entry) } else { this[UNPEND]() entry.resume() } done() }) } } const callSync = fn => { try { return [null, fn()] } catch (er) { return [er, null] } } class UnpackSync extends Unpack { [MAKEFS] (er, entry) { return super[MAKEFS](er, entry, () => {}) } [CHECKFS] (entry) { this[PRUNECACHE](entry) if (!this[CHECKED_CWD]) { const er = this[MKDIR](this.cwd, this.dmode) if (er) { return this[ONERROR](er, entry) } this[CHECKED_CWD] = true } // don't bother to make the parent if the current entry is the cwd, // we've already checked it. if (entry.absolute !== this.cwd) { const parent = normPath(path.dirname(entry.absolute)) if (parent !== this.cwd) { const mkParent = this[MKDIR](parent, this.dmode) if (mkParent) { return this[ONERROR](mkParent, entry) } } } const [lstatEr, st] = callSync(() => fs.lstatSync(entry.absolute)) if (st && (this.keep || this.newer && st.mtime > entry.mtime)) { return this[SKIP](entry) } if (lstatEr || this[ISREUSABLE](entry, st)) { return this[MAKEFS](null, entry) } if (st.isDirectory()) { if (entry.type === 'Directory') { const needChmod = !this.noChmod && entry.mode && (st.mode & 0o7777) !== entry.mode const [er] = needChmod ? callSync(() => { fs.chmodSync(entry.absolute, entry.mode) }) : [] return this[MAKEFS](er, entry) } // not a dir entry, have to remove it const [er] = callSync(() => fs.rmdirSync(entry.absolute)) this[MAKEFS](er, entry) } // not a dir, and not reusable. // don't remove if it's the cwd, since we want that error. const [er] = entry.absolute === this.cwd ? [] : callSync(() => unlinkFileSync(entry.absolute)) this[MAKEFS](er, entry) } [FILE] (entry, done) { const mode = entry.mode & 0o7777 || this.fmode const oner = er => { let closeError try { fs.closeSync(fd) } catch (e) { closeError = e } if (er || closeError) { this[ONERROR](er || closeError, entry) } done() } let fd try { fd = fs.openSync(entry.absolute, getFlag(entry.size), mode) } catch (er) { return oner(er) } const tx = this.transform ? this.transform(entry) || entry : entry if (tx !== entry) { tx.on('error', er => this[ONERROR](er, entry)) entry.pipe(tx) } tx.on('data', chunk => { try { fs.writeSync(fd, chunk, 0, chunk.length) } catch (er) { oner(er) } }) tx.on('end', _ => { let er = null // try both, falling futimes back to utimes // if either fails, handle the first error if (entry.mtime && !this.noMtime) { const atime = entry.atime || new Date() const mtime = entry.mtime try { fs.futimesSync(fd, atime, mtime) } catch (futimeser) { try { fs.utimesSync(entry.absolute, atime, mtime) } catch (utimeser) { er = futimeser } } } if (this[DOCHOWN](entry)) { const uid = this[UID](entry) const gid = this[GID](entry) try { fs.fchownSync(fd, uid, gid) } catch (fchowner) { try { fs.chownSync(entry.absolute, uid, gid) } catch (chowner) { er = er || fchowner } } } oner(er) }) } [DIRECTORY] (entry, done) { const mode = entry.mode & 0o7777 || this.dmode const er = this[MKDIR](entry.absolute, mode) if (er) { this[ONERROR](er, entry) done() return } if (entry.mtime && !this.noMtime) { try { fs.utimesSync(entry.absolute, entry.atime || new Date(), entry.mtime) } catch (er) {} } if (this[DOCHOWN](entry)) { try { fs.chownSync(entry.absolute, this[UID](entry), this[GID](entry)) } catch (er) {} } done() entry.resume() } [MKDIR] (dir, mode) { try { return mkdir.sync(normPath(dir), { uid: this.uid, gid: this.gid, processUid: this.processUid, processGid: this.processGid, umask: this.processUmask, preserve: this.preservePaths, unlink: this.unlink, cache: this.dirCache, cwd: this.cwd, mode: mode, }) } catch (er) { return er } } [LINK] (entry, linkpath, link, done) { try { fs[link + 'Sync'](linkpath, entry.absolute) done() entry.resume() } catch (er) { return this[ONERROR](er, entry) } } } Unpack.Sync = UnpackSync module.exports = Unpack PK ~\87tar/lib/normalize-unicode.jsnu[// warning: extremely hot code path. // This has been meticulously optimized for use // within npm install on large package trees. // Do not edit without careful benchmarking. const normalizeCache = Object.create(null) const { hasOwnProperty } = Object.prototype module.exports = s => { if (!hasOwnProperty.call(normalizeCache, s)) { normalizeCache[s] = s.normalize('NFD') } return normalizeCache[s] } PK ~\dnItar/lib/get-write-flag.jsnu[// Get the appropriate flag to use for creating files // We use fmap on Windows platforms for files less than // 512kb. This is a fairly low limit, but avoids making // things slower in some cases. Since most of what this // library is used for is extracting tarballs of many // relatively small files in npm packages and the like, // it can be a big boost on Windows platforms. // Only supported in Node v12.9.0 and above. const platform = process.env.__FAKE_PLATFORM__ || process.platform const isWindows = platform === 'win32' const fs = global.__FAKE_TESTING_FS__ || require('fs') /* istanbul ignore next */ const { O_CREAT, O_TRUNC, O_WRONLY, UV_FS_O_FILEMAP = 0 } = fs.constants const fMapEnabled = isWindows && !!UV_FS_O_FILEMAP const fMapLimit = 512 * 1024 const fMapFlag = UV_FS_O_FILEMAP | O_TRUNC | O_CREAT | O_WRONLY module.exports = !fMapEnabled ? () => 'w' : size => size < fMapLimit ? fMapFlag : 'w' PK ~\dk tar/lib/list.jsnu['use strict' // XXX: This shares a lot in common with extract.js // maybe some DRY opportunity here? // tar -t const hlo = require('./high-level-opt.js') const Parser = require('./parse.js') const fs = require('fs') const fsm = require('fs-minipass') const path = require('path') const stripSlash = require('./strip-trailing-slashes.js') module.exports = (opt_, files, cb) => { if (typeof opt_ === 'function') { cb = opt_, files = null, opt_ = {} } else if (Array.isArray(opt_)) { files = opt_, opt_ = {} } if (typeof files === 'function') { cb = files, files = null } if (!files) { files = [] } else { files = Array.from(files) } const opt = hlo(opt_) if (opt.sync && typeof cb === 'function') { throw new TypeError('callback not supported for sync tar functions') } if (!opt.file && typeof cb === 'function') { throw new TypeError('callback only supported with file option') } if (files.length) { filesFilter(opt, files) } if (!opt.noResume) { onentryFunction(opt) } return opt.file && opt.sync ? listFileSync(opt) : opt.file ? listFile(opt, cb) : list(opt) } const onentryFunction = opt => { const onentry = opt.onentry opt.onentry = onentry ? e => { onentry(e) e.resume() } : e => e.resume() } // construct a filter that limits the file entries listed // include child entries if a dir is included const filesFilter = (opt, files) => { const map = new Map(files.map(f => [stripSlash(f), true])) const filter = opt.filter const mapHas = (file, r) => { const root = r || path.parse(file).root || '.' const ret = file === root ? false : map.has(file) ? map.get(file) : mapHas(path.dirname(file), root) map.set(file, ret) return ret } opt.filter = filter ? (file, entry) => filter(file, entry) && mapHas(stripSlash(file)) : file => mapHas(stripSlash(file)) } const listFileSync = opt => { const p = list(opt) const file = opt.file let threw = true let fd try { const stat = fs.statSync(file) const readSize = opt.maxReadSize || 16 * 1024 * 1024 if (stat.size < readSize) { p.end(fs.readFileSync(file)) } else { let pos = 0 const buf = Buffer.allocUnsafe(readSize) fd = fs.openSync(file, 'r') while (pos < stat.size) { const bytesRead = fs.readSync(fd, buf, 0, readSize, pos) pos += bytesRead p.write(buf.slice(0, bytesRead)) } p.end() } threw = false } finally { if (threw && fd) { try { fs.closeSync(fd) } catch (er) {} } } } const listFile = (opt, cb) => { const parse = new Parser(opt) const readSize = opt.maxReadSize || 16 * 1024 * 1024 const file = opt.file const p = new Promise((resolve, reject) => { parse.on('error', reject) parse.on('end', resolve) fs.stat(file, (er, stat) => { if (er) { reject(er) } else { const stream = new fsm.ReadStream(file, { readSize: readSize, size: stat.size, }) stream.on('error', reject) stream.pipe(parse) } }) }) return cb ? p.then(cb, cb) : p } const list = opt => new Parser(opt) PK ~\$HHtar/lib/types.jsnu['use strict' // map types from key to human-friendly name exports.name = new Map([ ['0', 'File'], // same as File ['', 'OldFile'], ['1', 'Link'], ['2', 'SymbolicLink'], // Devices and FIFOs aren't fully supported // they are parsed, but skipped when unpacking ['3', 'CharacterDevice'], ['4', 'BlockDevice'], ['5', 'Directory'], ['6', 'FIFO'], // same as File ['7', 'ContiguousFile'], // pax headers ['g', 'GlobalExtendedHeader'], ['x', 'ExtendedHeader'], // vendor-specific stuff // skip ['A', 'SolarisACL'], // like 5, but with data, which should be skipped ['D', 'GNUDumpDir'], // metadata only, skip ['I', 'Inode'], // data = link path of next file ['K', 'NextFileHasLongLinkpath'], // data = path of next file ['L', 'NextFileHasLongPath'], // skip ['M', 'ContinuationFile'], // like L ['N', 'OldGnuLongPath'], // skip ['S', 'SparseFile'], // skip ['V', 'TapeVolumeHeader'], // like x ['X', 'OldExtendedHeader'], ]) // map the other direction exports.code = new Map(Array.from(exports.name).map(kv => [kv[1], kv[0]])) PK ~\9uRZ  tar/lib/read-entry.jsnu['use strict' const { Minipass } = require('minipass') const normPath = require('./normalize-windows-path.js') const SLURP = Symbol('slurp') module.exports = class ReadEntry extends Minipass { constructor (header, ex, gex) { super() // read entries always start life paused. this is to avoid the // situation where Minipass's auto-ending empty streams results // in an entry ending before we're ready for it. this.pause() this.extended = ex this.globalExtended = gex this.header = header this.startBlockSize = 512 * Math.ceil(header.size / 512) this.blockRemain = this.startBlockSize this.remain = header.size this.type = header.type this.meta = false this.ignore = false switch (this.type) { case 'File': case 'OldFile': case 'Link': case 'SymbolicLink': case 'CharacterDevice': case 'BlockDevice': case 'Directory': case 'FIFO': case 'ContiguousFile': case 'GNUDumpDir': break case 'NextFileHasLongLinkpath': case 'NextFileHasLongPath': case 'OldGnuLongPath': case 'GlobalExtendedHeader': case 'ExtendedHeader': case 'OldExtendedHeader': this.meta = true break // NOTE: gnutar and bsdtar treat unrecognized types as 'File' // it may be worth doing the same, but with a warning. default: this.ignore = true } this.path = normPath(header.path) this.mode = header.mode if (this.mode) { this.mode = this.mode & 0o7777 } this.uid = header.uid this.gid = header.gid this.uname = header.uname this.gname = header.gname this.size = header.size this.mtime = header.mtime this.atime = header.atime this.ctime = header.ctime this.linkpath = normPath(header.linkpath) this.uname = header.uname this.gname = header.gname if (ex) { this[SLURP](ex) } if (gex) { this[SLURP](gex, true) } } write (data) { const writeLen = data.length if (writeLen > this.blockRemain) { throw new Error('writing more to entry than is appropriate') } const r = this.remain const br = this.blockRemain this.remain = Math.max(0, r - writeLen) this.blockRemain = Math.max(0, br - writeLen) if (this.ignore) { return true } if (r >= writeLen) { return super.write(data) } // r < writeLen return super.write(data.slice(0, r)) } [SLURP] (ex, global) { for (const k in ex) { // we slurp in everything except for the path attribute in // a global extended header, because that's weird. if (ex[k] !== null && ex[k] !== undefined && !(global && k === 'path')) { this[k] = k === 'path' || k === 'linkpath' ? normPath(ex[k]) : ex[k] } } } } PK ~\(tar/lib/winchars.jsnu['use strict' // When writing files on Windows, translate the characters to their // 0xf000 higher-encoded versions. const raw = [ '|', '<', '>', '?', ':', ] const win = raw.map(char => String.fromCharCode(0xf000 + char.charCodeAt(0))) const toWin = new Map(raw.map((char, i) => [char, win[i]])) const toRaw = new Map(win.map((char, i) => [char, raw[i]])) module.exports = { encode: s => raw.reduce((s, c) => s.split(c).join(toWin.get(c)), s), decode: s => win.reduce((s, c) => s.split(c).join(toRaw.get(c)), s), } PK ~\~^tar/lib/update.jsnu['use strict' // tar -u const hlo = require('./high-level-opt.js') const r = require('./replace.js') // just call tar.r with the filter and mtimeCache module.exports = (opt_, files, cb) => { const opt = hlo(opt_) if (!opt.file) { throw new TypeError('file is required') } if (opt.gzip || opt.brotli || opt.file.endsWith('.br') || opt.file.endsWith('.tbr')) { throw new TypeError('cannot append to compressed archives') } if (!files || !Array.isArray(files) || !files.length) { throw new TypeError('no files or directories specified') } files = Array.from(files) mtimeFilter(opt) return r(opt, files, cb) } const mtimeFilter = opt => { const filter = opt.filter if (!opt.mtimeCache) { opt.mtimeCache = new Map() } opt.filter = filter ? (path, stat) => filter(path, stat) && !(opt.mtimeCache.get(path) > stat.mtime) : (path, stat) => !(opt.mtimeCache.get(path) > stat.mtime) } PK ~\##tar/lib/header.jsnu['use strict' // parse a 512-byte header block to a data object, or vice-versa // encode returns `true` if a pax extended header is needed, because // the data could not be faithfully encoded in a simple header. // (Also, check header.needPax to see if it needs a pax header.) const types = require('./types.js') const pathModule = require('path').posix const large = require('./large-numbers.js') const SLURP = Symbol('slurp') const TYPE = Symbol('type') class Header { constructor (data, off, ex, gex) { this.cksumValid = false this.needPax = false this.nullBlock = false this.block = null this.path = null this.mode = null this.uid = null this.gid = null this.size = null this.mtime = null this.cksum = null this[TYPE] = '0' this.linkpath = null this.uname = null this.gname = null this.devmaj = 0 this.devmin = 0 this.atime = null this.ctime = null if (Buffer.isBuffer(data)) { this.decode(data, off || 0, ex, gex) } else if (data) { this.set(data) } } decode (buf, off, ex, gex) { if (!off) { off = 0 } if (!buf || !(buf.length >= off + 512)) { throw new Error('need 512 bytes for header') } this.path = decString(buf, off, 100) this.mode = decNumber(buf, off + 100, 8) this.uid = decNumber(buf, off + 108, 8) this.gid = decNumber(buf, off + 116, 8) this.size = decNumber(buf, off + 124, 12) this.mtime = decDate(buf, off + 136, 12) this.cksum = decNumber(buf, off + 148, 12) // if we have extended or global extended headers, apply them now // See https://github.com/npm/node-tar/pull/187 this[SLURP](ex) this[SLURP](gex, true) // old tar versions marked dirs as a file with a trailing / this[TYPE] = decString(buf, off + 156, 1) if (this[TYPE] === '') { this[TYPE] = '0' } if (this[TYPE] === '0' && this.path.slice(-1) === '/') { this[TYPE] = '5' } // tar implementations sometimes incorrectly put the stat(dir).size // as the size in the tarball, even though Directory entries are // not able to have any body at all. In the very rare chance that // it actually DOES have a body, we weren't going to do anything with // it anyway, and it'll just be a warning about an invalid header. if (this[TYPE] === '5') { this.size = 0 } this.linkpath = decString(buf, off + 157, 100) if (buf.slice(off + 257, off + 265).toString() === 'ustar\u000000') { this.uname = decString(buf, off + 265, 32) this.gname = decString(buf, off + 297, 32) this.devmaj = decNumber(buf, off + 329, 8) this.devmin = decNumber(buf, off + 337, 8) if (buf[off + 475] !== 0) { // definitely a prefix, definitely >130 chars. const prefix = decString(buf, off + 345, 155) this.path = prefix + '/' + this.path } else { const prefix = decString(buf, off + 345, 130) if (prefix) { this.path = prefix + '/' + this.path } this.atime = decDate(buf, off + 476, 12) this.ctime = decDate(buf, off + 488, 12) } } let sum = 8 * 0x20 for (let i = off; i < off + 148; i++) { sum += buf[i] } for (let i = off + 156; i < off + 512; i++) { sum += buf[i] } this.cksumValid = sum === this.cksum if (this.cksum === null && sum === 8 * 0x20) { this.nullBlock = true } } [SLURP] (ex, global) { for (const k in ex) { // we slurp in everything except for the path attribute in // a global extended header, because that's weird. if (ex[k] !== null && ex[k] !== undefined && !(global && k === 'path')) { this[k] = ex[k] } } } encode (buf, off) { if (!buf) { buf = this.block = Buffer.alloc(512) off = 0 } if (!off) { off = 0 } if (!(buf.length >= off + 512)) { throw new Error('need 512 bytes for header') } const prefixSize = this.ctime || this.atime ? 130 : 155 const split = splitPrefix(this.path || '', prefixSize) const path = split[0] const prefix = split[1] this.needPax = split[2] this.needPax = encString(buf, off, 100, path) || this.needPax this.needPax = encNumber(buf, off + 100, 8, this.mode) || this.needPax this.needPax = encNumber(buf, off + 108, 8, this.uid) || this.needPax this.needPax = encNumber(buf, off + 116, 8, this.gid) || this.needPax this.needPax = encNumber(buf, off + 124, 12, this.size) || this.needPax this.needPax = encDate(buf, off + 136, 12, this.mtime) || this.needPax buf[off + 156] = this[TYPE].charCodeAt(0) this.needPax = encString(buf, off + 157, 100, this.linkpath) || this.needPax buf.write('ustar\u000000', off + 257, 8) this.needPax = encString(buf, off + 265, 32, this.uname) || this.needPax this.needPax = encString(buf, off + 297, 32, this.gname) || this.needPax this.needPax = encNumber(buf, off + 329, 8, this.devmaj) || this.needPax this.needPax = encNumber(buf, off + 337, 8, this.devmin) || this.needPax this.needPax = encString(buf, off + 345, prefixSize, prefix) || this.needPax if (buf[off + 475] !== 0) { this.needPax = encString(buf, off + 345, 155, prefix) || this.needPax } else { this.needPax = encString(buf, off + 345, 130, prefix) || this.needPax this.needPax = encDate(buf, off + 476, 12, this.atime) || this.needPax this.needPax = encDate(buf, off + 488, 12, this.ctime) || this.needPax } let sum = 8 * 0x20 for (let i = off; i < off + 148; i++) { sum += buf[i] } for (let i = off + 156; i < off + 512; i++) { sum += buf[i] } this.cksum = sum encNumber(buf, off + 148, 8, this.cksum) this.cksumValid = true return this.needPax } set (data) { for (const i in data) { if (data[i] !== null && data[i] !== undefined) { this[i] = data[i] } } } get type () { return types.name.get(this[TYPE]) || this[TYPE] } get typeKey () { return this[TYPE] } set type (type) { if (types.code.has(type)) { this[TYPE] = types.code.get(type) } else { this[TYPE] = type } } } const splitPrefix = (p, prefixSize) => { const pathSize = 100 let pp = p let prefix = '' let ret const root = pathModule.parse(p).root || '.' if (Buffer.byteLength(pp) < pathSize) { ret = [pp, prefix, false] } else { // first set prefix to the dir, and path to the base prefix = pathModule.dirname(pp) pp = pathModule.basename(pp) do { if (Buffer.byteLength(pp) <= pathSize && Buffer.byteLength(prefix) <= prefixSize) { // both fit! ret = [pp, prefix, false] } else if (Buffer.byteLength(pp) > pathSize && Buffer.byteLength(prefix) <= prefixSize) { // prefix fits in prefix, but path doesn't fit in path ret = [pp.slice(0, pathSize - 1), prefix, true] } else { // make path take a bit from prefix pp = pathModule.join(pathModule.basename(prefix), pp) prefix = pathModule.dirname(prefix) } } while (prefix !== root && !ret) // at this point, found no resolution, just truncate if (!ret) { ret = [p.slice(0, pathSize - 1), '', true] } } return ret } const decString = (buf, off, size) => buf.slice(off, off + size).toString('utf8').replace(/\0.*/, '') const decDate = (buf, off, size) => numToDate(decNumber(buf, off, size)) const numToDate = num => num === null ? null : new Date(num * 1000) const decNumber = (buf, off, size) => buf[off] & 0x80 ? large.parse(buf.slice(off, off + size)) : decSmallNumber(buf, off, size) const nanNull = value => isNaN(value) ? null : value const decSmallNumber = (buf, off, size) => nanNull(parseInt( buf.slice(off, off + size) .toString('utf8').replace(/\0.*$/, '').trim(), 8)) // the maximum encodable as a null-terminated octal, by field size const MAXNUM = { 12: 0o77777777777, 8: 0o7777777, } const encNumber = (buf, off, size, number) => number === null ? false : number > MAXNUM[size] || number < 0 ? (large.encode(number, buf.slice(off, off + size)), true) : (encSmallNumber(buf, off, size, number), false) const encSmallNumber = (buf, off, size, number) => buf.write(octalString(number, size), off, size, 'ascii') const octalString = (number, size) => padOctal(Math.floor(number).toString(8), size) const padOctal = (string, size) => (string.length === size - 1 ? string : new Array(size - string.length - 1).join('0') + string + ' ') + '\0' const encDate = (buf, off, size, date) => date === null ? false : encNumber(buf, off, size, date.getTime() / 1000) // enough to fill the longest string we've got const NULLS = new Array(156).join('\0') // pad with nulls, return true if it's longer or non-ascii const encString = (buf, off, size, string) => string === null ? false : (buf.write(string + NULLS, off, size, 'utf8'), string.length !== Buffer.byteLength(string) || string.length > size) module.exports = Header PK ~\$$ $ tar/lib/extract.jsnu['use strict' // tar -x const hlo = require('./high-level-opt.js') const Unpack = require('./unpack.js') const fs = require('fs') const fsm = require('fs-minipass') const path = require('path') const stripSlash = require('./strip-trailing-slashes.js') module.exports = (opt_, files, cb) => { if (typeof opt_ === 'function') { cb = opt_, files = null, opt_ = {} } else if (Array.isArray(opt_)) { files = opt_, opt_ = {} } if (typeof files === 'function') { cb = files, files = null } if (!files) { files = [] } else { files = Array.from(files) } const opt = hlo(opt_) if (opt.sync && typeof cb === 'function') { throw new TypeError('callback not supported for sync tar functions') } if (!opt.file && typeof cb === 'function') { throw new TypeError('callback only supported with file option') } if (files.length) { filesFilter(opt, files) } return opt.file && opt.sync ? extractFileSync(opt) : opt.file ? extractFile(opt, cb) : opt.sync ? extractSync(opt) : extract(opt) } // construct a filter that limits the file entries listed // include child entries if a dir is included const filesFilter = (opt, files) => { const map = new Map(files.map(f => [stripSlash(f), true])) const filter = opt.filter const mapHas = (file, r) => { const root = r || path.parse(file).root || '.' const ret = file === root ? false : map.has(file) ? map.get(file) : mapHas(path.dirname(file), root) map.set(file, ret) return ret } opt.filter = filter ? (file, entry) => filter(file, entry) && mapHas(stripSlash(file)) : file => mapHas(stripSlash(file)) } const extractFileSync = opt => { const u = new Unpack.Sync(opt) const file = opt.file const stat = fs.statSync(file) // This trades a zero-byte read() syscall for a stat // However, it will usually result in less memory allocation const readSize = opt.maxReadSize || 16 * 1024 * 1024 const stream = new fsm.ReadStreamSync(file, { readSize: readSize, size: stat.size, }) stream.pipe(u) } const extractFile = (opt, cb) => { const u = new Unpack(opt) const readSize = opt.maxReadSize || 16 * 1024 * 1024 const file = opt.file const p = new Promise((resolve, reject) => { u.on('error', reject) u.on('close', resolve) // This trades a zero-byte read() syscall for a stat // However, it will usually result in less memory allocation fs.stat(file, (er, stat) => { if (er) { reject(er) } else { const stream = new fsm.ReadStream(file, { readSize: readSize, size: stat.size, }) stream.on('error', reject) stream.pipe(u) } }) }) return cb ? p.then(cb, cb) : p } const extractSync = opt => new Unpack.Sync(opt) const extract = opt => new Unpack(opt) PK ~\$n/??tar/lib/parse.jsnu['use strict' // this[BUFFER] is the remainder of a chunk if we're waiting for // the full 512 bytes of a header to come in. We will Buffer.concat() // it to the next write(), which is a mem copy, but a small one. // // this[QUEUE] is a Yallist of entries that haven't been emitted // yet this can only get filled up if the user keeps write()ing after // a write() returns false, or does a write() with more than one entry // // We don't buffer chunks, we always parse them and either create an // entry, or push it into the active entry. The ReadEntry class knows // to throw data away if .ignore=true // // Shift entry off the buffer when it emits 'end', and emit 'entry' for // the next one in the list. // // At any time, we're pushing body chunks into the entry at WRITEENTRY, // and waiting for 'end' on the entry at READENTRY // // ignored entries get .resume() called on them straight away const warner = require('./warn-mixin.js') const Header = require('./header.js') const EE = require('events') const Yallist = require('yallist') const maxMetaEntrySize = 1024 * 1024 const Entry = require('./read-entry.js') const Pax = require('./pax.js') const zlib = require('minizlib') const { nextTick } = require('process') const gzipHeader = Buffer.from([0x1f, 0x8b]) const STATE = Symbol('state') const WRITEENTRY = Symbol('writeEntry') const READENTRY = Symbol('readEntry') const NEXTENTRY = Symbol('nextEntry') const PROCESSENTRY = Symbol('processEntry') const EX = Symbol('extendedHeader') const GEX = Symbol('globalExtendedHeader') const META = Symbol('meta') const EMITMETA = Symbol('emitMeta') const BUFFER = Symbol('buffer') const QUEUE = Symbol('queue') const ENDED = Symbol('ended') const EMITTEDEND = Symbol('emittedEnd') const EMIT = Symbol('emit') const UNZIP = Symbol('unzip') const CONSUMECHUNK = Symbol('consumeChunk') const CONSUMECHUNKSUB = Symbol('consumeChunkSub') const CONSUMEBODY = Symbol('consumeBody') const CONSUMEMETA = Symbol('consumeMeta') const CONSUMEHEADER = Symbol('consumeHeader') const CONSUMING = Symbol('consuming') const BUFFERCONCAT = Symbol('bufferConcat') const MAYBEEND = Symbol('maybeEnd') const WRITING = Symbol('writing') const ABORTED = Symbol('aborted') const DONE = Symbol('onDone') const SAW_VALID_ENTRY = Symbol('sawValidEntry') const SAW_NULL_BLOCK = Symbol('sawNullBlock') const SAW_EOF = Symbol('sawEOF') const CLOSESTREAM = Symbol('closeStream') const noop = _ => true module.exports = warner(class Parser extends EE { constructor (opt) { opt = opt || {} super(opt) this.file = opt.file || '' // set to boolean false when an entry starts. 1024 bytes of \0 // is technically a valid tarball, albeit a boring one. this[SAW_VALID_ENTRY] = null // these BADARCHIVE errors can't be detected early. listen on DONE. this.on(DONE, _ => { if (this[STATE] === 'begin' || this[SAW_VALID_ENTRY] === false) { // either less than 1 block of data, or all entries were invalid. // Either way, probably not even a tarball. this.warn('TAR_BAD_ARCHIVE', 'Unrecognized archive format') } }) if (opt.ondone) { this.on(DONE, opt.ondone) } else { this.on(DONE, _ => { this.emit('prefinish') this.emit('finish') this.emit('end') }) } this.strict = !!opt.strict this.maxMetaEntrySize = opt.maxMetaEntrySize || maxMetaEntrySize this.filter = typeof opt.filter === 'function' ? opt.filter : noop // Unlike gzip, brotli doesn't have any magic bytes to identify it // Users need to explicitly tell us they're extracting a brotli file // Or we infer from the file extension const isTBR = (opt.file && ( opt.file.endsWith('.tar.br') || opt.file.endsWith('.tbr'))) // if it's a tbr file it MIGHT be brotli, but we don't know until // we look at it and verify it's not a valid tar file. this.brotli = !opt.gzip && opt.brotli !== undefined ? opt.brotli : isTBR ? undefined : false // have to set this so that streams are ok piping into it this.writable = true this.readable = false this[QUEUE] = new Yallist() this[BUFFER] = null this[READENTRY] = null this[WRITEENTRY] = null this[STATE] = 'begin' this[META] = '' this[EX] = null this[GEX] = null this[ENDED] = false this[UNZIP] = null this[ABORTED] = false this[SAW_NULL_BLOCK] = false this[SAW_EOF] = false this.on('end', () => this[CLOSESTREAM]()) if (typeof opt.onwarn === 'function') { this.on('warn', opt.onwarn) } if (typeof opt.onentry === 'function') { this.on('entry', opt.onentry) } } [CONSUMEHEADER] (chunk, position) { if (this[SAW_VALID_ENTRY] === null) { this[SAW_VALID_ENTRY] = false } let header try { header = new Header(chunk, position, this[EX], this[GEX]) } catch (er) { return this.warn('TAR_ENTRY_INVALID', er) } if (header.nullBlock) { if (this[SAW_NULL_BLOCK]) { this[SAW_EOF] = true // ending an archive with no entries. pointless, but legal. if (this[STATE] === 'begin') { this[STATE] = 'header' } this[EMIT]('eof') } else { this[SAW_NULL_BLOCK] = true this[EMIT]('nullBlock') } } else { this[SAW_NULL_BLOCK] = false if (!header.cksumValid) { this.warn('TAR_ENTRY_INVALID', 'checksum failure', { header }) } else if (!header.path) { this.warn('TAR_ENTRY_INVALID', 'path is required', { header }) } else { const type = header.type if (/^(Symbolic)?Link$/.test(type) && !header.linkpath) { this.warn('TAR_ENTRY_INVALID', 'linkpath required', { header }) } else if (!/^(Symbolic)?Link$/.test(type) && header.linkpath) { this.warn('TAR_ENTRY_INVALID', 'linkpath forbidden', { header }) } else { const entry = this[WRITEENTRY] = new Entry(header, this[EX], this[GEX]) // we do this for meta & ignored entries as well, because they // are still valid tar, or else we wouldn't know to ignore them if (!this[SAW_VALID_ENTRY]) { if (entry.remain) { // this might be the one! const onend = () => { if (!entry.invalid) { this[SAW_VALID_ENTRY] = true } } entry.on('end', onend) } else { this[SAW_VALID_ENTRY] = true } } if (entry.meta) { if (entry.size > this.maxMetaEntrySize) { entry.ignore = true this[EMIT]('ignoredEntry', entry) this[STATE] = 'ignore' entry.resume() } else if (entry.size > 0) { this[META] = '' entry.on('data', c => this[META] += c) this[STATE] = 'meta' } } else { this[EX] = null entry.ignore = entry.ignore || !this.filter(entry.path, entry) if (entry.ignore) { // probably valid, just not something we care about this[EMIT]('ignoredEntry', entry) this[STATE] = entry.remain ? 'ignore' : 'header' entry.resume() } else { if (entry.remain) { this[STATE] = 'body' } else { this[STATE] = 'header' entry.end() } if (!this[READENTRY]) { this[QUEUE].push(entry) this[NEXTENTRY]() } else { this[QUEUE].push(entry) } } } } } } } [CLOSESTREAM] () { nextTick(() => this.emit('close')) } [PROCESSENTRY] (entry) { let go = true if (!entry) { this[READENTRY] = null go = false } else if (Array.isArray(entry)) { this.emit.apply(this, entry) } else { this[READENTRY] = entry this.emit('entry', entry) if (!entry.emittedEnd) { entry.on('end', _ => this[NEXTENTRY]()) go = false } } return go } [NEXTENTRY] () { do {} while (this[PROCESSENTRY](this[QUEUE].shift())) if (!this[QUEUE].length) { // At this point, there's nothing in the queue, but we may have an // entry which is being consumed (readEntry). // If we don't, then we definitely can handle more data. // If we do, and either it's flowing, or it has never had any data // written to it, then it needs more. // The only other possibility is that it has returned false from a // write() call, so we wait for the next drain to continue. const re = this[READENTRY] const drainNow = !re || re.flowing || re.size === re.remain if (drainNow) { if (!this[WRITING]) { this.emit('drain') } } else { re.once('drain', _ => this.emit('drain')) } } } [CONSUMEBODY] (chunk, position) { // write up to but no more than writeEntry.blockRemain const entry = this[WRITEENTRY] const br = entry.blockRemain const c = (br >= chunk.length && position === 0) ? chunk : chunk.slice(position, position + br) entry.write(c) if (!entry.blockRemain) { this[STATE] = 'header' this[WRITEENTRY] = null entry.end() } return c.length } [CONSUMEMETA] (chunk, position) { const entry = this[WRITEENTRY] const ret = this[CONSUMEBODY](chunk, position) // if we finished, then the entry is reset if (!this[WRITEENTRY]) { this[EMITMETA](entry) } return ret } [EMIT] (ev, data, extra) { if (!this[QUEUE].length && !this[READENTRY]) { this.emit(ev, data, extra) } else { this[QUEUE].push([ev, data, extra]) } } [EMITMETA] (entry) { this[EMIT]('meta', this[META]) switch (entry.type) { case 'ExtendedHeader': case 'OldExtendedHeader': this[EX] = Pax.parse(this[META], this[EX], false) break case 'GlobalExtendedHeader': this[GEX] = Pax.parse(this[META], this[GEX], true) break case 'NextFileHasLongPath': case 'OldGnuLongPath': this[EX] = this[EX] || Object.create(null) this[EX].path = this[META].replace(/\0.*/, '') break case 'NextFileHasLongLinkpath': this[EX] = this[EX] || Object.create(null) this[EX].linkpath = this[META].replace(/\0.*/, '') break /* istanbul ignore next */ default: throw new Error('unknown meta: ' + entry.type) } } abort (error) { this[ABORTED] = true this.emit('abort', error) // always throws, even in non-strict mode this.warn('TAR_ABORT', error, { recoverable: false }) } write (chunk) { if (this[ABORTED]) { return } // first write, might be gzipped const needSniff = this[UNZIP] === null || this.brotli === undefined && this[UNZIP] === false if (needSniff && chunk) { if (this[BUFFER]) { chunk = Buffer.concat([this[BUFFER], chunk]) this[BUFFER] = null } if (chunk.length < gzipHeader.length) { this[BUFFER] = chunk return true } // look for gzip header for (let i = 0; this[UNZIP] === null && i < gzipHeader.length; i++) { if (chunk[i] !== gzipHeader[i]) { this[UNZIP] = false } } const maybeBrotli = this.brotli === undefined if (this[UNZIP] === false && maybeBrotli) { // read the first header to see if it's a valid tar file. If so, // we can safely assume that it's not actually brotli, despite the // .tbr or .tar.br file extension. // if we ended before getting a full chunk, yes, def brotli if (chunk.length < 512) { if (this[ENDED]) { this.brotli = true } else { this[BUFFER] = chunk return true } } else { // if it's tar, it's pretty reliably not brotli, chances of // that happening are astronomical. try { new Header(chunk.slice(0, 512)) this.brotli = false } catch (_) { this.brotli = true } } } if (this[UNZIP] === null || (this[UNZIP] === false && this.brotli)) { const ended = this[ENDED] this[ENDED] = false this[UNZIP] = this[UNZIP] === null ? new zlib.Unzip() : new zlib.BrotliDecompress() this[UNZIP].on('data', chunk => this[CONSUMECHUNK](chunk)) this[UNZIP].on('error', er => this.abort(er)) this[UNZIP].on('end', _ => { this[ENDED] = true this[CONSUMECHUNK]() }) this[WRITING] = true const ret = this[UNZIP][ended ? 'end' : 'write'](chunk) this[WRITING] = false return ret } } this[WRITING] = true if (this[UNZIP]) { this[UNZIP].write(chunk) } else { this[CONSUMECHUNK](chunk) } this[WRITING] = false // return false if there's a queue, or if the current entry isn't flowing const ret = this[QUEUE].length ? false : this[READENTRY] ? this[READENTRY].flowing : true // if we have no queue, then that means a clogged READENTRY if (!ret && !this[QUEUE].length) { this[READENTRY].once('drain', _ => this.emit('drain')) } return ret } [BUFFERCONCAT] (c) { if (c && !this[ABORTED]) { this[BUFFER] = this[BUFFER] ? Buffer.concat([this[BUFFER], c]) : c } } [MAYBEEND] () { if (this[ENDED] && !this[EMITTEDEND] && !this[ABORTED] && !this[CONSUMING]) { this[EMITTEDEND] = true const entry = this[WRITEENTRY] if (entry && entry.blockRemain) { // truncated, likely a damaged file const have = this[BUFFER] ? this[BUFFER].length : 0 this.warn('TAR_BAD_ARCHIVE', `Truncated input (needed ${ entry.blockRemain} more bytes, only ${have} available)`, { entry }) if (this[BUFFER]) { entry.write(this[BUFFER]) } entry.end() } this[EMIT](DONE) } } [CONSUMECHUNK] (chunk) { if (this[CONSUMING]) { this[BUFFERCONCAT](chunk) } else if (!chunk && !this[BUFFER]) { this[MAYBEEND]() } else { this[CONSUMING] = true if (this[BUFFER]) { this[BUFFERCONCAT](chunk) const c = this[BUFFER] this[BUFFER] = null this[CONSUMECHUNKSUB](c) } else { this[CONSUMECHUNKSUB](chunk) } while (this[BUFFER] && this[BUFFER].length >= 512 && !this[ABORTED] && !this[SAW_EOF]) { const c = this[BUFFER] this[BUFFER] = null this[CONSUMECHUNKSUB](c) } this[CONSUMING] = false } if (!this[BUFFER] || this[ENDED]) { this[MAYBEEND]() } } [CONSUMECHUNKSUB] (chunk) { // we know that we are in CONSUMING mode, so anything written goes into // the buffer. Advance the position and put any remainder in the buffer. let position = 0 const length = chunk.length while (position + 512 <= length && !this[ABORTED] && !this[SAW_EOF]) { switch (this[STATE]) { case 'begin': case 'header': this[CONSUMEHEADER](chunk, position) position += 512 break case 'ignore': case 'body': position += this[CONSUMEBODY](chunk, position) break case 'meta': position += this[CONSUMEMETA](chunk, position) break /* istanbul ignore next */ default: throw new Error('invalid state: ' + this[STATE]) } } if (position < length) { if (this[BUFFER]) { this[BUFFER] = Buffer.concat([chunk.slice(position), this[BUFFER]]) } else { this[BUFFER] = chunk.slice(position) } } } end (chunk) { if (!this[ABORTED]) { if (this[UNZIP]) { this[UNZIP].end(chunk) } else { this[ENDED] = true if (this.brotli === undefined) chunk = chunk || Buffer.alloc(0) this.write(chunk) } } } }) PK ~\'!tar/lib/strip-trailing-slashes.jsnu[// warning: extremely hot code path. // This has been meticulously optimized for use // within npm install on large package trees. // Do not edit without careful benchmarking. module.exports = str => { let i = str.length - 1 let slashesStart = -1 while (i > -1 && str.charAt(i) === '/') { slashesStart = i i-- } return slashesStart === -1 ? str : str.slice(0, slashesStart) } PK ~\Jtar/lib/replace.jsnu['use strict' // tar -r const hlo = require('./high-level-opt.js') const Pack = require('./pack.js') const fs = require('fs') const fsm = require('fs-minipass') const t = require('./list.js') const path = require('path') // starting at the head of the file, read a Header // If the checksum is invalid, that's our position to start writing // If it is, jump forward by the specified size (round up to 512) // and try again. // Write the new Pack stream starting there. const Header = require('./header.js') module.exports = (opt_, files, cb) => { const opt = hlo(opt_) if (!opt.file) { throw new TypeError('file is required') } if (opt.gzip || opt.brotli || opt.file.endsWith('.br') || opt.file.endsWith('.tbr')) { throw new TypeError('cannot append to compressed archives') } if (!files || !Array.isArray(files) || !files.length) { throw new TypeError('no files or directories specified') } files = Array.from(files) return opt.sync ? replaceSync(opt, files) : replace(opt, files, cb) } const replaceSync = (opt, files) => { const p = new Pack.Sync(opt) let threw = true let fd let position try { try { fd = fs.openSync(opt.file, 'r+') } catch (er) { if (er.code === 'ENOENT') { fd = fs.openSync(opt.file, 'w+') } else { throw er } } const st = fs.fstatSync(fd) const headBuf = Buffer.alloc(512) POSITION: for (position = 0; position < st.size; position += 512) { for (let bufPos = 0, bytes = 0; bufPos < 512; bufPos += bytes) { bytes = fs.readSync( fd, headBuf, bufPos, headBuf.length - bufPos, position + bufPos ) if (position === 0 && headBuf[0] === 0x1f && headBuf[1] === 0x8b) { throw new Error('cannot append to compressed archives') } if (!bytes) { break POSITION } } const h = new Header(headBuf) if (!h.cksumValid) { break } const entryBlockSize = 512 * Math.ceil(h.size / 512) if (position + entryBlockSize + 512 > st.size) { break } // the 512 for the header we just parsed will be added as well // also jump ahead all the blocks for the body position += entryBlockSize if (opt.mtimeCache) { opt.mtimeCache.set(h.path, h.mtime) } } threw = false streamSync(opt, p, position, fd, files) } finally { if (threw) { try { fs.closeSync(fd) } catch (er) {} } } } const streamSync = (opt, p, position, fd, files) => { const stream = new fsm.WriteStreamSync(opt.file, { fd: fd, start: position, }) p.pipe(stream) addFilesSync(p, files) } const replace = (opt, files, cb) => { files = Array.from(files) const p = new Pack(opt) const getPos = (fd, size, cb_) => { const cb = (er, pos) => { if (er) { fs.close(fd, _ => cb_(er)) } else { cb_(null, pos) } } let position = 0 if (size === 0) { return cb(null, 0) } let bufPos = 0 const headBuf = Buffer.alloc(512) const onread = (er, bytes) => { if (er) { return cb(er) } bufPos += bytes if (bufPos < 512 && bytes) { return fs.read( fd, headBuf, bufPos, headBuf.length - bufPos, position + bufPos, onread ) } if (position === 0 && headBuf[0] === 0x1f && headBuf[1] === 0x8b) { return cb(new Error('cannot append to compressed archives')) } // truncated header if (bufPos < 512) { return cb(null, position) } const h = new Header(headBuf) if (!h.cksumValid) { return cb(null, position) } const entryBlockSize = 512 * Math.ceil(h.size / 512) if (position + entryBlockSize + 512 > size) { return cb(null, position) } position += entryBlockSize + 512 if (position >= size) { return cb(null, position) } if (opt.mtimeCache) { opt.mtimeCache.set(h.path, h.mtime) } bufPos = 0 fs.read(fd, headBuf, 0, 512, position, onread) } fs.read(fd, headBuf, 0, 512, position, onread) } const promise = new Promise((resolve, reject) => { p.on('error', reject) let flag = 'r+' const onopen = (er, fd) => { if (er && er.code === 'ENOENT' && flag === 'r+') { flag = 'w+' return fs.open(opt.file, flag, onopen) } if (er) { return reject(er) } fs.fstat(fd, (er, st) => { if (er) { return fs.close(fd, () => reject(er)) } getPos(fd, st.size, (er, position) => { if (er) { return reject(er) } const stream = new fsm.WriteStream(opt.file, { fd: fd, start: position, }) p.pipe(stream) stream.on('error', reject) stream.on('close', resolve) addFilesAsync(p, files) }) }) } fs.open(opt.file, flag, onopen) }) return cb ? promise.then(cb, cb) : promise } const addFilesSync = (p, files) => { files.forEach(file => { if (file.charAt(0) === '@') { t({ file: path.resolve(p.cwd, file.slice(1)), sync: true, noResume: true, onentry: entry => p.add(entry), }) } else { p.add(file) } }) p.end() } const addFilesAsync = (p, files) => { while (files.length) { const file = files.shift() if (file.charAt(0) === '@') { return t({ file: path.resolve(p.cwd, file.slice(1)), noResume: true, onentry: entry => p.add(entry), }).then(_ => addFilesAsync(p, files)) } else { p.add(file) } } p.end() } PK ~\ʊtar/lib/high-level-opt.jsnu['use strict' // turn tar(1) style args like `C` into the more verbose things like `cwd` const argmap = new Map([ ['C', 'cwd'], ['f', 'file'], ['z', 'gzip'], ['P', 'preservePaths'], ['U', 'unlink'], ['strip-components', 'strip'], ['stripComponents', 'strip'], ['keep-newer', 'newer'], ['keepNewer', 'newer'], ['keep-newer-files', 'newer'], ['keepNewerFiles', 'newer'], ['k', 'keep'], ['keep-existing', 'keep'], ['keepExisting', 'keep'], ['m', 'noMtime'], ['no-mtime', 'noMtime'], ['p', 'preserveOwner'], ['L', 'follow'], ['h', 'follow'], ]) module.exports = opt => opt ? Object.keys(opt).map(k => [ argmap.has(k) ? argmap.get(k) : k, opt[k], ]).reduce((set, kv) => (set[kv[0]] = kv[1], set), Object.create(null)) : {} PK ~\!tar/lib/normalize-windows-path.jsnu[// on windows, either \ or / are valid directory separators. // on unix, \ is a valid character in filenames. // so, on windows, and only on windows, we replace all \ chars with /, // so that we can use / as our one and only directory separator char. const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform module.exports = platform !== 'win32' ? p => p : p => p && p.replace(/\\/g, '/') PK ~\n]tar/lib/pax.jsnu['use strict' const Header = require('./header.js') const path = require('path') class Pax { constructor (obj, global) { this.atime = obj.atime || null this.charset = obj.charset || null this.comment = obj.comment || null this.ctime = obj.ctime || null this.gid = obj.gid || null this.gname = obj.gname || null this.linkpath = obj.linkpath || null this.mtime = obj.mtime || null this.path = obj.path || null this.size = obj.size || null this.uid = obj.uid || null this.uname = obj.uname || null this.dev = obj.dev || null this.ino = obj.ino || null this.nlink = obj.nlink || null this.global = global || false } encode () { const body = this.encodeBody() if (body === '') { return null } const bodyLen = Buffer.byteLength(body) // round up to 512 bytes // add 512 for header const bufLen = 512 * Math.ceil(1 + bodyLen / 512) const buf = Buffer.allocUnsafe(bufLen) // 0-fill the header section, it might not hit every field for (let i = 0; i < 512; i++) { buf[i] = 0 } new Header({ // XXX split the path // then the path should be PaxHeader + basename, but less than 99, // prepend with the dirname path: ('PaxHeader/' + path.basename(this.path)).slice(0, 99), mode: this.mode || 0o644, uid: this.uid || null, gid: this.gid || null, size: bodyLen, mtime: this.mtime || null, type: this.global ? 'GlobalExtendedHeader' : 'ExtendedHeader', linkpath: '', uname: this.uname || '', gname: this.gname || '', devmaj: 0, devmin: 0, atime: this.atime || null, ctime: this.ctime || null, }).encode(buf) buf.write(body, 512, bodyLen, 'utf8') // null pad after the body for (let i = bodyLen + 512; i < buf.length; i++) { buf[i] = 0 } return buf } encodeBody () { return ( this.encodeField('path') + this.encodeField('ctime') + this.encodeField('atime') + this.encodeField('dev') + this.encodeField('ino') + this.encodeField('nlink') + this.encodeField('charset') + this.encodeField('comment') + this.encodeField('gid') + this.encodeField('gname') + this.encodeField('linkpath') + this.encodeField('mtime') + this.encodeField('size') + this.encodeField('uid') + this.encodeField('uname') ) } encodeField (field) { if (this[field] === null || this[field] === undefined) { return '' } const v = this[field] instanceof Date ? this[field].getTime() / 1000 : this[field] const s = ' ' + (field === 'dev' || field === 'ino' || field === 'nlink' ? 'SCHILY.' : '') + field + '=' + v + '\n' const byteLen = Buffer.byteLength(s) // the digits includes the length of the digits in ascii base-10 // so if it's 9 characters, then adding 1 for the 9 makes it 10 // which makes it 11 chars. let digits = Math.floor(Math.log(byteLen) / Math.log(10)) + 1 if (byteLen + digits >= Math.pow(10, digits)) { digits += 1 } const len = digits + byteLen return len + s } } Pax.parse = (string, ex, g) => new Pax(merge(parseKV(string), ex), g) const merge = (a, b) => b ? Object.keys(a).reduce((s, k) => (s[k] = a[k], s), b) : a const parseKV = string => string .replace(/\n$/, '') .split('\n') .reduce(parseKVLine, Object.create(null)) const parseKVLine = (set, line) => { const n = parseInt(line, 10) // XXX Values with \n in them will fail this. // Refactor to not be a naive line-by-line parse. if (n !== Buffer.byteLength(line) + 1) { return set } line = line.slice((n + ' ').length) const kv = line.split('=') const k = kv.shift().replace(/^SCHILY\.(dev|ino|nlink)/, '$1') if (!k) { return set } const v = kv.join('=') set[k] = /^([A-Z]+\.)?([mac]|birth|creation)time$/.test(k) ? new Date(v * 1000) : /^[0-9]+$/.test(v) ? +v : v return set } module.exports = Pax PK ~\ Ttar/lib/strip-absolute-path.jsnu[// unix absolute paths are also absolute on win32, so we use this for both const { isAbsolute, parse } = require('path').win32 // returns [root, stripped] // Note that windows will think that //x/y/z/a has a "root" of //x/y, and in // those cases, we want to sanitize it to x/y/z/a, not z/a, so we strip / // explicitly if it's the first character. // drive-specific relative paths on Windows get their root stripped off even // though they are not absolute, so `c:../foo` becomes ['c:', '../foo'] module.exports = path => { let r = '' let parsed = parse(path) while (isAbsolute(path) || parsed.root) { // windows will think that //x/y/z has a "root" of //x/y/ // but strip the //?/C:/ off of //?/C:/path const root = path.charAt(0) === '/' && path.slice(0, 4) !== '//?/' ? '/' : parsed.root path = path.slice(root.length) r += root parsed = parse(path) } return [r, path] } PK ~\tar/lib/large-numbers.jsnu['use strict' // Tar can encode large and negative numbers using a leading byte of // 0xff for negative, and 0x80 for positive. const encode = (num, buf) => { if (!Number.isSafeInteger(num)) { // The number is so large that javascript cannot represent it with integer // precision. throw Error('cannot encode number outside of javascript safe integer range') } else if (num < 0) { encodeNegative(num, buf) } else { encodePositive(num, buf) } return buf } const encodePositive = (num, buf) => { buf[0] = 0x80 for (var i = buf.length; i > 1; i--) { buf[i - 1] = num & 0xff num = Math.floor(num / 0x100) } } const encodeNegative = (num, buf) => { buf[0] = 0xff var flipped = false num = num * -1 for (var i = buf.length; i > 1; i--) { var byte = num & 0xff num = Math.floor(num / 0x100) if (flipped) { buf[i - 1] = onesComp(byte) } else if (byte === 0) { buf[i - 1] = 0 } else { flipped = true buf[i - 1] = twosComp(byte) } } } const parse = (buf) => { const pre = buf[0] const value = pre === 0x80 ? pos(buf.slice(1, buf.length)) : pre === 0xff ? twos(buf) : null if (value === null) { throw Error('invalid base256 encoding') } if (!Number.isSafeInteger(value)) { // The number is so large that javascript cannot represent it with integer // precision. throw Error('parsed number outside of javascript safe integer range') } return value } const twos = (buf) => { var len = buf.length var sum = 0 var flipped = false for (var i = len - 1; i > -1; i--) { var byte = buf[i] var f if (flipped) { f = onesComp(byte) } else if (byte === 0) { f = byte } else { flipped = true f = twosComp(byte) } if (f !== 0) { sum -= f * Math.pow(256, len - i - 1) } } return sum } const pos = (buf) => { var len = buf.length var sum = 0 for (var i = len - 1; i > -1; i--) { var byte = buf[i] if (byte !== 0) { sum += byte * Math.pow(256, len - i - 1) } } return sum } const onesComp = byte => (0xff ^ byte) & 0xff const twosComp = byte => ((0xff ^ byte) + 1) & 0xff module.exports = { encode, parse, } PK ~\;;tar/lib/write-entry.jsnu['use strict' const { Minipass } = require('minipass') const Pax = require('./pax.js') const Header = require('./header.js') const fs = require('fs') const path = require('path') const normPath = require('./normalize-windows-path.js') const stripSlash = require('./strip-trailing-slashes.js') const prefixPath = (path, prefix) => { if (!prefix) { return normPath(path) } path = normPath(path).replace(/^\.(\/|$)/, '') return stripSlash(prefix) + '/' + path } const maxReadSize = 16 * 1024 * 1024 const PROCESS = Symbol('process') const FILE = Symbol('file') const DIRECTORY = Symbol('directory') const SYMLINK = Symbol('symlink') const HARDLINK = Symbol('hardlink') const HEADER = Symbol('header') const READ = Symbol('read') const LSTAT = Symbol('lstat') const ONLSTAT = Symbol('onlstat') const ONREAD = Symbol('onread') const ONREADLINK = Symbol('onreadlink') const OPENFILE = Symbol('openfile') const ONOPENFILE = Symbol('onopenfile') const CLOSE = Symbol('close') const MODE = Symbol('mode') const AWAITDRAIN = Symbol('awaitDrain') const ONDRAIN = Symbol('ondrain') const PREFIX = Symbol('prefix') const HAD_ERROR = Symbol('hadError') const warner = require('./warn-mixin.js') const winchars = require('./winchars.js') const stripAbsolutePath = require('./strip-absolute-path.js') const modeFix = require('./mode-fix.js') const WriteEntry = warner(class WriteEntry extends Minipass { constructor (p, opt) { opt = opt || {} super(opt) if (typeof p !== 'string') { throw new TypeError('path is required') } this.path = normPath(p) // suppress atime, ctime, uid, gid, uname, gname this.portable = !!opt.portable // until node has builtin pwnam functions, this'll have to do this.myuid = process.getuid && process.getuid() || 0 this.myuser = process.env.USER || '' this.maxReadSize = opt.maxReadSize || maxReadSize this.linkCache = opt.linkCache || new Map() this.statCache = opt.statCache || new Map() this.preservePaths = !!opt.preservePaths this.cwd = normPath(opt.cwd || process.cwd()) this.strict = !!opt.strict this.noPax = !!opt.noPax this.noMtime = !!opt.noMtime this.mtime = opt.mtime || null this.prefix = opt.prefix ? normPath(opt.prefix) : null this.fd = null this.blockLen = null this.blockRemain = null this.buf = null this.offset = null this.length = null this.pos = null this.remain = null if (typeof opt.onwarn === 'function') { this.on('warn', opt.onwarn) } let pathWarn = false if (!this.preservePaths) { const [root, stripped] = stripAbsolutePath(this.path) if (root) { this.path = stripped pathWarn = root } } this.win32 = !!opt.win32 || process.platform === 'win32' if (this.win32) { // force the \ to / normalization, since we might not *actually* // be on windows, but want \ to be considered a path separator. this.path = winchars.decode(this.path.replace(/\\/g, '/')) p = p.replace(/\\/g, '/') } this.absolute = normPath(opt.absolute || path.resolve(this.cwd, p)) if (this.path === '') { this.path = './' } if (pathWarn) { this.warn('TAR_ENTRY_INFO', `stripping ${pathWarn} from absolute path`, { entry: this, path: pathWarn + this.path, }) } if (this.statCache.has(this.absolute)) { this[ONLSTAT](this.statCache.get(this.absolute)) } else { this[LSTAT]() } } emit (ev, ...data) { if (ev === 'error') { this[HAD_ERROR] = true } return super.emit(ev, ...data) } [LSTAT] () { fs.lstat(this.absolute, (er, stat) => { if (er) { return this.emit('error', er) } this[ONLSTAT](stat) }) } [ONLSTAT] (stat) { this.statCache.set(this.absolute, stat) this.stat = stat if (!stat.isFile()) { stat.size = 0 } this.type = getType(stat) this.emit('stat', stat) this[PROCESS]() } [PROCESS] () { switch (this.type) { case 'File': return this[FILE]() case 'Directory': return this[DIRECTORY]() case 'SymbolicLink': return this[SYMLINK]() // unsupported types are ignored. default: return this.end() } } [MODE] (mode) { return modeFix(mode, this.type === 'Directory', this.portable) } [PREFIX] (path) { return prefixPath(path, this.prefix) } [HEADER] () { if (this.type === 'Directory' && this.portable) { this.noMtime = true } this.header = new Header({ path: this[PREFIX](this.path), // only apply the prefix to hard links. linkpath: this.type === 'Link' ? this[PREFIX](this.linkpath) : this.linkpath, // only the permissions and setuid/setgid/sticky bitflags // not the higher-order bits that specify file type mode: this[MODE](this.stat.mode), uid: this.portable ? null : this.stat.uid, gid: this.portable ? null : this.stat.gid, size: this.stat.size, mtime: this.noMtime ? null : this.mtime || this.stat.mtime, type: this.type, uname: this.portable ? null : this.stat.uid === this.myuid ? this.myuser : '', atime: this.portable ? null : this.stat.atime, ctime: this.portable ? null : this.stat.ctime, }) if (this.header.encode() && !this.noPax) { super.write(new Pax({ atime: this.portable ? null : this.header.atime, ctime: this.portable ? null : this.header.ctime, gid: this.portable ? null : this.header.gid, mtime: this.noMtime ? null : this.mtime || this.header.mtime, path: this[PREFIX](this.path), linkpath: this.type === 'Link' ? this[PREFIX](this.linkpath) : this.linkpath, size: this.header.size, uid: this.portable ? null : this.header.uid, uname: this.portable ? null : this.header.uname, dev: this.portable ? null : this.stat.dev, ino: this.portable ? null : this.stat.ino, nlink: this.portable ? null : this.stat.nlink, }).encode()) } super.write(this.header.block) } [DIRECTORY] () { if (this.path.slice(-1) !== '/') { this.path += '/' } this.stat.size = 0 this[HEADER]() this.end() } [SYMLINK] () { fs.readlink(this.absolute, (er, linkpath) => { if (er) { return this.emit('error', er) } this[ONREADLINK](linkpath) }) } [ONREADLINK] (linkpath) { this.linkpath = normPath(linkpath) this[HEADER]() this.end() } [HARDLINK] (linkpath) { this.type = 'Link' this.linkpath = normPath(path.relative(this.cwd, linkpath)) this.stat.size = 0 this[HEADER]() this.end() } [FILE] () { if (this.stat.nlink > 1) { const linkKey = this.stat.dev + ':' + this.stat.ino if (this.linkCache.has(linkKey)) { const linkpath = this.linkCache.get(linkKey) if (linkpath.indexOf(this.cwd) === 0) { return this[HARDLINK](linkpath) } } this.linkCache.set(linkKey, this.absolute) } this[HEADER]() if (this.stat.size === 0) { return this.end() } this[OPENFILE]() } [OPENFILE] () { fs.open(this.absolute, 'r', (er, fd) => { if (er) { return this.emit('error', er) } this[ONOPENFILE](fd) }) } [ONOPENFILE] (fd) { this.fd = fd if (this[HAD_ERROR]) { return this[CLOSE]() } this.blockLen = 512 * Math.ceil(this.stat.size / 512) this.blockRemain = this.blockLen const bufLen = Math.min(this.blockLen, this.maxReadSize) this.buf = Buffer.allocUnsafe(bufLen) this.offset = 0 this.pos = 0 this.remain = this.stat.size this.length = this.buf.length this[READ]() } [READ] () { const { fd, buf, offset, length, pos } = this fs.read(fd, buf, offset, length, pos, (er, bytesRead) => { if (er) { // ignoring the error from close(2) is a bad practice, but at // this point we already have an error, don't need another one return this[CLOSE](() => this.emit('error', er)) } this[ONREAD](bytesRead) }) } [CLOSE] (cb) { fs.close(this.fd, cb) } [ONREAD] (bytesRead) { if (bytesRead <= 0 && this.remain > 0) { const er = new Error('encountered unexpected EOF') er.path = this.absolute er.syscall = 'read' er.code = 'EOF' return this[CLOSE](() => this.emit('error', er)) } if (bytesRead > this.remain) { const er = new Error('did not encounter expected EOF') er.path = this.absolute er.syscall = 'read' er.code = 'EOF' return this[CLOSE](() => this.emit('error', er)) } // null out the rest of the buffer, if we could fit the block padding // at the end of this loop, we've incremented bytesRead and this.remain // to be incremented up to the blockRemain level, as if we had expected // to get a null-padded file, and read it until the end. then we will // decrement both remain and blockRemain by bytesRead, and know that we // reached the expected EOF, without any null buffer to append. if (bytesRead === this.remain) { for (let i = bytesRead; i < this.length && bytesRead < this.blockRemain; i++) { this.buf[i + this.offset] = 0 bytesRead++ this.remain++ } } const writeBuf = this.offset === 0 && bytesRead === this.buf.length ? this.buf : this.buf.slice(this.offset, this.offset + bytesRead) const flushed = this.write(writeBuf) if (!flushed) { this[AWAITDRAIN](() => this[ONDRAIN]()) } else { this[ONDRAIN]() } } [AWAITDRAIN] (cb) { this.once('drain', cb) } write (writeBuf) { if (this.blockRemain < writeBuf.length) { const er = new Error('writing more data than expected') er.path = this.absolute return this.emit('error', er) } this.remain -= writeBuf.length this.blockRemain -= writeBuf.length this.pos += writeBuf.length this.offset += writeBuf.length return super.write(writeBuf) } [ONDRAIN] () { if (!this.remain) { if (this.blockRemain) { super.write(Buffer.alloc(this.blockRemain)) } return this[CLOSE](er => er ? this.emit('error', er) : this.end()) } if (this.offset >= this.length) { // if we only have a smaller bit left to read, alloc a smaller buffer // otherwise, keep it the same length it was before. this.buf = Buffer.allocUnsafe(Math.min(this.blockRemain, this.buf.length)) this.offset = 0 } this.length = this.buf.length - this.offset this[READ]() } }) class WriteEntrySync extends WriteEntry { [LSTAT] () { this[ONLSTAT](fs.lstatSync(this.absolute)) } [SYMLINK] () { this[ONREADLINK](fs.readlinkSync(this.absolute)) } [OPENFILE] () { this[ONOPENFILE](fs.openSync(this.absolute, 'r')) } [READ] () { let threw = true try { const { fd, buf, offset, length, pos } = this const bytesRead = fs.readSync(fd, buf, offset, length, pos) this[ONREAD](bytesRead) threw = false } finally { // ignoring the error from close(2) is a bad practice, but at // this point we already have an error, don't need another one if (threw) { try { this[CLOSE](() => {}) } catch (er) {} } } } [AWAITDRAIN] (cb) { cb() } [CLOSE] (cb) { fs.closeSync(this.fd) cb() } } const WriteEntryTar = warner(class WriteEntryTar extends Minipass { constructor (readEntry, opt) { opt = opt || {} super(opt) this.preservePaths = !!opt.preservePaths this.portable = !!opt.portable this.strict = !!opt.strict this.noPax = !!opt.noPax this.noMtime = !!opt.noMtime this.readEntry = readEntry this.type = readEntry.type if (this.type === 'Directory' && this.portable) { this.noMtime = true } this.prefix = opt.prefix || null this.path = normPath(readEntry.path) this.mode = this[MODE](readEntry.mode) this.uid = this.portable ? null : readEntry.uid this.gid = this.portable ? null : readEntry.gid this.uname = this.portable ? null : readEntry.uname this.gname = this.portable ? null : readEntry.gname this.size = readEntry.size this.mtime = this.noMtime ? null : opt.mtime || readEntry.mtime this.atime = this.portable ? null : readEntry.atime this.ctime = this.portable ? null : readEntry.ctime this.linkpath = normPath(readEntry.linkpath) if (typeof opt.onwarn === 'function') { this.on('warn', opt.onwarn) } let pathWarn = false if (!this.preservePaths) { const [root, stripped] = stripAbsolutePath(this.path) if (root) { this.path = stripped pathWarn = root } } this.remain = readEntry.size this.blockRemain = readEntry.startBlockSize this.header = new Header({ path: this[PREFIX](this.path), linkpath: this.type === 'Link' ? this[PREFIX](this.linkpath) : this.linkpath, // only the permissions and setuid/setgid/sticky bitflags // not the higher-order bits that specify file type mode: this.mode, uid: this.portable ? null : this.uid, gid: this.portable ? null : this.gid, size: this.size, mtime: this.noMtime ? null : this.mtime, type: this.type, uname: this.portable ? null : this.uname, atime: this.portable ? null : this.atime, ctime: this.portable ? null : this.ctime, }) if (pathWarn) { this.warn('TAR_ENTRY_INFO', `stripping ${pathWarn} from absolute path`, { entry: this, path: pathWarn + this.path, }) } if (this.header.encode() && !this.noPax) { super.write(new Pax({ atime: this.portable ? null : this.atime, ctime: this.portable ? null : this.ctime, gid: this.portable ? null : this.gid, mtime: this.noMtime ? null : this.mtime, path: this[PREFIX](this.path), linkpath: this.type === 'Link' ? this[PREFIX](this.linkpath) : this.linkpath, size: this.size, uid: this.portable ? null : this.uid, uname: this.portable ? null : this.uname, dev: this.portable ? null : this.readEntry.dev, ino: this.portable ? null : this.readEntry.ino, nlink: this.portable ? null : this.readEntry.nlink, }).encode()) } super.write(this.header.block) readEntry.pipe(this) } [PREFIX] (path) { return prefixPath(path, this.prefix) } [MODE] (mode) { return modeFix(mode, this.type === 'Directory', this.portable) } write (data) { const writeLen = data.length if (writeLen > this.blockRemain) { throw new Error('writing more to entry than is appropriate') } this.blockRemain -= writeLen return super.write(data) } end () { if (this.blockRemain) { super.write(Buffer.alloc(this.blockRemain)) } return super.end() } }) WriteEntry.Sync = WriteEntrySync WriteEntry.Tar = WriteEntryTar const getType = stat => stat.isFile() ? 'File' : stat.isDirectory() ? 'Directory' : stat.isSymbolicLink() ? 'SymbolicLink' : 'Unsupported' module.exports = WriteEntry PK ~\tar/lib/warn-mixin.jsnu['use strict' module.exports = Base => class extends Base { warn (code, message, data = {}) { if (this.file) { data.file = this.file } if (this.cwd) { data.cwd = this.cwd } data.code = message instanceof Error && message.code || code data.tarCode = code if (!this.strict && data.recoverable !== false) { if (message instanceof Error) { data = Object.assign(message, data) message = message.message } this.emit('warn', data.tarCode, message, data) } else if (message instanceof Error) { this.emit('error', Object.assign(message, data)) } else { this.emit('error', Object.assign(new Error(`${code}: ${message}`), data)) } } } PK ~\z%'%'tar/lib/pack.jsnu['use strict' // A readable tar stream creator // Technically, this is a transform stream that you write paths into, // and tar format comes out of. // The `add()` method is like `write()` but returns this, // and end() return `this` as well, so you can // do `new Pack(opt).add('files').add('dir').end().pipe(output) // You could also do something like: // streamOfPaths().pipe(new Pack()).pipe(new fs.WriteStream('out.tar')) class PackJob { constructor (path, absolute) { this.path = path || './' this.absolute = absolute this.entry = null this.stat = null this.readdir = null this.pending = false this.ignore = false this.piped = false } } const { Minipass } = require('minipass') const zlib = require('minizlib') const ReadEntry = require('./read-entry.js') const WriteEntry = require('./write-entry.js') const WriteEntrySync = WriteEntry.Sync const WriteEntryTar = WriteEntry.Tar const Yallist = require('yallist') const EOF = Buffer.alloc(1024) const ONSTAT = Symbol('onStat') const ENDED = Symbol('ended') const QUEUE = Symbol('queue') const CURRENT = Symbol('current') const PROCESS = Symbol('process') const PROCESSING = Symbol('processing') const PROCESSJOB = Symbol('processJob') const JOBS = Symbol('jobs') const JOBDONE = Symbol('jobDone') const ADDFSENTRY = Symbol('addFSEntry') const ADDTARENTRY = Symbol('addTarEntry') const STAT = Symbol('stat') const READDIR = Symbol('readdir') const ONREADDIR = Symbol('onreaddir') const PIPE = Symbol('pipe') const ENTRY = Symbol('entry') const ENTRYOPT = Symbol('entryOpt') const WRITEENTRYCLASS = Symbol('writeEntryClass') const WRITE = Symbol('write') const ONDRAIN = Symbol('ondrain') const fs = require('fs') const path = require('path') const warner = require('./warn-mixin.js') const normPath = require('./normalize-windows-path.js') const Pack = warner(class Pack extends Minipass { constructor (opt) { super(opt) opt = opt || Object.create(null) this.opt = opt this.file = opt.file || '' this.cwd = opt.cwd || process.cwd() this.maxReadSize = opt.maxReadSize this.preservePaths = !!opt.preservePaths this.strict = !!opt.strict this.noPax = !!opt.noPax this.prefix = normPath(opt.prefix || '') this.linkCache = opt.linkCache || new Map() this.statCache = opt.statCache || new Map() this.readdirCache = opt.readdirCache || new Map() this[WRITEENTRYCLASS] = WriteEntry if (typeof opt.onwarn === 'function') { this.on('warn', opt.onwarn) } this.portable = !!opt.portable this.zip = null if (opt.gzip || opt.brotli) { if (opt.gzip && opt.brotli) { throw new TypeError('gzip and brotli are mutually exclusive') } if (opt.gzip) { if (typeof opt.gzip !== 'object') { opt.gzip = {} } if (this.portable) { opt.gzip.portable = true } this.zip = new zlib.Gzip(opt.gzip) } if (opt.brotli) { if (typeof opt.brotli !== 'object') { opt.brotli = {} } this.zip = new zlib.BrotliCompress(opt.brotli) } this.zip.on('data', chunk => super.write(chunk)) this.zip.on('end', _ => super.end()) this.zip.on('drain', _ => this[ONDRAIN]()) this.on('resume', _ => this.zip.resume()) } else { this.on('drain', this[ONDRAIN]) } this.noDirRecurse = !!opt.noDirRecurse this.follow = !!opt.follow this.noMtime = !!opt.noMtime this.mtime = opt.mtime || null this.filter = typeof opt.filter === 'function' ? opt.filter : _ => true this[QUEUE] = new Yallist() this[JOBS] = 0 this.jobs = +opt.jobs || 4 this[PROCESSING] = false this[ENDED] = false } [WRITE] (chunk) { return super.write(chunk) } add (path) { this.write(path) return this } end (path) { if (path) { this.write(path) } this[ENDED] = true this[PROCESS]() return this } write (path) { if (this[ENDED]) { throw new Error('write after end') } if (path instanceof ReadEntry) { this[ADDTARENTRY](path) } else { this[ADDFSENTRY](path) } return this.flowing } [ADDTARENTRY] (p) { const absolute = normPath(path.resolve(this.cwd, p.path)) // in this case, we don't have to wait for the stat if (!this.filter(p.path, p)) { p.resume() } else { const job = new PackJob(p.path, absolute, false) job.entry = new WriteEntryTar(p, this[ENTRYOPT](job)) job.entry.on('end', _ => this[JOBDONE](job)) this[JOBS] += 1 this[QUEUE].push(job) } this[PROCESS]() } [ADDFSENTRY] (p) { const absolute = normPath(path.resolve(this.cwd, p)) this[QUEUE].push(new PackJob(p, absolute)) this[PROCESS]() } [STAT] (job) { job.pending = true this[JOBS] += 1 const stat = this.follow ? 'stat' : 'lstat' fs[stat](job.absolute, (er, stat) => { job.pending = false this[JOBS] -= 1 if (er) { this.emit('error', er) } else { this[ONSTAT](job, stat) } }) } [ONSTAT] (job, stat) { this.statCache.set(job.absolute, stat) job.stat = stat // now we have the stat, we can filter it. if (!this.filter(job.path, stat)) { job.ignore = true } this[PROCESS]() } [READDIR] (job) { job.pending = true this[JOBS] += 1 fs.readdir(job.absolute, (er, entries) => { job.pending = false this[JOBS] -= 1 if (er) { return this.emit('error', er) } this[ONREADDIR](job, entries) }) } [ONREADDIR] (job, entries) { this.readdirCache.set(job.absolute, entries) job.readdir = entries this[PROCESS]() } [PROCESS] () { if (this[PROCESSING]) { return } this[PROCESSING] = true for (let w = this[QUEUE].head; w !== null && this[JOBS] < this.jobs; w = w.next) { this[PROCESSJOB](w.value) if (w.value.ignore) { const p = w.next this[QUEUE].removeNode(w) w.next = p } } this[PROCESSING] = false if (this[ENDED] && !this[QUEUE].length && this[JOBS] === 0) { if (this.zip) { this.zip.end(EOF) } else { super.write(EOF) super.end() } } } get [CURRENT] () { return this[QUEUE] && this[QUEUE].head && this[QUEUE].head.value } [JOBDONE] (job) { this[QUEUE].shift() this[JOBS] -= 1 this[PROCESS]() } [PROCESSJOB] (job) { if (job.pending) { return } if (job.entry) { if (job === this[CURRENT] && !job.piped) { this[PIPE](job) } return } if (!job.stat) { if (this.statCache.has(job.absolute)) { this[ONSTAT](job, this.statCache.get(job.absolute)) } else { this[STAT](job) } } if (!job.stat) { return } // filtered out! if (job.ignore) { return } if (!this.noDirRecurse && job.stat.isDirectory() && !job.readdir) { if (this.readdirCache.has(job.absolute)) { this[ONREADDIR](job, this.readdirCache.get(job.absolute)) } else { this[READDIR](job) } if (!job.readdir) { return } } // we know it doesn't have an entry, because that got checked above job.entry = this[ENTRY](job) if (!job.entry) { job.ignore = true return } if (job === this[CURRENT] && !job.piped) { this[PIPE](job) } } [ENTRYOPT] (job) { return { onwarn: (code, msg, data) => this.warn(code, msg, data), noPax: this.noPax, cwd: this.cwd, absolute: job.absolute, preservePaths: this.preservePaths, maxReadSize: this.maxReadSize, strict: this.strict, portable: this.portable, linkCache: this.linkCache, statCache: this.statCache, noMtime: this.noMtime, mtime: this.mtime, prefix: this.prefix, } } [ENTRY] (job) { this[JOBS] += 1 try { return new this[WRITEENTRYCLASS](job.path, this[ENTRYOPT](job)) .on('end', () => this[JOBDONE](job)) .on('error', er => this.emit('error', er)) } catch (er) { this.emit('error', er) } } [ONDRAIN] () { if (this[CURRENT] && this[CURRENT].entry) { this[CURRENT].entry.resume() } } // like .pipe() but using super, because our write() is special [PIPE] (job) { job.piped = true if (job.readdir) { job.readdir.forEach(entry => { const p = job.path const base = p === './' ? '' : p.replace(/\/*$/, '/') this[ADDFSENTRY](base + entry) }) } const source = job.entry const zip = this.zip if (zip) { source.on('data', chunk => { if (!zip.write(chunk)) { source.pause() } }) } else { source.on('data', chunk => { if (!super.write(chunk)) { source.pause() } }) } } pause () { if (this.zip) { this.zip.pause() } return super.pause() } }) class PackSync extends Pack { constructor (opt) { super(opt) this[WRITEENTRYCLASS] = WriteEntrySync } // pause/resume are no-ops in sync streams. pause () {} resume () {} [STAT] (job) { const stat = this.follow ? 'statSync' : 'lstatSync' this[ONSTAT](job, fs[stat](job.absolute)) } [READDIR] (job, stat) { this[ONREADDIR](job, fs.readdirSync(job.absolute)) } // gotta get it all in this tick [PIPE] (job) { const source = job.entry const zip = this.zip if (job.readdir) { job.readdir.forEach(entry => { const p = job.path const base = p === './' ? '' : p.replace(/\/*$/, '/') this[ADDFSENTRY](base + entry) }) } if (zip) { source.on('data', chunk => { zip.write(chunk) }) } else { source.on('data', chunk => { super[WRITE](chunk) }) } } } Pack.Sync = PackSync module.exports = Pack PK ~\ [ [ tar/lib/create.jsnu['use strict' // tar -c const hlo = require('./high-level-opt.js') const Pack = require('./pack.js') const fsm = require('fs-minipass') const t = require('./list.js') const path = require('path') module.exports = (opt_, files, cb) => { if (typeof files === 'function') { cb = files } if (Array.isArray(opt_)) { files = opt_, opt_ = {} } if (!files || !Array.isArray(files) || !files.length) { throw new TypeError('no files or directories specified') } files = Array.from(files) const opt = hlo(opt_) if (opt.sync && typeof cb === 'function') { throw new TypeError('callback not supported for sync tar functions') } if (!opt.file && typeof cb === 'function') { throw new TypeError('callback only supported with file option') } return opt.file && opt.sync ? createFileSync(opt, files) : opt.file ? createFile(opt, files, cb) : opt.sync ? createSync(opt, files) : create(opt, files) } const createFileSync = (opt, files) => { const p = new Pack.Sync(opt) const stream = new fsm.WriteStreamSync(opt.file, { mode: opt.mode || 0o666, }) p.pipe(stream) addFilesSync(p, files) } const createFile = (opt, files, cb) => { const p = new Pack(opt) const stream = new fsm.WriteStream(opt.file, { mode: opt.mode || 0o666, }) p.pipe(stream) const promise = new Promise((res, rej) => { stream.on('error', rej) stream.on('close', res) p.on('error', rej) }) addFilesAsync(p, files) return cb ? promise.then(cb, cb) : promise } const addFilesSync = (p, files) => { files.forEach(file => { if (file.charAt(0) === '@') { t({ file: path.resolve(p.cwd, file.slice(1)), sync: true, noResume: true, onentry: entry => p.add(entry), }) } else { p.add(file) } }) p.end() } const addFilesAsync = (p, files) => { while (files.length) { const file = files.shift() if (file.charAt(0) === '@') { return t({ file: path.resolve(p.cwd, file.slice(1)), noResume: true, onentry: entry => p.add(entry), }).then(_ => addFilesAsync(p, files)) } else { p.add(file) } } p.end() } const createSync = (opt, files) => { const p = new Pack.Sync(opt) addFilesSync(p, files) return p } const create = (opt, files) => { const p = new Pack(opt) addFilesAsync(p, files) return p } PK ~\`ĉtar/lib/mode-fix.jsnu['use strict' module.exports = (mode, isDir, portable) => { mode &= 0o7777 // in portable mode, use the minimum reasonable umask // if this system creates files with 0o664 by default // (as some linux distros do), then we'll write the // archive with 0o644 instead. Also, don't ever create // a file that is not readable/writable by the owner. if (portable) { mode = (mode | 0o600) & ~0o22 } // if dirs are readable, then they should be listable if (isDir) { if (mode & 0o400) { mode |= 0o100 } if (mode & 0o40) { mode |= 0o10 } if (mode & 0o4) { mode |= 0o1 } } return mode } PK ~\}Qmmtar/lib/mkdir.jsnu['use strict' // wrapper around mkdirp for tar's needs. // TODO: This should probably be a class, not functionally // passing around state in a gazillion args. const mkdirp = require('mkdirp') const fs = require('fs') const path = require('path') const chownr = require('chownr') const normPath = require('./normalize-windows-path.js') class SymlinkError extends Error { constructor (symlink, path) { super('Cannot extract through symbolic link') this.path = path this.symlink = symlink } get name () { return 'SylinkError' } } class CwdError extends Error { constructor (path, code) { super(code + ': Cannot cd into \'' + path + '\'') this.path = path this.code = code } get name () { return 'CwdError' } } const cGet = (cache, key) => cache.get(normPath(key)) const cSet = (cache, key, val) => cache.set(normPath(key), val) const checkCwd = (dir, cb) => { fs.stat(dir, (er, st) => { if (er || !st.isDirectory()) { er = new CwdError(dir, er && er.code || 'ENOTDIR') } cb(er) }) } module.exports = (dir, opt, cb) => { dir = normPath(dir) // if there's any overlap between mask and mode, // then we'll need an explicit chmod const umask = opt.umask const mode = opt.mode | 0o0700 const needChmod = (mode & umask) !== 0 const uid = opt.uid const gid = opt.gid const doChown = typeof uid === 'number' && typeof gid === 'number' && (uid !== opt.processUid || gid !== opt.processGid) const preserve = opt.preserve const unlink = opt.unlink const cache = opt.cache const cwd = normPath(opt.cwd) const done = (er, created) => { if (er) { cb(er) } else { cSet(cache, dir, true) if (created && doChown) { chownr(created, uid, gid, er => done(er)) } else if (needChmod) { fs.chmod(dir, mode, cb) } else { cb() } } } if (cache && cGet(cache, dir) === true) { return done() } if (dir === cwd) { return checkCwd(dir, done) } if (preserve) { return mkdirp(dir, { mode }).then(made => done(null, made), done) } const sub = normPath(path.relative(cwd, dir)) const parts = sub.split('/') mkdir_(cwd, parts, mode, cache, unlink, cwd, null, done) } const mkdir_ = (base, parts, mode, cache, unlink, cwd, created, cb) => { if (!parts.length) { return cb(null, created) } const p = parts.shift() const part = normPath(path.resolve(base + '/' + p)) if (cGet(cache, part)) { return mkdir_(part, parts, mode, cache, unlink, cwd, created, cb) } fs.mkdir(part, mode, onmkdir(part, parts, mode, cache, unlink, cwd, created, cb)) } const onmkdir = (part, parts, mode, cache, unlink, cwd, created, cb) => er => { if (er) { fs.lstat(part, (statEr, st) => { if (statEr) { statEr.path = statEr.path && normPath(statEr.path) cb(statEr) } else if (st.isDirectory()) { mkdir_(part, parts, mode, cache, unlink, cwd, created, cb) } else if (unlink) { fs.unlink(part, er => { if (er) { return cb(er) } fs.mkdir(part, mode, onmkdir(part, parts, mode, cache, unlink, cwd, created, cb)) }) } else if (st.isSymbolicLink()) { return cb(new SymlinkError(part, part + '/' + parts.join('/'))) } else { cb(er) } }) } else { created = created || part mkdir_(part, parts, mode, cache, unlink, cwd, created, cb) } } const checkCwdSync = dir => { let ok = false let code = 'ENOTDIR' try { ok = fs.statSync(dir).isDirectory() } catch (er) { code = er.code } finally { if (!ok) { throw new CwdError(dir, code) } } } module.exports.sync = (dir, opt) => { dir = normPath(dir) // if there's any overlap between mask and mode, // then we'll need an explicit chmod const umask = opt.umask const mode = opt.mode | 0o0700 const needChmod = (mode & umask) !== 0 const uid = opt.uid const gid = opt.gid const doChown = typeof uid === 'number' && typeof gid === 'number' && (uid !== opt.processUid || gid !== opt.processGid) const preserve = opt.preserve const unlink = opt.unlink const cache = opt.cache const cwd = normPath(opt.cwd) const done = (created) => { cSet(cache, dir, true) if (created && doChown) { chownr.sync(created, uid, gid) } if (needChmod) { fs.chmodSync(dir, mode) } } if (cache && cGet(cache, dir) === true) { return done() } if (dir === cwd) { checkCwdSync(cwd) return done() } if (preserve) { return done(mkdirp.sync(dir, mode)) } const sub = normPath(path.relative(cwd, dir)) const parts = sub.split('/') let created = null for (let p = parts.shift(), part = cwd; p && (part += '/' + p); p = parts.shift()) { part = normPath(path.resolve(part)) if (cGet(cache, part)) { continue } try { fs.mkdirSync(part, mode) created = created || part cSet(cache, part, true) } catch (er) { const st = fs.lstatSync(part) if (st.isDirectory()) { cSet(cache, part, true) continue } else if (unlink) { fs.unlinkSync(part) fs.mkdirSync(part, mode) created = created || part cSet(cache, part, true) continue } else if (st.isSymbolicLink()) { return new SymlinkError(part, part + '/' + parts.join('/')) } } } return done(created) } PK ~\aGW tar/LICENSEnu[The ISC License Copyright (c) Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\EÜ tar/index.jsnu['use strict' // high-level commands exports.c = exports.create = require('./lib/create.js') exports.r = exports.replace = require('./lib/replace.js') exports.t = exports.list = require('./lib/list.js') exports.u = exports.update = require('./lib/update.js') exports.x = exports.extract = require('./lib/extract.js') // classes exports.Pack = require('./lib/pack.js') exports.Unpack = require('./lib/unpack.js') exports.Parse = require('./lib/parse.js') exports.ReadEntry = require('./lib/read-entry.js') exports.WriteEntry = require('./lib/write-entry.js') exports.Header = require('./lib/header.js') exports.Pax = require('./lib/pax.js') exports.types = require('./lib/types.js') PK ~\ɐmmignore-walk/package.jsonnu[{ "_id": "ignore-walk@6.0.5", "_inBundle": true, "_location": "/npm/ignore-walk", "_phantomChildren": {}, "_requiredBy": [ "/npm/npm-packlist" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/ignore-walk/issues" }, "dependencies": { "minimatch": "^9.0.0" }, "description": "Nested/recursive `.gitignore`/`.npmignore` parsing and filtering.", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.22.0", "mutate-fs": "^2.1.1", "tap": "^16.0.1" }, "engines": { "node": "^14.17.0 || ^16.13.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/ignore-walk#readme", "keywords": [ "ignorefile", "ignore", "file", ".gitignore", ".npmignore", "glob" ], "license": "ISC", "main": "lib/index.js", "name": "ignore-walk", "repository": { "type": "git", "url": "git+https://github.com/npm/ignore-walk.git" }, "scripts": { "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap", "test:windows-coverage": "npm pkg set tap.statements=99 --json && npm pkg set tap.branches=98 --json && npm pkg set tap.lines=99 --json" }, "tap": { "test-env": "LC_ALL=sk", "before": "test/00-setup.js", "after": "test/zz-cleanup.js", "timeout": 600, "jobs": 1, "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.22.0", "content": "scripts/template-oss", "publish": "true" }, "version": "6.0.5" } PK ~\i["["ignore-walk/lib/index.jsnu['use strict' const fs = require('fs') const path = require('path') const EE = require('events').EventEmitter const Minimatch = require('minimatch').Minimatch class Walker extends EE { constructor (opts) { opts = opts || {} super(opts) // set to true if this.path is a symlink, whether follow is true or not this.isSymbolicLink = opts.isSymbolicLink this.path = opts.path || process.cwd() this.basename = path.basename(this.path) this.ignoreFiles = opts.ignoreFiles || ['.ignore'] this.ignoreRules = {} this.parent = opts.parent || null this.includeEmpty = !!opts.includeEmpty this.root = this.parent ? this.parent.root : this.path this.follow = !!opts.follow this.result = this.parent ? this.parent.result : new Set() this.entries = null this.sawError = false this.exact = opts.exact } sort (a, b) { return a.localeCompare(b, 'en') } emit (ev, data) { let ret = false if (!(this.sawError && ev === 'error')) { if (ev === 'error') { this.sawError = true } else if (ev === 'done' && !this.parent) { data = Array.from(data) .map(e => /^@/.test(e) ? `./${e}` : e).sort(this.sort) this.result = data } if (ev === 'error' && this.parent) { ret = this.parent.emit('error', data) } else { ret = super.emit(ev, data) } } return ret } start () { fs.readdir(this.path, (er, entries) => er ? this.emit('error', er) : this.onReaddir(entries)) return this } isIgnoreFile (e) { return e !== '.' && e !== '..' && this.ignoreFiles.indexOf(e) !== -1 } onReaddir (entries) { this.entries = entries if (entries.length === 0) { if (this.includeEmpty) { this.result.add(this.path.slice(this.root.length + 1)) } this.emit('done', this.result) } else { const hasIg = this.entries.some(e => this.isIgnoreFile(e)) if (hasIg) { this.addIgnoreFiles() } else { this.filterEntries() } } } addIgnoreFiles () { const newIg = this.entries .filter(e => this.isIgnoreFile(e)) let igCount = newIg.length const then = () => { if (--igCount === 0) { this.filterEntries() } } newIg.forEach(e => this.addIgnoreFile(e, then)) } addIgnoreFile (file, then) { const ig = path.resolve(this.path, file) fs.readFile(ig, 'utf8', (er, data) => er ? this.emit('error', er) : this.onReadIgnoreFile(file, data, then)) } onReadIgnoreFile (file, data, then) { const mmopt = { matchBase: true, dot: true, flipNegate: true, nocase: true, } const rules = data.split(/\r?\n/) .filter(line => !/^#|^$/.test(line.trim())) .map(rule => { return new Minimatch(rule.trim(), mmopt) }) this.ignoreRules[file] = rules then() } filterEntries () { // at this point we either have ignore rules, or just inheriting // this exclusion is at the point where we know the list of // entries in the dir, but don't know what they are. since // some of them *might* be directories, we have to run the // match in dir-mode as well, so that we'll pick up partials // of files that will be included later. Anything included // at this point will be checked again later once we know // what it is. const filtered = this.entries.map(entry => { // at this point, we don't know if it's a dir or not. const passFile = this.filterEntry(entry) const passDir = this.filterEntry(entry, true) return (passFile || passDir) ? [entry, passFile, passDir] : false }).filter(e => e) // now we stat them all // if it's a dir, and passes as a dir, then recurse // if it's not a dir, but passes as a file, add to set let entryCount = filtered.length if (entryCount === 0) { this.emit('done', this.result) } else { const then = () => { if (--entryCount === 0) { this.emit('done', this.result) } } filtered.forEach(filt => { const entry = filt[0] const file = filt[1] const dir = filt[2] this.stat({ entry, file, dir }, then) }) } } onstat ({ st, entry, file, dir, isSymbolicLink }, then) { const abs = this.path + '/' + entry if (!st.isDirectory()) { if (file) { this.result.add(abs.slice(this.root.length + 1)) } then() } else { // is a directory if (dir) { this.walker(entry, { isSymbolicLink, exact: file || this.filterEntry(entry + '/') }, then) } else { then() } } } stat ({ entry, file, dir }, then) { const abs = this.path + '/' + entry fs.lstat(abs, (lstatErr, lstatResult) => { if (lstatErr) { this.emit('error', lstatErr) } else { const isSymbolicLink = lstatResult.isSymbolicLink() if (this.follow && isSymbolicLink) { fs.stat(abs, (statErr, statResult) => { if (statErr) { this.emit('error', statErr) } else { this.onstat({ st: statResult, entry, file, dir, isSymbolicLink }, then) } }) } else { this.onstat({ st: lstatResult, entry, file, dir, isSymbolicLink }, then) } } }) } walkerOpt (entry, opts) { return { path: this.path + '/' + entry, parent: this, ignoreFiles: this.ignoreFiles, follow: this.follow, includeEmpty: this.includeEmpty, ...opts, } } walker (entry, opts, then) { new Walker(this.walkerOpt(entry, opts)).on('done', then).start() } filterEntry (entry, partial, entryBasename) { let included = true // this = /a/b/c // entry = d // parent /a/b sees c/d if (this.parent && this.parent.filterEntry) { const parentEntry = this.basename + '/' + entry const parentBasename = entryBasename || entry included = this.parent.filterEntry(parentEntry, partial, parentBasename) if (!included && !this.exact) { return false } } this.ignoreFiles.forEach(f => { if (this.ignoreRules[f]) { this.ignoreRules[f].forEach(rule => { // negation means inclusion // so if it's negated, and already included, no need to check // likewise if it's neither negated nor included if (rule.negate !== included) { const isRelativeRule = entryBasename && rule.globParts.some(part => part.length <= (part.slice(-1)[0] ? 1 : 2) ) // first, match against /foo/bar // then, against foo/bar // then, in the case of partials, match with a / // then, if also the rule is relative, match against basename const match = rule.match('/' + entry) || rule.match(entry) || !!partial && ( rule.match('/' + entry + '/') || rule.match(entry + '/') || rule.negate && ( rule.match('/' + entry, true) || rule.match(entry, true)) || isRelativeRule && ( rule.match('/' + entryBasename + '/') || rule.match(entryBasename + '/') || rule.negate && ( rule.match('/' + entryBasename, true) || rule.match(entryBasename, true)))) if (match) { included = rule.negate } } }) } }) return included } } class WalkerSync extends Walker { start () { this.onReaddir(fs.readdirSync(this.path)) return this } addIgnoreFile (file, then) { const ig = path.resolve(this.path, file) this.onReadIgnoreFile(file, fs.readFileSync(ig, 'utf8'), then) } stat ({ entry, file, dir }, then) { const abs = this.path + '/' + entry let st = fs.lstatSync(abs) const isSymbolicLink = st.isSymbolicLink() if (this.follow && isSymbolicLink) { st = fs.statSync(abs) } // console.error('STAT SYNC', {st, entry, file, dir, isSymbolicLink, then}) this.onstat({ st, entry, file, dir, isSymbolicLink }, then) } walker (entry, opts, then) { new WalkerSync(this.walkerOpt(entry, opts)).start() then() } } const walk = (opts, callback) => { const p = new Promise((resolve, reject) => { new Walker(opts).on('done', resolve).on('error', reject).start() }) return callback ? p.then(res => callback(null, res), callback) : p } const walkSync = opts => new WalkerSync(opts).start().result module.exports = walk walk.sync = walkSync walk.Walker = Walker walk.WalkerSync = WalkerSync PK ~\aGWignore-walk/LICENSEnu[The ISC License Copyright (c) Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\yɗmake-fetch-happen/package.jsonnu[{ "_id": "make-fetch-happen@13.0.1", "_inBundle": true, "_location": "/npm/make-fetch-happen", "_phantomChildren": {}, "_requiredBy": [ "/npm", "/npm/@sigstore/sign", "/npm/node-gyp", "/npm/npm-registry-fetch", "/npm/tuf-js" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/make-fetch-happen/issues" }, "dependencies": { "@npmcli/agent": "^2.0.0", "cacache": "^18.0.0", "http-cache-semantics": "^4.1.1", "is-lambda": "^1.0.1", "minipass": "^7.0.2", "minipass-fetch": "^3.0.0", "minipass-flush": "^1.0.5", "minipass-pipeline": "^1.2.4", "negotiator": "^0.6.3", "proc-log": "^4.2.0", "promise-retry": "^2.0.1", "ssri": "^10.0.0" }, "description": "Opinionated, caching, retrying fetch client", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.21.4", "nock": "^13.2.4", "safe-buffer": "^5.2.1", "standard-version": "^9.3.2", "tap": "^16.0.0" }, "engines": { "node": "^16.14.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/make-fetch-happen#readme", "keywords": [ "http", "request", "fetch", "mean girls", "caching", "cache", "subresource integrity" ], "license": "ISC", "main": "lib/index.js", "name": "make-fetch-happen", "repository": { "type": "git", "url": "git+https://github.com/npm/make-fetch-happen.git" }, "scripts": { "eslint": "eslint", "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "color": 1, "files": "test/*.js", "check-coverage": true, "timeout": 60, "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.21.4", "publish": "true" }, "version": "13.0.1" } PK ~\R7kkmake-fetch-happen/lib/fetch.jsnu['use strict' const { FetchError, Request, isRedirect } = require('minipass-fetch') const url = require('url') const CachePolicy = require('./cache/policy.js') const cache = require('./cache/index.js') const remote = require('./remote.js') // given a Request, a Response and user options // return true if the response is a redirect that // can be followed. we throw errors that will result // in the fetch being rejected if the redirect is // possible but invalid for some reason const canFollowRedirect = (request, response, options) => { if (!isRedirect(response.status)) { return false } if (options.redirect === 'manual') { return false } if (options.redirect === 'error') { throw new FetchError(`redirect mode is set to error: ${request.url}`, 'no-redirect', { code: 'ENOREDIRECT' }) } if (!response.headers.has('location')) { throw new FetchError(`redirect location header missing for: ${request.url}`, 'no-location', { code: 'EINVALIDREDIRECT' }) } if (request.counter >= request.follow) { throw new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect', { code: 'EMAXREDIRECT' }) } return true } // given a Request, a Response, and the user's options return an object // with a new Request and a new options object that will be used for // following the redirect const getRedirect = (request, response, options) => { const _opts = { ...options } const location = response.headers.get('location') const redirectUrl = new url.URL(location, /^https?:/.test(location) ? undefined : request.url) // Comment below is used under the following license: /** * @license * Copyright (c) 2010-2012 Mikeal Rogers * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language * governing permissions and limitations under the License. */ // Remove authorization if changing hostnames (but not if just // changing ports or protocols). This matches the behavior of request: // https://github.com/request/request/blob/b12a6245/lib/redirect.js#L134-L138 if (new url.URL(request.url).hostname !== redirectUrl.hostname) { request.headers.delete('authorization') request.headers.delete('cookie') } // for POST request with 301/302 response, or any request with 303 response, // use GET when following redirect if ( response.status === 303 || (request.method === 'POST' && [301, 302].includes(response.status)) ) { _opts.method = 'GET' _opts.body = null request.headers.delete('content-length') } _opts.headers = {} request.headers.forEach((value, key) => { _opts.headers[key] = value }) _opts.counter = ++request.counter const redirectReq = new Request(url.format(redirectUrl), _opts) return { request: redirectReq, options: _opts, } } const fetch = async (request, options) => { const response = CachePolicy.storable(request, options) ? await cache(request, options) : await remote(request, options) // if the request wasn't a GET or HEAD, and the response // status is between 200 and 399 inclusive, invalidate the // request url if (!['GET', 'HEAD'].includes(request.method) && response.status >= 200 && response.status <= 399) { await cache.invalidate(request, options) } if (!canFollowRedirect(request, response, options)) { return response } const redirect = getRedirect(request, response, options) return fetch(redirect.request, redirect.options) } module.exports = fetch PK ~\ make-fetch-happen/lib/index.jsnu[const { FetchError, Headers, Request, Response } = require('minipass-fetch') const configureOptions = require('./options.js') const fetch = require('./fetch.js') const makeFetchHappen = (url, opts) => { const options = configureOptions(opts) const request = new Request(url, options) return fetch(request, options) } makeFetchHappen.defaults = (defaultUrl, defaultOptions = {}, wrappedFetch = makeFetchHappen) => { if (typeof defaultUrl === 'object') { defaultOptions = defaultUrl defaultUrl = null } const defaultedFetch = (url, options = {}) => { const finalUrl = url || defaultUrl const finalOptions = { ...defaultOptions, ...options, headers: { ...defaultOptions.headers, ...options.headers, }, } return wrappedFetch(finalUrl, finalOptions) } defaultedFetch.defaults = (defaultUrl1, defaultOptions1 = {}) => makeFetchHappen.defaults(defaultUrl1, defaultOptions1, defaultedFetch) return defaultedFetch } module.exports = makeFetchHappen module.exports.FetchError = FetchError module.exports.Headers = Headers module.exports.Request = Request module.exports.Response = Response PK ~\"7ZZ!make-fetch-happen/lib/pipeline.jsnu['use strict' const MinipassPipeline = require('minipass-pipeline') class CachingMinipassPipeline extends MinipassPipeline { #events = [] #data = new Map() constructor (opts, ...streams) { // CRITICAL: do NOT pass the streams to the call to super(), this will start // the flow of data and potentially cause the events we need to catch to emit // before we've finished our own setup. instead we call super() with no args, // finish our setup, and then push the streams into ourselves to start the // data flow super() this.#events = opts.events /* istanbul ignore next - coverage disabled because this is pointless to test here */ if (streams.length) { this.push(...streams) } } on (event, handler) { if (this.#events.includes(event) && this.#data.has(event)) { return handler(...this.#data.get(event)) } return super.on(event, handler) } emit (event, ...data) { if (this.#events.includes(event)) { this.#data.set(event, data) } return super.emit(event, ...data) } } module.exports = CachingMinipassPipeline PK ~\~ή"make-fetch-happen/lib/cache/key.jsnu[const { URL, format } = require('url') // options passed to url.format() when generating a key const formatOptions = { auth: false, fragment: false, search: true, unicode: false, } // returns a string to be used as the cache key for the Request const cacheKey = (request) => { const parsed = new URL(request.url) return `make-fetch-happen:request-cache:${format(parsed, formatOptions)}` } module.exports = cacheKey PK ~\RSJ%@%@$make-fetch-happen/lib/cache/entry.jsnu[const { Request, Response } = require('minipass-fetch') const { Minipass } = require('minipass') const MinipassFlush = require('minipass-flush') const cacache = require('cacache') const url = require('url') const CachingMinipassPipeline = require('../pipeline.js') const CachePolicy = require('./policy.js') const cacheKey = require('./key.js') const remote = require('../remote.js') const hasOwnProperty = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop) // allow list for request headers that will be written to the cache index // note: we will also store any request headers // that are named in a response's vary header const KEEP_REQUEST_HEADERS = [ 'accept-charset', 'accept-encoding', 'accept-language', 'accept', 'cache-control', ] // allow list for response headers that will be written to the cache index // note: we must not store the real response's age header, or when we load // a cache policy based on the metadata it will think the cached response // is always stale const KEEP_RESPONSE_HEADERS = [ 'cache-control', 'content-encoding', 'content-language', 'content-type', 'date', 'etag', 'expires', 'last-modified', 'link', 'location', 'pragma', 'vary', ] // return an object containing all metadata to be written to the index const getMetadata = (request, response, options) => { const metadata = { time: Date.now(), url: request.url, reqHeaders: {}, resHeaders: {}, // options on which we must match the request and vary the response options: { compress: options.compress != null ? options.compress : request.compress, }, } // only save the status if it's not a 200 or 304 if (response.status !== 200 && response.status !== 304) { metadata.status = response.status } for (const name of KEEP_REQUEST_HEADERS) { if (request.headers.has(name)) { metadata.reqHeaders[name] = request.headers.get(name) } } // if the request's host header differs from the host in the url // we need to keep it, otherwise it's just noise and we ignore it const host = request.headers.get('host') const parsedUrl = new url.URL(request.url) if (host && parsedUrl.host !== host) { metadata.reqHeaders.host = host } // if the response has a vary header, make sure // we store the relevant request headers too if (response.headers.has('vary')) { const vary = response.headers.get('vary') // a vary of "*" means every header causes a different response. // in that scenario, we do not include any additional headers // as the freshness check will always fail anyway and we don't // want to bloat the cache indexes if (vary !== '*') { // copy any other request headers that will vary the response const varyHeaders = vary.trim().toLowerCase().split(/\s*,\s*/) for (const name of varyHeaders) { if (request.headers.has(name)) { metadata.reqHeaders[name] = request.headers.get(name) } } } } for (const name of KEEP_RESPONSE_HEADERS) { if (response.headers.has(name)) { metadata.resHeaders[name] = response.headers.get(name) } } for (const name of options.cacheAdditionalHeaders) { if (response.headers.has(name)) { metadata.resHeaders[name] = response.headers.get(name) } } return metadata } // symbols used to hide objects that may be lazily evaluated in a getter const _request = Symbol('request') const _response = Symbol('response') const _policy = Symbol('policy') class CacheEntry { constructor ({ entry, request, response, options }) { if (entry) { this.key = entry.key this.entry = entry // previous versions of this module didn't write an explicit timestamp in // the metadata, so fall back to the entry's timestamp. we can't use the // entry timestamp to determine staleness because cacache will update it // when it verifies its data this.entry.metadata.time = this.entry.metadata.time || this.entry.time } else { this.key = cacheKey(request) } this.options = options // these properties are behind getters that lazily evaluate this[_request] = request this[_response] = response this[_policy] = null } // returns a CacheEntry instance that satisfies the given request // or undefined if no existing entry satisfies static async find (request, options) { try { // compacts the index and returns an array of unique entries var matches = await cacache.index.compact(options.cachePath, cacheKey(request), (A, B) => { const entryA = new CacheEntry({ entry: A, options }) const entryB = new CacheEntry({ entry: B, options }) return entryA.policy.satisfies(entryB.request) }, { validateEntry: (entry) => { // clean out entries with a buggy content-encoding value if (entry.metadata && entry.metadata.resHeaders && entry.metadata.resHeaders['content-encoding'] === null) { return false } // if an integrity is null, it needs to have a status specified if (entry.integrity === null) { return !!(entry.metadata && entry.metadata.status) } return true }, }) } catch (err) { // if the compact request fails, ignore the error and return return } // a cache mode of 'reload' means to behave as though we have no cache // on the way to the network. return undefined to allow cacheFetch to // create a brand new request no matter what. if (options.cache === 'reload') { return } // find the specific entry that satisfies the request let match for (const entry of matches) { const _entry = new CacheEntry({ entry, options, }) if (_entry.policy.satisfies(request)) { match = _entry break } } return match } // if the user made a PUT/POST/PATCH then we invalidate our // cache for the same url by deleting the index entirely static async invalidate (request, options) { const key = cacheKey(request) try { await cacache.rm.entry(options.cachePath, key, { removeFully: true }) } catch (err) { // ignore errors } } get request () { if (!this[_request]) { this[_request] = new Request(this.entry.metadata.url, { method: 'GET', headers: this.entry.metadata.reqHeaders, ...this.entry.metadata.options, }) } return this[_request] } get response () { if (!this[_response]) { this[_response] = new Response(null, { url: this.entry.metadata.url, counter: this.options.counter, status: this.entry.metadata.status || 200, headers: { ...this.entry.metadata.resHeaders, 'content-length': this.entry.size, }, }) } return this[_response] } get policy () { if (!this[_policy]) { this[_policy] = new CachePolicy({ entry: this.entry, request: this.request, response: this.response, options: this.options, }) } return this[_policy] } // wraps the response in a pipeline that stores the data // in the cache while the user consumes it async store (status) { // if we got a status other than 200, 301, or 308, // or the CachePolicy forbid storage, append the // cache status header and return it untouched if ( this.request.method !== 'GET' || ![200, 301, 308].includes(this.response.status) || !this.policy.storable() ) { this.response.headers.set('x-local-cache-status', 'skip') return this.response } const size = this.response.headers.get('content-length') const cacheOpts = { algorithms: this.options.algorithms, metadata: getMetadata(this.request, this.response, this.options), size, integrity: this.options.integrity, integrityEmitter: this.response.body.hasIntegrityEmitter && this.response.body, } let body = null // we only set a body if the status is a 200, redirects are // stored as metadata only if (this.response.status === 200) { let cacheWriteResolve, cacheWriteReject const cacheWritePromise = new Promise((resolve, reject) => { cacheWriteResolve = resolve cacheWriteReject = reject }).catch((err) => { body.emit('error', err) }) body = new CachingMinipassPipeline({ events: ['integrity', 'size'] }, new MinipassFlush({ flush () { return cacheWritePromise }, })) // this is always true since if we aren't reusing the one from the remote fetch, we // are using the one from cacache body.hasIntegrityEmitter = true const onResume = () => { const tee = new Minipass() const cacheStream = cacache.put.stream(this.options.cachePath, this.key, cacheOpts) // re-emit the integrity and size events on our new response body so they can be reused cacheStream.on('integrity', i => body.emit('integrity', i)) cacheStream.on('size', s => body.emit('size', s)) // stick a flag on here so downstream users will know if they can expect integrity events tee.pipe(cacheStream) // TODO if the cache write fails, log a warning but return the response anyway // eslint-disable-next-line promise/catch-or-return cacheStream.promise().then(cacheWriteResolve, cacheWriteReject) body.unshift(tee) body.unshift(this.response.body) } body.once('resume', onResume) body.once('end', () => body.removeListener('resume', onResume)) } else { await cacache.index.insert(this.options.cachePath, this.key, null, cacheOpts) } // note: we do not set the x-local-cache-hash header because we do not know // the hash value until after the write to the cache completes, which doesn't // happen until after the response has been sent and it's too late to write // the header anyway this.response.headers.set('x-local-cache', encodeURIComponent(this.options.cachePath)) this.response.headers.set('x-local-cache-key', encodeURIComponent(this.key)) this.response.headers.set('x-local-cache-mode', 'stream') this.response.headers.set('x-local-cache-status', status) this.response.headers.set('x-local-cache-time', new Date().toISOString()) const newResponse = new Response(body, { url: this.response.url, status: this.response.status, headers: this.response.headers, counter: this.options.counter, }) return newResponse } // use the cached data to create a response and return it async respond (method, options, status) { let response if (method === 'HEAD' || [301, 308].includes(this.response.status)) { // if the request is a HEAD, or the response is a redirect, // then the metadata in the entry already includes everything // we need to build a response response = this.response } else { // we're responding with a full cached response, so create a body // that reads from cacache and attach it to a new Response const body = new Minipass() const headers = { ...this.policy.responseHeaders() } const onResume = () => { const cacheStream = cacache.get.stream.byDigest( this.options.cachePath, this.entry.integrity, { memoize: this.options.memoize } ) cacheStream.on('error', async (err) => { cacheStream.pause() if (err.code === 'EINTEGRITY') { await cacache.rm.content( this.options.cachePath, this.entry.integrity, { memoize: this.options.memoize } ) } if (err.code === 'ENOENT' || err.code === 'EINTEGRITY') { await CacheEntry.invalidate(this.request, this.options) } body.emit('error', err) cacheStream.resume() }) // emit the integrity and size events based on our metadata so we're consistent body.emit('integrity', this.entry.integrity) body.emit('size', Number(headers['content-length'])) cacheStream.pipe(body) } body.once('resume', onResume) body.once('end', () => body.removeListener('resume', onResume)) response = new Response(body, { url: this.entry.metadata.url, counter: options.counter, status: 200, headers, }) } response.headers.set('x-local-cache', encodeURIComponent(this.options.cachePath)) response.headers.set('x-local-cache-hash', encodeURIComponent(this.entry.integrity)) response.headers.set('x-local-cache-key', encodeURIComponent(this.key)) response.headers.set('x-local-cache-mode', 'stream') response.headers.set('x-local-cache-status', status) response.headers.set('x-local-cache-time', new Date(this.entry.metadata.time).toUTCString()) return response } // use the provided request along with this cache entry to // revalidate the stored response. returns a response, either // from the cache or from the update async revalidate (request, options) { const revalidateRequest = new Request(request, { headers: this.policy.revalidationHeaders(request), }) try { // NOTE: be sure to remove the headers property from the // user supplied options, since we have already defined // them on the new request object. if they're still in the // options then those will overwrite the ones from the policy var response = await remote(revalidateRequest, { ...options, headers: undefined, }) } catch (err) { // if the network fetch fails, return the stale // cached response unless it has a cache-control // of 'must-revalidate' if (!this.policy.mustRevalidate) { return this.respond(request.method, options, 'stale') } throw err } if (this.policy.revalidated(revalidateRequest, response)) { // we got a 304, write a new index to the cache and respond from cache const metadata = getMetadata(request, response, options) // 304 responses do not include headers that are specific to the response data // since they do not include a body, so we copy values for headers that were // in the old cache entry to the new one, if the new metadata does not already // include that header for (const name of KEEP_RESPONSE_HEADERS) { if ( !hasOwnProperty(metadata.resHeaders, name) && hasOwnProperty(this.entry.metadata.resHeaders, name) ) { metadata.resHeaders[name] = this.entry.metadata.resHeaders[name] } } for (const name of options.cacheAdditionalHeaders) { const inMeta = hasOwnProperty(metadata.resHeaders, name) const inEntry = hasOwnProperty(this.entry.metadata.resHeaders, name) const inPolicy = hasOwnProperty(this.policy.response.headers, name) // if the header is in the existing entry, but it is not in the metadata // then we need to write it to the metadata as this will refresh the on-disk cache if (!inMeta && inEntry) { metadata.resHeaders[name] = this.entry.metadata.resHeaders[name] } // if the header is in the metadata, but not in the policy, then we need to set // it in the policy so that it's included in the immediate response. future // responses will load a new cache entry, so we don't need to change that if (!inPolicy && inMeta) { this.policy.response.headers[name] = metadata.resHeaders[name] } } try { await cacache.index.insert(options.cachePath, this.key, this.entry.integrity, { size: this.entry.size, metadata, }) } catch (err) { // if updating the cache index fails, we ignore it and // respond anyway } return this.respond(request.method, options, 'revalidated') } // if we got a modified response, create a new entry based on it const newEntry = new CacheEntry({ request, response, options, }) // respond with the new entry while writing it to the cache return newEntry.store('updated') } } module.exports = CacheEntry PK ~\$make-fetch-happen/lib/cache/index.jsnu[const { NotCachedError } = require('./errors.js') const CacheEntry = require('./entry.js') const remote = require('../remote.js') // do whatever is necessary to get a Response and return it const cacheFetch = async (request, options) => { // try to find a cached entry that satisfies this request const entry = await CacheEntry.find(request, options) if (!entry) { // no cached result, if the cache mode is 'only-if-cached' that's a failure if (options.cache === 'only-if-cached') { throw new NotCachedError(request.url) } // otherwise, we make a request, store it and return it const response = await remote(request, options) const newEntry = new CacheEntry({ request, response, options }) return newEntry.store('miss') } // we have a cached response that satisfies this request, however if the cache // mode is 'no-cache' then we send the revalidation request no matter what if (options.cache === 'no-cache') { return entry.revalidate(request, options) } // if the cached entry is not stale, or if the cache mode is 'force-cache' or // 'only-if-cached' we can respond with the cached entry. set the status // based on the result of needsRevalidation and respond const _needsRevalidation = entry.policy.needsRevalidation(request) if (options.cache === 'force-cache' || options.cache === 'only-if-cached' || !_needsRevalidation) { return entry.respond(request.method, options, _needsRevalidation ? 'stale' : 'hit') } // if we got here, the cache entry is stale so revalidate it return entry.revalidate(request, options) } cacheFetch.invalidate = async (request, options) => { if (!options.cachePath) { return } return CacheEntry.invalidate(request, options) } module.exports = cacheFetch PK ~\9N!%make-fetch-happen/lib/cache/errors.jsnu[class NotCachedError extends Error { constructor (url) { /* eslint-disable-next-line max-len */ super(`request to ${url} failed: cache mode is 'only-if-cached' but no cached response is available.`) this.code = 'ENOTCACHED' } } module.exports = { NotCachedError, } PK ~\D%make-fetch-happen/lib/cache/policy.jsnu[const CacheSemantics = require('http-cache-semantics') const Negotiator = require('negotiator') const ssri = require('ssri') // options passed to http-cache-semantics constructor const policyOptions = { shared: false, ignoreCargoCult: true, } // a fake empty response, used when only testing the // request for storability const emptyResponse = { status: 200, headers: {} } // returns a plain object representation of the Request const requestObject = (request) => { const _obj = { method: request.method, url: request.url, headers: {}, compress: request.compress, } request.headers.forEach((value, key) => { _obj.headers[key] = value }) return _obj } // returns a plain object representation of the Response const responseObject = (response) => { const _obj = { status: response.status, headers: {}, } response.headers.forEach((value, key) => { _obj.headers[key] = value }) return _obj } class CachePolicy { constructor ({ entry, request, response, options }) { this.entry = entry this.request = requestObject(request) this.response = responseObject(response) this.options = options this.policy = new CacheSemantics(this.request, this.response, policyOptions) if (this.entry) { // if we have an entry, copy the timestamp to the _responseTime // this is necessary because the CacheSemantics constructor forces // the value to Date.now() which means a policy created from a // cache entry is likely to always identify itself as stale this.policy._responseTime = this.entry.metadata.time } } // static method to quickly determine if a request alone is storable static storable (request, options) { // no cachePath means no caching if (!options.cachePath) { return false } // user explicitly asked not to cache if (options.cache === 'no-store') { return false } // we only cache GET and HEAD requests if (!['GET', 'HEAD'].includes(request.method)) { return false } // otherwise, let http-cache-semantics make the decision // based on the request's headers const policy = new CacheSemantics(requestObject(request), emptyResponse, policyOptions) return policy.storable() } // returns true if the policy satisfies the request satisfies (request) { const _req = requestObject(request) if (this.request.headers.host !== _req.headers.host) { return false } if (this.request.compress !== _req.compress) { return false } const negotiatorA = new Negotiator(this.request) const negotiatorB = new Negotiator(_req) if (JSON.stringify(negotiatorA.mediaTypes()) !== JSON.stringify(negotiatorB.mediaTypes())) { return false } if (JSON.stringify(negotiatorA.languages()) !== JSON.stringify(negotiatorB.languages())) { return false } if (JSON.stringify(negotiatorA.encodings()) !== JSON.stringify(negotiatorB.encodings())) { return false } if (this.options.integrity) { return ssri.parse(this.options.integrity).match(this.entry.integrity) } return true } // returns true if the request and response allow caching storable () { return this.policy.storable() } // NOTE: this is a hack to avoid parsing the cache-control // header ourselves, it returns true if the response's // cache-control contains must-revalidate get mustRevalidate () { return !!this.policy._rescc['must-revalidate'] } // returns true if the cached response requires revalidation // for the given request needsRevalidation (request) { const _req = requestObject(request) // force method to GET because we only cache GETs // but can serve a HEAD from a cached GET _req.method = 'GET' return !this.policy.satisfiesWithoutRevalidation(_req) } responseHeaders () { return this.policy.responseHeaders() } // returns a new object containing the appropriate headers // to send a revalidation request revalidationHeaders (request) { const _req = requestObject(request) return this.policy.revalidationHeaders(_req) } // returns true if the request/response was revalidated // successfully. returns false if a new response was received revalidated (request, response) { const _req = requestObject(request) const _res = responseObject(response) const policy = this.policy.revalidatedPolicy(_req, _res) return !policy.modified } } module.exports = CachePolicy PK ~\=r make-fetch-happen/lib/options.jsnu[const dns = require('dns') const conditionalHeaders = [ 'if-modified-since', 'if-none-match', 'if-unmodified-since', 'if-match', 'if-range', ] const configureOptions = (opts) => { const { strictSSL, ...options } = { ...opts } options.method = options.method ? options.method.toUpperCase() : 'GET' options.rejectUnauthorized = strictSSL !== false if (!options.retry) { options.retry = { retries: 0 } } else if (typeof options.retry === 'string') { const retries = parseInt(options.retry, 10) if (isFinite(retries)) { options.retry = { retries } } else { options.retry = { retries: 0 } } } else if (typeof options.retry === 'number') { options.retry = { retries: options.retry } } else { options.retry = { retries: 0, ...options.retry } } options.dns = { ttl: 5 * 60 * 1000, lookup: dns.lookup, ...options.dns } options.cache = options.cache || 'default' if (options.cache === 'default') { const hasConditionalHeader = Object.keys(options.headers || {}).some((name) => { return conditionalHeaders.includes(name.toLowerCase()) }) if (hasConditionalHeader) { options.cache = 'no-store' } } options.cacheAdditionalHeaders = options.cacheAdditionalHeaders || [] // cacheManager is deprecated, but if it's set and // cachePath is not we should copy it to the new field if (options.cacheManager && !options.cachePath) { options.cachePath = options.cacheManager } return options } module.exports = configureOptions PK ~\K~make-fetch-happen/lib/remote.jsnu[const { Minipass } = require('minipass') const fetch = require('minipass-fetch') const promiseRetry = require('promise-retry') const ssri = require('ssri') const { log } = require('proc-log') const CachingMinipassPipeline = require('./pipeline.js') const { getAgent } = require('@npmcli/agent') const pkg = require('../package.json') const USER_AGENT = `${pkg.name}/${pkg.version} (+https://npm.im/${pkg.name})` const RETRY_ERRORS = [ 'ECONNRESET', // remote socket closed on us 'ECONNREFUSED', // remote host refused to open connection 'EADDRINUSE', // failed to bind to a local port (proxy?) 'ETIMEDOUT', // someone in the transaction is WAY TOO SLOW // from @npmcli/agent 'ECONNECTIONTIMEOUT', 'EIDLETIMEOUT', 'ERESPONSETIMEOUT', 'ETRANSFERTIMEOUT', // Known codes we do NOT retry on: // ENOTFOUND (getaddrinfo failure. Either bad hostname, or offline) // EINVALIDPROXY // invalid protocol from @npmcli/agent // EINVALIDRESPONSE // invalid status code from @npmcli/agent ] const RETRY_TYPES = [ 'request-timeout', ] // make a request directly to the remote source, // retrying certain classes of errors as well as // following redirects (through the cache if necessary) // and verifying response integrity const remoteFetch = (request, options) => { const agent = getAgent(request.url, options) if (!request.headers.has('connection')) { request.headers.set('connection', agent ? 'keep-alive' : 'close') } if (!request.headers.has('user-agent')) { request.headers.set('user-agent', USER_AGENT) } // keep our own options since we're overriding the agent // and the redirect mode const _opts = { ...options, agent, redirect: 'manual', } return promiseRetry(async (retryHandler, attemptNum) => { const req = new fetch.Request(request, _opts) try { let res = await fetch(req, _opts) if (_opts.integrity && res.status === 200) { // we got a 200 response and the user has specified an expected // integrity value, so wrap the response in an ssri stream to verify it const integrityStream = ssri.integrityStream({ algorithms: _opts.algorithms, integrity: _opts.integrity, size: _opts.size, }) const pipeline = new CachingMinipassPipeline({ events: ['integrity', 'size'], }, res.body, integrityStream) // we also propagate the integrity and size events out to the pipeline so we can use // this new response body as an integrityEmitter for cacache integrityStream.on('integrity', i => pipeline.emit('integrity', i)) integrityStream.on('size', s => pipeline.emit('size', s)) res = new fetch.Response(pipeline, res) // set an explicit flag so we know if our response body will emit integrity and size res.body.hasIntegrityEmitter = true } res.headers.set('x-fetch-attempts', attemptNum) // do not retry POST requests, or requests with a streaming body // do retry requests with a 408, 420, 429 or 500+ status in the response const isStream = Minipass.isStream(req.body) const isRetriable = req.method !== 'POST' && !isStream && ([408, 420, 429].includes(res.status) || res.status >= 500) if (isRetriable) { if (typeof options.onRetry === 'function') { options.onRetry(res) } /* eslint-disable-next-line max-len */ log.http('fetch', `${req.method} ${req.url} attempt ${attemptNum} failed with ${res.status}`) return retryHandler(res) } return res } catch (err) { const code = (err.code === 'EPROMISERETRY') ? err.retried.code : err.code // err.retried will be the thing that was thrown from above // if it's a response, we just got a bad status code and we // can re-throw to allow the retry const isRetryError = err.retried instanceof fetch.Response || (RETRY_ERRORS.includes(code) && RETRY_TYPES.includes(err.type)) if (req.method === 'POST' || isRetryError) { throw err } if (typeof options.onRetry === 'function') { options.onRetry(err) } log.http('fetch', `${req.method} ${req.url} attempt ${attemptNum} failed with ${err.code}`) return retryHandler(err) } }, options.retry).catch((err) => { // don't reject for http errors, just return them if (err.status >= 400 && err.type !== 'system') { return err } throw err }) } module.exports = remoteFetch PK ~\O~make-fetch-happen/LICENSEnu[ISC License Copyright 2017-2022 (c) npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE COPYRIGHT HOLDER DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\shebang-command/package.jsonnu[{ "_id": "shebang-command@2.0.0", "_inBundle": true, "_location": "/npm/shebang-command", "_phantomChildren": {}, "_requiredBy": [ "/npm/cross-spawn" ], "author": { "name": "Kevin Mårtensson", "email": "kevinmartensson@gmail.com", "url": "github.com/kevva" }, "bugs": { "url": "https://github.com/kevva/shebang-command/issues" }, "dependencies": { "shebang-regex": "^3.0.0" }, "description": "Get the command from a shebang", "devDependencies": { "ava": "^2.3.0", "xo": "^0.24.0" }, "engines": { "node": ">=8" }, "files": [ "index.js" ], "homepage": "https://github.com/kevva/shebang-command#readme", "keywords": [ "cmd", "command", "parse", "shebang" ], "license": "MIT", "name": "shebang-command", "repository": { "type": "git", "url": "git+https://github.com/kevva/shebang-command.git" }, "scripts": { "test": "xo && ava" }, "version": "2.0.0" } PK ~\a(ծshebang-command/index.jsnu['use strict'; const shebangRegex = require('shebang-regex'); module.exports = (string = '') => { const match = string.match(shebangRegex); if (!match) { return null; } const [path, argument] = match[0].replace(/#! ?/, '').split(' '); const binary = path.split('/').pop(); if (binary === 'env') { return argument; } return argument ? `${binary} ${argument}` : binary; }; PK ~\ 0\\shebang-command/licensenu[MIT License Copyright (c) Kevin Mårtensson (github.com/kevva) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\I|99libnpmsearch/package.jsonnu[{ "_id": "libnpmsearch@7.0.6", "_inBundle": true, "_location": "/npm/libnpmsearch", "_phantomChildren": {}, "_requiredBy": [ "/npm" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/libnpmsearch/issues" }, "dependencies": { "npm-registry-fetch": "^17.0.1" }, "description": "Programmatic API for searching in npm and compatible registries.", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.22.0", "nock": "^13.3.3", "tap": "^16.3.8" }, "engines": { "node": "^16.14.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://npmjs.com/package/libnpmsearch", "keywords": [ "npm", "search", "api", "libnpm" ], "license": "ISC", "main": "lib/index.js", "name": "libnpmsearch", "repository": { "type": "git", "url": "git+https://github.com/npm/cli.git", "directory": "workspaces/libnpmsearch" }, "scripts": { "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.22.0", "content": "../../scripts/template-oss/index.js" }, "version": "7.0.6" } PK ~\њ;libnpmsearch/lib/index.jsnu['use strict' const npmFetch = require('npm-registry-fetch') module.exports = search function search (query, opts) { return search.stream(query, opts).collect() } search.stream = searchStream function searchStream (query, opts = {}) { opts = { detailed: false, limit: 20, from: 0, quality: 0.65, popularity: 0.98, maintenance: 0.5, ...opts.opts, // this is to support the cli's --searchopts parameter ...opts, } switch (opts.sortBy) { case 'optimal': { opts.quality = 0.65 opts.popularity = 0.98 opts.maintenance = 0.5 break } case 'quality': { opts.quality = 1 opts.popularity = 0 opts.maintenance = 0 break } case 'popularity': { opts.quality = 0 opts.popularity = 1 opts.maintenance = 0 break } case 'maintenance': { opts.quality = 0 opts.popularity = 0 opts.maintenance = 1 break } } return npmFetch.json.stream('/-/v1/search', 'objects.*', { ...opts, query: { text: Array.isArray(query) ? query.join(' ') : query, size: opts.limit, from: opts.from, quality: opts.quality, popularity: opts.popularity, maintenance: opts.maintenance, }, mapJSON: (obj) => { if (obj.package.date) { obj.package.date = new Date(obj.package.date) } if (opts.detailed) { return obj } else { return obj.package } }, } ) } PK ~\gXlibnpmsearch/LICENSEnu[Copyright npm, Inc Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\>^libnpmsearch/README.mdnu[# libnpmsearch [![npm version](https://img.shields.io/npm/v/libnpmsearch.svg)](https://npm.im/libnpmsearch) [![license](https://img.shields.io/npm/l/libnpmsearch.svg)](https://npm.im/libnpmsearch) [![CI - libnpmsearch](https://github.com/npm/cli/actions/workflows/ci-libnpmsearch.yml/badge.svg)](https://github.com/npm/cli/actions/workflows/ci-libnpmsearch.yml) [`libnpmsearch`](https://github.com/npm/libnpmsearch) is a Node.js library for programmatically accessing the npm search endpoint. It does **not** support legacy search through `/-/all`. ## Table of Contents * [Example](#example) * [Install](#install) * [Contributing](#contributing) * [API](#api) * [search opts](#opts) * [`search()`](#search) * [`search.stream()`](#search-stream) ## Example ```js const search = require('libnpmsearch') console.log(await search('libnpm')) => [ { name: 'libnpm', description: 'programmatic npm API', ...etc }, { name: 'libnpmsearch', description: 'Programmatic API for searching in npm and compatible registries', ...etc }, ...more ] ``` ## Install `$ npm install libnpmsearch` ### API #### `opts` for `libnpmsearch` commands The following opts are used directly by `libnpmsearch` itself: * `opts.limit` - Number of results to limit the query to. Default: 20 * `opts.from` - Offset number for results. Used with `opts.limit` for pagination. Default: 0 * `opts.detailed` - If true, returns an object with `package`, `score`, and `searchScore` fields, with `package` being what would usually be returned, and the other two containing details about how that package scored. Useful for UIs. Default: false * `opts.sortBy` - Used as a shorthand to set `opts.quality`, `opts.maintenance`, and `opts.popularity` with values that prioritize each one. Should be one of `'optimal'`, `'quality'`, `'maintenance'`, or `'popularity'`. Default: `'optimal'` * `opts.maintenance` - Decimal number between `0` and `1` that defines the weight of `maintenance` metrics when scoring and sorting packages. Default: `0.65` (same as `opts.sortBy: 'optimal'`) * `opts.popularity` - Decimal number between `0` and `1` that defines the weight of `popularity` metrics when scoring and sorting packages. Default: `0.98` (same as `opts.sortBy: 'optimal'`) * `opts.quality` - Decimal number between `0` and `1` that defines the weight of `quality` metrics when scoring and sorting packages. Default: `0.5` (same as `opts.sortBy: 'optimal'`) `libnpmsearch` uses [`npm-registry-fetch`](https://npm.im/npm-registry-fetch). Most options are passed through directly to that library, so please refer to [its own `opts` documentation](https://www.npmjs.com/package/npm-registry-fetch#fetch-options) for options that can be passed in. A couple of options of note for those in a hurry: * `opts.token` - can be passed in and will be used as the authentication token for the registry. For other ways to pass in auth details, see the n-r-f docs. #### `> search(query, [opts]) -> Promise` `query` must be either a String or an Array of search terms. If `opts.limit` is provided, it will be sent to the API to constrain the number of returned results. You may receive more, or fewer results, at the endpoint's discretion. The returned Promise resolved to an Array of search results with the following format: ```js { name: String, version: SemverString, description: String || null, maintainers: [ { username: String, email: String }, ...etc ] || null, keywords: [String] || null, date: Date || null } ``` If `opts.limit` is provided, it will be sent to the API to constrain the number of returned results. You may receive more, or fewer results, at the endpoint's discretion. For streamed results, see [`search.stream`](#search-stream). ##### Example ```javascript await search('libnpm') => [ { name: 'libnpm', description: 'programmatic npm API', ...etc }, { name: 'libnpmsearch', description: 'Programmatic API for searching in npm and compatible registries', ...etc }, ...more ] ``` #### `> search.stream(query, [opts]) -> Stream` `query` must be either a String or an Array of search terms. If `opts.limit` is provided, it will be sent to the API to constrain the number of returned results. You may receive more, or fewer results, at the endpoint's discretion. The returned Stream emits one entry per search result, with each entry having the following format: ```js { name: String, version: SemverString, description: String || null, maintainers: [ { username: String, email: String }, ...etc ] || null, keywords: [String] || null, date: Date || null } ``` For getting results in one chunk, see [`search`](#search-stream). ##### Example ```javascript search.stream('libnpm').on('data', console.log) => // entry 1 { name: 'libnpm', description: 'programmatic npm API', ...etc } // entry 2 { name: 'libnpmsearch', description: 'Programmatic API for searching in npm and compatible registries', ...etc } // etc ``` PK ~\0_p**path-key/package.jsonnu[{ "_id": "path-key@3.1.1", "_inBundle": true, "_location": "/npm/path-key", "_phantomChildren": {}, "_requiredBy": [ "/npm/cross-spawn" ], "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "bugs": { "url": "https://github.com/sindresorhus/path-key/issues" }, "description": "Get the PATH environment variable key cross-platform", "devDependencies": { "@types/node": "^11.13.0", "ava": "^1.4.1", "tsd": "^0.7.2", "xo": "^0.24.0" }, "engines": { "node": ">=8" }, "files": [ "index.js", "index.d.ts" ], "homepage": "https://github.com/sindresorhus/path-key#readme", "keywords": [ "path", "key", "environment", "env", "variable", "var", "get", "cross-platform", "windows" ], "license": "MIT", "name": "path-key", "repository": { "type": "git", "url": "git+https://github.com/sindresorhus/path-key.git" }, "scripts": { "test": "xo && ava && tsd" }, "version": "3.1.1" } PK ~\cpath-key/index.jsnu['use strict'; const pathKey = (options = {}) => { const environment = options.env || process.env; const platform = options.platform || process.platform; if (platform !== 'win32') { return 'PATH'; } return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path'; }; module.exports = pathKey; // TODO: Remove this for the next major release module.exports.default = pathKey; PK ~\E}UUpath-key/licensenu[MIT License Copyright (c) Sindre Sorhus (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\iꝔpromzard/package.jsonnu[{ "_id": "promzard@1.0.2", "_inBundle": true, "_location": "/npm/promzard", "_phantomChildren": {}, "_requiredBy": [ "/npm/init-package-json" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/promzard/issues" }, "dependencies": { "read": "^3.0.1" }, "description": "prompting wizardly", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.22.0", "tap": "^16.3.0" }, "engines": { "node": "^14.17.0 || ^16.13.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/promzard#readme", "license": "ISC", "main": "lib/index.js", "name": "promzard", "repository": { "url": "git+https://github.com/npm/promzard.git", "type": "git" }, "scripts": { "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "jobs": 1, "test-ignore": "fixtures/", "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.22.0", "publish": true }, "version": "1.0.2" } PK ~\oƏ::promzard/lib/index.jsnu[const fs = require('fs/promises') const { runInThisContext } = require('vm') const { promisify } = require('util') const { randomBytes } = require('crypto') const { Module } = require('module') const { dirname, basename } = require('path') const { read } = require('read') const files = {} class PromZard { #file = null #backupFile = null #ctx = null #unique = randomBytes(8).toString('hex') #prompts = [] constructor (file, ctx = {}, options = {}) { this.#file = file this.#ctx = ctx this.#backupFile = options.backupFile } static async promzard (file, ctx, options) { const pz = new PromZard(file, ctx, options) return pz.load() } static async fromBuffer (buf, ctx, options) { let filename = 0 do { filename = '\0' + Math.random() } while (files[filename]) files[filename] = buf const ret = await PromZard.promzard(filename, ctx, options) delete files[filename] return ret } async load () { if (files[this.#file]) { return this.#loaded() } try { files[this.#file] = await fs.readFile(this.#file, 'utf8') } catch (er) { if (er && this.#backupFile) { this.#file = this.#backupFile this.#backupFile = null return this.load() } throw er } return this.#loaded() } async #loaded () { const mod = new Module(this.#file, module) mod.loaded = true mod.filename = this.#file mod.id = this.#file mod.paths = Module._nodeModulePaths(dirname(this.#file)) this.#ctx.prompt = this.#makePrompt() this.#ctx.__filename = this.#file this.#ctx.__dirname = dirname(this.#file) this.#ctx.__basename = basename(this.#file) this.#ctx.module = mod this.#ctx.require = (p) => mod.require(p) this.#ctx.require.resolve = (p) => Module._resolveFilename(p, mod) this.#ctx.exports = mod.exports const body = `(function(${Object.keys(this.#ctx).join(', ')}) { ${files[this.#file]}\n })` runInThisContext(body, this.#file).apply(this.#ctx, Object.values(this.#ctx)) this.#ctx.res = mod.exports return this.#walk() } #makePrompt () { return (...args) => { let p, d, t for (let i = 0; i < args.length; i++) { const a = args[i] if (typeof a === 'string') { if (p) { d = a } else { p = a } } else if (typeof a === 'function') { t = a } else if (a && typeof a === 'object') { p = a.prompt || p d = a.default || d t = a.transform || t } } try { return `${this.#unique}-${this.#prompts.length}` } finally { this.#prompts.push([p, d, t]) } } } async #walk (o = this.#ctx.res) { const keys = Object.keys(o) const len = keys.length let i = 0 while (i < len) { const k = keys[i] const v = o[k] i++ if (v && typeof v === 'object') { o[k] = await this.#walk(v) continue } if (v && typeof v === 'string' && v.startsWith(this.#unique)) { const n = +v.slice(this.#unique.length + 1) // default to the key // default to the ctx value, if there is one const [prompt = k, def = this.#ctx[k], tx] = this.#prompts[n] try { o[k] = await this.#prompt(prompt, def, tx) } catch (er) { if (er.notValid) { // eslint-disable-next-line no-console console.log(er.message) i-- } else { throw er } } continue } if (typeof v === 'function') { // XXX: remove v.length check to remove cb from functions // would be a breaking change for `npm init` // XXX: if cb is no longer an argument then this.#ctx should // be passed in to allow arrow fns to be used and still access ctx const fn = v.length ? promisify(v) : v o[k] = await fn.call(this.#ctx) // back up so that we process this one again. // this is because it might return a prompt() call in the cb. i-- continue } } return o } async #prompt (prompt, def, tx) { const res = await read({ prompt: prompt + ':', default: def }).then((r) => tx ? tx(r) : r) // XXX: remove this to require throwing an error instead of // returning it. would be a breaking change for `npm init` if (res instanceof Error && res.notValid) { throw res } return res } } module.exports = PromZard.promzard module.exports.fromBuffer = PromZard.fromBuffer module.exports.PromZard = PromZard PK ~\?&promzard/LICENSEnu[The ISC License Copyright (c) Isaac Z. Schlueter Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\ __spdx-license-ids/package.jsonnu[{ "_id": "spdx-license-ids@3.0.18", "_inBundle": true, "_location": "/npm/spdx-license-ids", "_phantomChildren": {}, "_requiredBy": [ "/npm/spdx-correct", "/npm/spdx-correct/spdx-expression-parse", "/npm/spdx-expression-parse", "/npm/validate-npm-package-license/spdx-expression-parse" ], "author": { "name": "Shinnosuke Watanabe", "url": "https://github.com/shinnn" }, "bugs": { "url": "https://github.com/jslicense/spdx-license-ids/issues" }, "description": "A list of SPDX license identifiers", "devDependencies": { "@shinnn/eslint-config": "^7.0.0", "eslint": "^8.49.0", "eslint-formatter-codeframe": "^7.32.1", "rmfr": "^2.0.0", "tape": "^5.6.6" }, "eslintConfig": { "extends": "@shinnn" }, "files": [ "deprecated.json", "index.json" ], "homepage": "https://github.com/jslicense/spdx-license-ids#readme", "keywords": [ "spdx", "license", "licenses", "id", "identifier", "identifiers", "json", "array", "oss" ], "license": "CC0-1.0", "name": "spdx-license-ids", "repository": { "type": "git", "url": "git+https://github.com/jslicense/spdx-license-ids.git" }, "scripts": { "build": "node build.js", "latest": "node latest.js", "pretest": "eslint .", "test": "node test.js" }, "version": "3.0.18" } PK ~\02 spdx-license-ids/deprecated.jsonnu[[ "AGPL-1.0", "AGPL-3.0", "BSD-2-Clause-FreeBSD", "BSD-2-Clause-NetBSD", "GFDL-1.1", "GFDL-1.2", "GFDL-1.3", "GPL-1.0", "GPL-2.0", "GPL-2.0-with-GCC-exception", "GPL-2.0-with-autoconf-exception", "GPL-2.0-with-bison-exception", "GPL-2.0-with-classpath-exception", "GPL-2.0-with-font-exception", "GPL-3.0", "GPL-3.0-with-GCC-exception", "GPL-3.0-with-autoconf-exception", "LGPL-2.0", "LGPL-2.1", "LGPL-3.0", "Nunit", "StandardML-NJ", "bzip2-1.0.5", "eCos-2.0", "wxWindows" ] PK ~\Zzz'z'spdx-license-ids/index.jsonnu[[ "0BSD", "3D-Slicer-1.0", "AAL", "ADSL", "AFL-1.1", "AFL-1.2", "AFL-2.0", "AFL-2.1", "AFL-3.0", "AGPL-1.0-only", "AGPL-1.0-or-later", "AGPL-3.0-only", "AGPL-3.0-or-later", "AMD-newlib", "AMDPLPA", "AML", "AML-glslang", "AMPAS", "ANTLR-PD", "ANTLR-PD-fallback", "APAFML", "APL-1.0", "APSL-1.0", "APSL-1.1", "APSL-1.2", "APSL-2.0", "ASWF-Digital-Assets-1.0", "ASWF-Digital-Assets-1.1", "Abstyles", "AdaCore-doc", "Adobe-2006", "Adobe-Display-PostScript", "Adobe-Glyph", "Adobe-Utopia", "Afmparse", "Aladdin", "Apache-1.0", "Apache-1.1", "Apache-2.0", "App-s2p", "Arphic-1999", "Artistic-1.0", "Artistic-1.0-Perl", "Artistic-1.0-cl8", "Artistic-2.0", "BSD-1-Clause", "BSD-2-Clause", "BSD-2-Clause-Darwin", "BSD-2-Clause-Patent", "BSD-2-Clause-Views", "BSD-2-Clause-first-lines", "BSD-3-Clause", "BSD-3-Clause-Attribution", "BSD-3-Clause-Clear", "BSD-3-Clause-HP", "BSD-3-Clause-LBNL", "BSD-3-Clause-Modification", "BSD-3-Clause-No-Military-License", "BSD-3-Clause-No-Nuclear-License", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause-No-Nuclear-Warranty", "BSD-3-Clause-Open-MPI", "BSD-3-Clause-Sun", "BSD-3-Clause-acpica", "BSD-3-Clause-flex", "BSD-4-Clause", "BSD-4-Clause-Shortened", "BSD-4-Clause-UC", "BSD-4.3RENO", "BSD-4.3TAHOE", "BSD-Advertising-Acknowledgement", "BSD-Attribution-HPND-disclaimer", "BSD-Inferno-Nettverk", "BSD-Protection", "BSD-Source-Code", "BSD-Source-beginning-file", "BSD-Systemics", "BSD-Systemics-W3Works", "BSL-1.0", "BUSL-1.1", "Baekmuk", "Bahyph", "Barr", "Beerware", "BitTorrent-1.0", "BitTorrent-1.1", "Bitstream-Charter", "Bitstream-Vera", "BlueOak-1.0.0", "Boehm-GC", "Borceux", "Brian-Gladman-2-Clause", "Brian-Gladman-3-Clause", "C-UDA-1.0", "CAL-1.0", "CAL-1.0-Combined-Work-Exception", "CATOSL-1.1", "CC-BY-1.0", "CC-BY-2.0", "CC-BY-2.5", "CC-BY-2.5-AU", "CC-BY-3.0", "CC-BY-3.0-AT", "CC-BY-3.0-AU", "CC-BY-3.0-DE", "CC-BY-3.0-IGO", "CC-BY-3.0-NL", "CC-BY-3.0-US", "CC-BY-4.0", "CC-BY-NC-1.0", "CC-BY-NC-2.0", "CC-BY-NC-2.5", "CC-BY-NC-3.0", "CC-BY-NC-3.0-DE", "CC-BY-NC-4.0", "CC-BY-NC-ND-1.0", "CC-BY-NC-ND-2.0", "CC-BY-NC-ND-2.5", "CC-BY-NC-ND-3.0", "CC-BY-NC-ND-3.0-DE", "CC-BY-NC-ND-3.0-IGO", "CC-BY-NC-ND-4.0", "CC-BY-NC-SA-1.0", "CC-BY-NC-SA-2.0", "CC-BY-NC-SA-2.0-DE", "CC-BY-NC-SA-2.0-FR", "CC-BY-NC-SA-2.0-UK", "CC-BY-NC-SA-2.5", "CC-BY-NC-SA-3.0", "CC-BY-NC-SA-3.0-DE", "CC-BY-NC-SA-3.0-IGO", "CC-BY-NC-SA-4.0", "CC-BY-ND-1.0", "CC-BY-ND-2.0", "CC-BY-ND-2.5", "CC-BY-ND-3.0", "CC-BY-ND-3.0-DE", "CC-BY-ND-4.0", "CC-BY-SA-1.0", "CC-BY-SA-2.0", "CC-BY-SA-2.0-UK", "CC-BY-SA-2.1-JP", "CC-BY-SA-2.5", "CC-BY-SA-3.0", "CC-BY-SA-3.0-AT", "CC-BY-SA-3.0-DE", "CC-BY-SA-3.0-IGO", "CC-BY-SA-4.0", "CC-PDDC", "CC0-1.0", "CDDL-1.0", "CDDL-1.1", "CDL-1.0", "CDLA-Permissive-1.0", "CDLA-Permissive-2.0", "CDLA-Sharing-1.0", "CECILL-1.0", "CECILL-1.1", "CECILL-2.0", "CECILL-2.1", "CECILL-B", "CECILL-C", "CERN-OHL-1.1", "CERN-OHL-1.2", "CERN-OHL-P-2.0", "CERN-OHL-S-2.0", "CERN-OHL-W-2.0", "CFITSIO", "CMU-Mach", "CMU-Mach-nodoc", "CNRI-Jython", "CNRI-Python", "CNRI-Python-GPL-Compatible", "COIL-1.0", "CPAL-1.0", "CPL-1.0", "CPOL-1.02", "CUA-OPL-1.0", "Caldera", "Caldera-no-preamble", "Catharon", "ClArtistic", "Clips", "Community-Spec-1.0", "Condor-1.1", "Cornell-Lossless-JPEG", "Cronyx", "Crossword", "CrystalStacker", "Cube", "D-FSL-1.0", "DEC-3-Clause", "DL-DE-BY-2.0", "DL-DE-ZERO-2.0", "DOC", "DRL-1.0", "DRL-1.1", "DSDP", "Dotseqn", "ECL-1.0", "ECL-2.0", "EFL-1.0", "EFL-2.0", "EPICS", "EPL-1.0", "EPL-2.0", "EUDatagrid", "EUPL-1.0", "EUPL-1.1", "EUPL-1.2", "Elastic-2.0", "Entessa", "ErlPL-1.1", "Eurosym", "FBM", "FDK-AAC", "FSFAP", "FSFAP-no-warranty-disclaimer", "FSFUL", "FSFULLR", "FSFULLRWD", "FTL", "Fair", "Ferguson-Twofish", "Frameworx-1.0", "FreeBSD-DOC", "FreeImage", "Furuseth", "GCR-docs", "GD", "GFDL-1.1-invariants-only", "GFDL-1.1-invariants-or-later", "GFDL-1.1-no-invariants-only", "GFDL-1.1-no-invariants-or-later", "GFDL-1.1-only", "GFDL-1.1-or-later", "GFDL-1.2-invariants-only", "GFDL-1.2-invariants-or-later", "GFDL-1.2-no-invariants-only", "GFDL-1.2-no-invariants-or-later", "GFDL-1.2-only", "GFDL-1.2-or-later", "GFDL-1.3-invariants-only", "GFDL-1.3-invariants-or-later", "GFDL-1.3-no-invariants-only", "GFDL-1.3-no-invariants-or-later", "GFDL-1.3-only", "GFDL-1.3-or-later", "GL2PS", "GLWTPL", "GPL-1.0-only", "GPL-1.0-or-later", "GPL-2.0-only", "GPL-2.0-or-later", "GPL-3.0-only", "GPL-3.0-or-later", "Giftware", "Glide", "Glulxe", "Graphics-Gems", "Gutmann", "HP-1986", "HP-1989", "HPND", "HPND-DEC", "HPND-Fenneberg-Livingston", "HPND-INRIA-IMAG", "HPND-Intel", "HPND-Kevlin-Henney", "HPND-MIT-disclaimer", "HPND-Markus-Kuhn", "HPND-Pbmplus", "HPND-UC", "HPND-UC-export-US", "HPND-doc", "HPND-doc-sell", "HPND-export-US", "HPND-export-US-acknowledgement", "HPND-export-US-modify", "HPND-export2-US", "HPND-merchantability-variant", "HPND-sell-MIT-disclaimer-xserver", "HPND-sell-regexpr", "HPND-sell-variant", "HPND-sell-variant-MIT-disclaimer", "HPND-sell-variant-MIT-disclaimer-rev", "HTMLTIDY", "HaskellReport", "Hippocratic-2.1", "IBM-pibs", "ICU", "IEC-Code-Components-EULA", "IJG", "IJG-short", "IPA", "IPL-1.0", "ISC", "ISC-Veillard", "ImageMagick", "Imlib2", "Info-ZIP", "Inner-Net-2.0", "Intel", "Intel-ACPI", "Interbase-1.0", "JPL-image", "JPNIC", "JSON", "Jam", "JasPer-2.0", "Kastrup", "Kazlib", "Knuth-CTAN", "LAL-1.2", "LAL-1.3", "LGPL-2.0-only", "LGPL-2.0-or-later", "LGPL-2.1-only", "LGPL-2.1-or-later", "LGPL-3.0-only", "LGPL-3.0-or-later", "LGPLLR", "LOOP", "LPD-document", "LPL-1.0", "LPL-1.02", "LPPL-1.0", "LPPL-1.1", "LPPL-1.2", "LPPL-1.3a", "LPPL-1.3c", "LZMA-SDK-9.11-to-9.20", "LZMA-SDK-9.22", "Latex2e", "Latex2e-translated-notice", "Leptonica", "LiLiQ-P-1.1", "LiLiQ-R-1.1", "LiLiQ-Rplus-1.1", "Libpng", "Linux-OpenIB", "Linux-man-pages-1-para", "Linux-man-pages-copyleft", "Linux-man-pages-copyleft-2-para", "Linux-man-pages-copyleft-var", "Lucida-Bitmap-Fonts", "MIT", "MIT-0", "MIT-CMU", "MIT-Festival", "MIT-Khronos-old", "MIT-Modern-Variant", "MIT-Wu", "MIT-advertising", "MIT-enna", "MIT-feh", "MIT-open-group", "MIT-testregex", "MITNFA", "MMIXware", "MPEG-SSG", "MPL-1.0", "MPL-1.1", "MPL-2.0", "MPL-2.0-no-copyleft-exception", "MS-LPL", "MS-PL", "MS-RL", "MTLL", "Mackerras-3-Clause", "Mackerras-3-Clause-acknowledgment", "MakeIndex", "Martin-Birgmeier", "McPhee-slideshow", "Minpack", "MirOS", "Motosoto", "MulanPSL-1.0", "MulanPSL-2.0", "Multics", "Mup", "NAIST-2003", "NASA-1.3", "NBPL-1.0", "NCBI-PD", "NCGL-UK-2.0", "NCL", "NCSA", "NGPL", "NICTA-1.0", "NIST-PD", "NIST-PD-fallback", "NIST-Software", "NLOD-1.0", "NLOD-2.0", "NLPL", "NOSL", "NPL-1.0", "NPL-1.1", "NPOSL-3.0", "NRL", "NTP", "NTP-0", "Naumen", "Net-SNMP", "NetCDF", "Newsletr", "Nokia", "Noweb", "O-UDA-1.0", "OAR", "OCCT-PL", "OCLC-2.0", "ODC-By-1.0", "ODbL-1.0", "OFFIS", "OFL-1.0", "OFL-1.0-RFN", "OFL-1.0-no-RFN", "OFL-1.1", "OFL-1.1-RFN", "OFL-1.1-no-RFN", "OGC-1.0", "OGDL-Taiwan-1.0", "OGL-Canada-2.0", "OGL-UK-1.0", "OGL-UK-2.0", "OGL-UK-3.0", "OGTSL", "OLDAP-1.1", "OLDAP-1.2", "OLDAP-1.3", "OLDAP-1.4", "OLDAP-2.0", "OLDAP-2.0.1", "OLDAP-2.1", "OLDAP-2.2", "OLDAP-2.2.1", "OLDAP-2.2.2", "OLDAP-2.3", "OLDAP-2.4", "OLDAP-2.5", "OLDAP-2.6", "OLDAP-2.7", "OLDAP-2.8", "OLFL-1.3", "OML", "OPL-1.0", "OPL-UK-3.0", "OPUBL-1.0", "OSET-PL-2.1", "OSL-1.0", "OSL-1.1", "OSL-2.0", "OSL-2.1", "OSL-3.0", "OpenPBS-2.3", "OpenSSL", "OpenSSL-standalone", "OpenVision", "PADL", "PDDL-1.0", "PHP-3.0", "PHP-3.01", "PPL", "PSF-2.0", "Parity-6.0.0", "Parity-7.0.0", "Pixar", "Plexus", "PolyForm-Noncommercial-1.0.0", "PolyForm-Small-Business-1.0.0", "PostgreSQL", "Python-2.0", "Python-2.0.1", "QPL-1.0", "QPL-1.0-INRIA-2004", "Qhull", "RHeCos-1.1", "RPL-1.1", "RPL-1.5", "RPSL-1.0", "RSA-MD", "RSCPL", "Rdisc", "Ruby", "SAX-PD", "SAX-PD-2.0", "SCEA", "SGI-B-1.0", "SGI-B-1.1", "SGI-B-2.0", "SGI-OpenGL", "SGP4", "SHL-0.5", "SHL-0.51", "SISSL", "SISSL-1.2", "SL", "SMLNJ", "SMPPL", "SNIA", "SPL-1.0", "SSH-OpenSSH", "SSH-short", "SSLeay-standalone", "SSPL-1.0", "SWL", "Saxpath", "SchemeReport", "Sendmail", "Sendmail-8.23", "SimPL-2.0", "Sleepycat", "Soundex", "Spencer-86", "Spencer-94", "Spencer-99", "SugarCRM-1.1.3", "Sun-PPP", "Sun-PPP-2000", "SunPro", "Symlinks", "TAPR-OHL-1.0", "TCL", "TCP-wrappers", "TGPPL-1.0", "TMate", "TORQUE-1.1", "TOSL", "TPDL", "TPL-1.0", "TTWL", "TTYP0", "TU-Berlin-1.0", "TU-Berlin-2.0", "TermReadKey", "UCAR", "UCL-1.0", "UMich-Merit", "UPL-1.0", "URT-RLE", "Unicode-3.0", "Unicode-DFS-2015", "Unicode-DFS-2016", "Unicode-TOU", "UnixCrypt", "Unlicense", "VOSTROM", "VSL-1.0", "Vim", "W3C", "W3C-19980720", "W3C-20150513", "WTFPL", "Watcom-1.0", "Widget-Workshop", "Wsuipa", "X11", "X11-distribute-modifications-variant", "XFree86-1.1", "XSkat", "Xdebug-1.03", "Xerox", "Xfig", "Xnet", "YPL-1.0", "YPL-1.1", "ZPL-1.1", "ZPL-2.0", "ZPL-2.1", "Zed", "Zeeff", "Zend-2.0", "Zimbra-1.3", "Zimbra-1.4", "Zlib", "any-OSI", "bcrypt-Solar-Designer", "blessing", "bzip2-1.0.6", "check-cvs", "checkmk", "copyleft-next-0.3.0", "copyleft-next-0.3.1", "curl", "cve-tou", "diffmark", "dtoa", "dvipdfm", "eGenix", "etalab-2.0", "fwlw", "gSOAP-1.3b", "gnuplot", "gtkbook", "hdparm", "iMatix", "libpng-2.0", "libselinux-1.0", "libtiff", "libutil-David-Nugent", "lsof", "magaz", "mailprio", "metamail", "mpi-permissive", "mpich2", "mplus", "pkgconf", "pnmstitch", "psfrag", "psutils", "python-ldap", "radvd", "snprintf", "softSurfer", "ssh-keyscan", "swrule", "threeparttable", "ulem", "w3m", "xinetd", "xkeyboard-config-Zinoviev", "xlock", "xpp", "xzoom", "zlib-acknowledgement" ] PK ~\l~YYtext-table/package.jsonnu[{ "_id": "text-table@0.2.0", "_inBundle": true, "_location": "/npm/text-table", "_phantomChildren": {}, "_requiredBy": [ "/npm" ], "author": { "name": "James Halliday", "email": "mail@substack.net", "url": "http://substack.net" }, "bugs": { "url": "https://github.com/substack/text-table/issues" }, "description": "borderless text tables with alignment", "devDependencies": { "cli-color": "~0.2.3", "tap": "~0.4.0", "tape": "~1.0.2" }, "homepage": "https://github.com/substack/text-table", "keywords": [ "text", "table", "align", "ascii", "rows", "tabular" ], "license": "MIT", "main": "index.js", "name": "text-table", "repository": { "type": "git", "url": "git://github.com/substack/text-table.git" }, "scripts": { "test": "tap test/*.js" }, "testling": { "files": "test/*.js", "browsers": [ "ie/6..latest", "chrome/20..latest", "firefox/10..latest", "safari/latest", "opera/11.0..latest", "iphone/6", "ipad/6" ] }, "version": "0.2.0" } PK ~\x&text-table/test/center.jsnu[var test = require('tape'); var table = require('../'); test('center', function (t) { t.plan(1); var s = table([ [ 'beep', '1024', 'xyz' ], [ 'boop', '3388450', 'tuv' ], [ 'foo', '10106', 'qrstuv' ], [ 'bar', '45', 'lmno' ] ], { align: [ 'l', 'c', 'l' ] }); t.equal(s, [ 'beep 1024 xyz', 'boop 3388450 tuv', 'foo 10106 qrstuv', 'bar 45 lmno' ].join('\n')); }); PK ~\8||text-table/test/ansi-colors.jsnu[var test = require('tape'); var table = require('../'); var color = require('cli-color'); var ansiTrim = require('cli-color/lib/trim'); test('center', function (t) { t.plan(1); var opts = { align: [ 'l', 'c', 'l' ], stringLength: function(s) { return ansiTrim(s).length } }; var s = table([ [ color.red('Red'), color.green('Green'), color.blue('Blue') ], [ color.bold('Bold'), color.underline('Underline'), color.italic('Italic') ], [ color.inverse('Inverse'), color.strike('Strike'), color.blink('Blink') ], [ 'bar', '45', 'lmno' ] ], opts); t.equal(ansiTrim(s), [ 'Red Green Blue', 'Bold Underline Italic', 'Inverse Strike Blink', 'bar 45 lmno' ].join('\n')); }); PK ~\2text-table/test/doubledot.jsnu[var test = require('tape'); var table = require('../'); test('dot align', function (t) { t.plan(1); var s = table([ [ '0.1.2' ], [ '11.22.33' ], [ '5.6.7' ], [ '1.22222' ], [ '12345.' ], [ '5555.' ], [ '123' ] ], { align: [ '.' ] }); t.equal(s, [ ' 0.1.2', '11.22.33', ' 5.6.7', ' 1.22222', '12345.', ' 5555.', ' 123' ].join('\n')); }); PK ~\ text-table/test/dotalign.jsnu[var test = require('tape'); var table = require('../'); test('dot align', function (t) { t.plan(1); var s = table([ [ 'beep', '1024' ], [ 'boop', '334.212' ], [ 'foo', '1006' ], [ 'bar', '45.6' ], [ 'baz', '123.' ] ], { align: [ 'l', '.' ] }); t.equal(s, [ 'beep 1024', 'boop 334.212', 'foo 1006', 'bar 45.6', 'baz 123.' ].join('\n')); }); PK ~\BzMtext-table/test/align.jsnu[var test = require('tape'); var table = require('../'); test('align', function (t) { t.plan(1); var s = table([ [ 'beep', '1024' ], [ 'boop', '33450' ], [ 'foo', '1006' ], [ 'bar', '45' ] ], { align: [ 'l', 'r' ] }); t.equal(s, [ 'beep 1024', 'boop 33450', 'foo 1006', 'bar 45' ].join('\n')); }); PK ~\ FFtext-table/test/table.jsnu[var test = require('tape'); var table = require('../'); test('table', function (t) { t.plan(1); var s = table([ [ 'master', '0123456789abcdef' ], [ 'staging', 'fedcba9876543210' ] ]); t.equal(s, [ 'master 0123456789abcdef', 'staging fedcba9876543210' ].join('\n')); }); PK ~\Gl11text-table/LICENSEnu[This software is released under the MIT license: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\I| | text-table/index.jsnu[module.exports = function (rows_, opts) { if (!opts) opts = {}; var hsep = opts.hsep === undefined ? ' ' : opts.hsep; var align = opts.align || []; var stringLength = opts.stringLength || function (s) { return String(s).length; } ; var dotsizes = reduce(rows_, function (acc, row) { forEach(row, function (c, ix) { var n = dotindex(c); if (!acc[ix] || n > acc[ix]) acc[ix] = n; }); return acc; }, []); var rows = map(rows_, function (row) { return map(row, function (c_, ix) { var c = String(c_); if (align[ix] === '.') { var index = dotindex(c); var size = dotsizes[ix] + (/\./.test(c) ? 1 : 2) - (stringLength(c) - index) ; return c + Array(size).join(' '); } else return c; }); }); var sizes = reduce(rows, function (acc, row) { forEach(row, function (c, ix) { var n = stringLength(c); if (!acc[ix] || n > acc[ix]) acc[ix] = n; }); return acc; }, []); return map(rows, function (row) { return map(row, function (c, ix) { var n = (sizes[ix] - stringLength(c)) || 0; var s = Array(Math.max(n + 1, 1)).join(' '); if (align[ix] === 'r' || align[ix] === '.') { return s + c; } if (align[ix] === 'c') { return Array(Math.ceil(n / 2 + 1)).join(' ') + c + Array(Math.floor(n / 2 + 1)).join(' ') ; } return c + s; }).join(hsep).replace(/\s+$/, ''); }).join('\n'); }; function dotindex (c) { var m = /\.[^.]*$/.exec(c); return m ? m.index + 1 : c.length; } function reduce (xs, f, init) { if (xs.reduce) return xs.reduce(f, init); var i = 0; var acc = arguments.length >= 3 ? init : xs[i++]; for (; i < xs.length; i++) { f(acc, xs[i], i); } return acc; } function forEach (xs, f) { if (xs.forEach) return xs.forEach(f); for (var i = 0; i < xs.length; i++) { f.call(xs, xs[i], i); } } function map (xs, f) { if (xs.map) return xs.map(f); var res = []; for (var i = 0; i < xs.length; i++) { res.push(f.call(xs, xs[i], i)); } return res; } PK ~\tFʡtext-table/example/center.jsnu[var table = require('../'); var t = table([ [ 'beep', '1024', 'xyz' ], [ 'boop', '3388450', 'tuv' ], [ 'foo', '10106', 'qrstuv' ], [ 'bar', '45', 'lmno' ] ], { align: [ 'l', 'c', 'l' ] }); console.log(t); PK ~\o;wtext-table/example/doubledot.jsnu[var table = require('../'); var t = table([ [ '0.1.2' ], [ '11.22.33' ], [ '5.6.7' ], [ '1.22222' ], [ '12345.' ], [ '5555.' ], [ '123' ] ], { align: [ '.' ] }); console.log(t); PK ~\N\text-table/example/dotalign.jsnu[var table = require('../'); var t = table([ [ 'beep', '1024' ], [ 'boop', '334.212' ], [ 'foo', '1006' ], [ 'bar', '45.6' ], [ 'baz', '123.' ] ], { align: [ 'l', '.' ] }); console.log(t); PK ~\text-table/example/align.jsnu[var table = require('../'); var t = table([ [ 'beep', '1024' ], [ 'boop', '33450' ], [ 'foo', '1006' ], [ 'bar', '45' ] ], { align: [ 'l', 'r' ] }); console.log(t); PK ~\F]utext-table/example/table.jsnu[var table = require('../'); var t = table([ [ 'master', '0123456789abcdef' ], [ 'staging', 'fedcba9876543210' ] ]); console.log(t); PK ~\?#write-file-atomic/package.jsonnu[{ "_id": "write-file-atomic@5.0.1", "_inBundle": true, "_location": "/npm/write-file-atomic", "_phantomChildren": {}, "_requiredBy": [ "/npm", "/npm/bin-links" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/write-file-atomic/issues" }, "dependencies": { "imurmurhash": "^0.1.4", "signal-exit": "^4.0.1" }, "description": "Write files in an atomic fashion w/configurable ownership", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.14.1", "tap": "^16.0.1" }, "engines": { "node": "^14.17.0 || ^16.13.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/write-file-atomic", "keywords": [ "writeFile", "atomic" ], "license": "ISC", "main": "./lib/index.js", "name": "write-file-atomic", "repository": { "type": "git", "url": "git+https://github.com/npm/write-file-atomic.git" }, "scripts": { "lint": "eslint \"**/*.js\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "windowsCI": false, "version": "4.14.1", "publish": "true" }, "version": "5.0.1" } PK ~\k=^^write-file-atomic/lib/index.jsnu['use strict' module.exports = writeFile module.exports.sync = writeFileSync module.exports._getTmpname = getTmpname // for testing module.exports._cleanupOnExit = cleanupOnExit const fs = require('fs') const MurmurHash3 = require('imurmurhash') const { onExit } = require('signal-exit') const path = require('path') const { promisify } = require('util') const activeFiles = {} // if we run inside of a worker_thread, `process.pid` is not unique /* istanbul ignore next */ const threadId = (function getId () { try { const workerThreads = require('worker_threads') /// if we are in main thread, this is set to `0` return workerThreads.threadId } catch (e) { // worker_threads are not available, fallback to 0 return 0 } })() let invocations = 0 function getTmpname (filename) { return filename + '.' + MurmurHash3(__filename) .hash(String(process.pid)) .hash(String(threadId)) .hash(String(++invocations)) .result() } function cleanupOnExit (tmpfile) { return () => { try { fs.unlinkSync(typeof tmpfile === 'function' ? tmpfile() : tmpfile) } catch { // ignore errors } } } function serializeActiveFile (absoluteName) { return new Promise(resolve => { // make a queue if it doesn't already exist if (!activeFiles[absoluteName]) { activeFiles[absoluteName] = [] } activeFiles[absoluteName].push(resolve) // add this job to the queue if (activeFiles[absoluteName].length === 1) { resolve() } // kick off the first one }) } // https://github.com/isaacs/node-graceful-fs/blob/master/polyfills.js#L315-L342 function isChownErrOk (err) { if (err.code === 'ENOSYS') { return true } const nonroot = !process.getuid || process.getuid() !== 0 if (nonroot) { if (err.code === 'EINVAL' || err.code === 'EPERM') { return true } } return false } async function writeFileAsync (filename, data, options = {}) { if (typeof options === 'string') { options = { encoding: options } } let fd let tmpfile /* istanbul ignore next -- The closure only gets called when onExit triggers */ const removeOnExitHandler = onExit(cleanupOnExit(() => tmpfile)) const absoluteName = path.resolve(filename) try { await serializeActiveFile(absoluteName) const truename = await promisify(fs.realpath)(filename).catch(() => filename) tmpfile = getTmpname(truename) if (!options.mode || !options.chown) { // Either mode or chown is not explicitly set // Default behavior is to copy it from original file const stats = await promisify(fs.stat)(truename).catch(() => {}) if (stats) { if (options.mode == null) { options.mode = stats.mode } if (options.chown == null && process.getuid) { options.chown = { uid: stats.uid, gid: stats.gid } } } } fd = await promisify(fs.open)(tmpfile, 'w', options.mode) if (options.tmpfileCreated) { await options.tmpfileCreated(tmpfile) } if (ArrayBuffer.isView(data)) { await promisify(fs.write)(fd, data, 0, data.length, 0) } else if (data != null) { await promisify(fs.write)(fd, String(data), 0, String(options.encoding || 'utf8')) } if (options.fsync !== false) { await promisify(fs.fsync)(fd) } await promisify(fs.close)(fd) fd = null if (options.chown) { await promisify(fs.chown)(tmpfile, options.chown.uid, options.chown.gid).catch(err => { if (!isChownErrOk(err)) { throw err } }) } if (options.mode) { await promisify(fs.chmod)(tmpfile, options.mode).catch(err => { if (!isChownErrOk(err)) { throw err } }) } await promisify(fs.rename)(tmpfile, truename) } finally { if (fd) { await promisify(fs.close)(fd).catch( /* istanbul ignore next */ () => {} ) } removeOnExitHandler() await promisify(fs.unlink)(tmpfile).catch(() => {}) activeFiles[absoluteName].shift() // remove the element added by serializeSameFile if (activeFiles[absoluteName].length > 0) { activeFiles[absoluteName][0]() // start next job if one is pending } else { delete activeFiles[absoluteName] } } } async function writeFile (filename, data, options, callback) { if (options instanceof Function) { callback = options options = {} } const promise = writeFileAsync(filename, data, options) if (callback) { try { const result = await promise return callback(result) } catch (err) { return callback(err) } } return promise } function writeFileSync (filename, data, options) { if (typeof options === 'string') { options = { encoding: options } } else if (!options) { options = {} } try { filename = fs.realpathSync(filename) } catch (ex) { // it's ok, it'll happen on a not yet existing file } const tmpfile = getTmpname(filename) if (!options.mode || !options.chown) { // Either mode or chown is not explicitly set // Default behavior is to copy it from original file try { const stats = fs.statSync(filename) options = Object.assign({}, options) if (!options.mode) { options.mode = stats.mode } if (!options.chown && process.getuid) { options.chown = { uid: stats.uid, gid: stats.gid } } } catch (ex) { // ignore stat errors } } let fd const cleanup = cleanupOnExit(tmpfile) const removeOnExitHandler = onExit(cleanup) let threw = true try { fd = fs.openSync(tmpfile, 'w', options.mode || 0o666) if (options.tmpfileCreated) { options.tmpfileCreated(tmpfile) } if (ArrayBuffer.isView(data)) { fs.writeSync(fd, data, 0, data.length, 0) } else if (data != null) { fs.writeSync(fd, String(data), 0, String(options.encoding || 'utf8')) } if (options.fsync !== false) { fs.fsyncSync(fd) } fs.closeSync(fd) fd = null if (options.chown) { try { fs.chownSync(tmpfile, options.chown.uid, options.chown.gid) } catch (err) { if (!isChownErrOk(err)) { throw err } } } if (options.mode) { try { fs.chmodSync(tmpfile, options.mode) } catch (err) { if (!isChownErrOk(err)) { throw err } } } fs.renameSync(tmpfile, filename) threw = false } finally { if (fd) { try { fs.closeSync(fd) } catch (ex) { // ignore close errors at this stage, error may have closed fd already. } } removeOnExitHandler() if (threw) { cleanup() } } } PK ~\ write-file-atomic/LICENSE.mdnu[Copyright (c) 2015, Rebecca Turner Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\8K jackspeak/package.jsonnu[{ "_id": "jackspeak@3.1.2", "_inBundle": true, "_location": "/npm/jackspeak", "_phantomChildren": {}, "_requiredBy": [ "/npm/glob" ], "author": { "name": "Isaac Z. Schlueter", "email": "i@izs.me" }, "bugs": { "url": "https://github.com/isaacs/jackspeak/issues" }, "dependencies": { "@isaacs/cliui": "^8.0.2", "@pkgjs/parseargs": "^0.11.0" }, "description": "A very strict and proper argument parser.", "devDependencies": { "@types/node": "^20.7.0", "@types/pkgjs__parseargs": "^0.10.1", "prettier": "^3.2.5", "tap": "^18.8.0", "tshy": "^1.14.0", "typedoc": "^0.25.1", "typescript": "^5.2.2" }, "engines": { "node": ">=14" }, "exports": { "./package.json": "./package.json", ".": { "import": { "types": "./dist/esm/index.d.ts", "default": "./dist/esm/index.js" }, "require": { "types": "./dist/commonjs/index.d.ts", "default": "./dist/commonjs/index.js" } } }, "files": [ "dist" ], "funding": { "url": "https://github.com/sponsors/isaacs" }, "homepage": "https://github.com/isaacs/jackspeak#readme", "keywords": [ "argument", "parser", "args", "option", "flag", "cli", "command", "line", "parse", "parsing" ], "license": "BlueOak-1.0.0", "main": "./dist/commonjs/index.js", "name": "jackspeak", "optionalDependencies": { "@pkgjs/parseargs": "^0.11.0" }, "prettier": { "experimentalTernaries": true, "semi": false, "printWidth": 75, "tabWidth": 2, "useTabs": false, "singleQuote": true, "jsxSingleQuote": false, "bracketSameLine": true, "arrowParens": "avoid", "endOfLine": "lf" }, "repository": { "type": "git", "url": "git+https://github.com/isaacs/jackspeak.git" }, "scripts": { "build-examples": "for i in examples/*.js ; do node $i -h > ${i/.js/.txt}; done", "format": "prettier --write . --loglevel warn", "postversion": "npm publish", "prepare": "tshy", "prepublishOnly": "git push origin --follow-tags", "presnap": "npm run prepare", "pretest": "npm run prepare", "preversion": "npm test", "snap": "tap", "test": "tap", "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts" }, "tshy": { "main": true, "exports": { "./package.json": "./package.json", ".": "./src/index.js" } }, "type": "module", "types": "./dist/commonjs/index.d.ts", "version": "3.1.2" } PK ~\^Qv%jackspeak/dist/commonjs/parse-args.jsnu["use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseArgs = void 0; const util = __importStar(require("util")); const pv = typeof process === 'object' && !!process && typeof process.version === 'string' ? process.version : 'v0.0.0'; const pvs = pv .replace(/^v/, '') .split('.') .map(s => parseInt(s, 10)); /* c8 ignore start */ const [major = 0, minor = 0] = pvs; /* c8 ignore stop */ let { parseArgs: pa } = util; /* c8 ignore start */ if (!pa || major < 16 || (major === 18 && minor < 11) || (major === 16 && minor < 19)) { /* c8 ignore stop */ pa = require('@pkgjs/parseargs').parseArgs; } exports.parseArgs = pa; //# sourceMappingURL=parse-args-cjs.cjs.mapPK ~\>$jackspeak/dist/commonjs/package.jsonnu[{ "type": "commonjs" } PK ~\9 jackspeak/dist/commonjs/index.jsnu["use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.jack = exports.Jack = exports.isConfigOption = exports.isConfigType = void 0; const node_util_1 = require("node:util"); const parse_args_js_1 = require("./parse-args.js"); // it's a tiny API, just cast it inline, it's fine //@ts-ignore const cliui_1 = __importDefault(require("@isaacs/cliui")); const node_path_1 = require("node:path"); const width = Math.min((process && process.stdout && process.stdout.columns) || 80, 80); // indentation spaces from heading level const indent = (n) => (n - 1) * 2; const toEnvKey = (pref, key) => { return [pref, key.replace(/[^a-zA-Z0-9]+/g, ' ')] .join(' ') .trim() .toUpperCase() .replace(/ /g, '_'); }; const toEnvVal = (value, delim = '\n') => { const str = typeof value === 'string' ? value : typeof value === 'boolean' ? value ? '1' : '0' : typeof value === 'number' ? String(value) : Array.isArray(value) ? value.map((v) => toEnvVal(v)).join(delim) : /* c8 ignore start */ undefined; if (typeof str !== 'string') { throw new Error(`could not serialize value to environment: ${JSON.stringify(value)}`); } /* c8 ignore stop */ return str; }; const fromEnvVal = (env, type, multiple, delim = '\n') => (multiple ? env ? env.split(delim).map(v => fromEnvVal(v, type, false)) : [] : type === 'string' ? env : type === 'boolean' ? env === '1' : +env.trim()); const isConfigType = (t) => typeof t === 'string' && (t === 'string' || t === 'number' || t === 'boolean'); exports.isConfigType = isConfigType; const undefOrType = (v, t) => v === undefined || typeof v === t; const undefOrTypeArray = (v, t) => v === undefined || (Array.isArray(v) && v.every(x => typeof x === t)); const isValidOption = (v, vo) => Array.isArray(v) ? v.every(x => isValidOption(x, vo)) : vo.includes(v); // print the value type, for error message reporting const valueType = (v) => typeof v === 'string' ? 'string' : typeof v === 'boolean' ? 'boolean' : typeof v === 'number' ? 'number' : Array.isArray(v) ? joinTypes([...new Set(v.map(v => valueType(v)))]) + '[]' : `${v.type}${v.multiple ? '[]' : ''}`; const joinTypes = (types) => types.length === 1 && typeof types[0] === 'string' ? types[0] : `(${types.join('|')})`; const isValidValue = (v, type, multi) => { if (multi) { if (!Array.isArray(v)) return false; return !v.some((v) => !isValidValue(v, type, false)); } if (Array.isArray(v)) return false; return typeof v === type; }; const isConfigOption = (o, type, multi) => !!o && typeof o === 'object' && (0, exports.isConfigType)(o.type) && o.type === type && undefOrType(o.short, 'string') && undefOrType(o.description, 'string') && undefOrType(o.hint, 'string') && undefOrType(o.validate, 'function') && (o.type === 'boolean' ? o.validOptions === undefined : undefOrTypeArray(o.validOptions, o.type)) && (o.default === undefined || isValidValue(o.default, type, multi)) && !!o.multiple === multi; exports.isConfigOption = isConfigOption; function num(o = {}) { const { default: def, validate: val, validOptions, ...rest } = o; if (def !== undefined && !isValidValue(def, 'number', false)) { throw new TypeError('invalid default value', { cause: { found: def, wanted: 'number', }, }); } if (!undefOrTypeArray(validOptions, 'number')) { throw new TypeError('invalid validOptions', { cause: { found: validOptions, wanted: 'number[]', }, }); } const validate = val ? val : undefined; return { ...rest, default: def, validate, validOptions, type: 'number', multiple: false, }; } function numList(o = {}) { const { default: def, validate: val, validOptions, ...rest } = o; if (def !== undefined && !isValidValue(def, 'number', true)) { throw new TypeError('invalid default value', { cause: { found: def, wanted: 'number[]', }, }); } if (!undefOrTypeArray(validOptions, 'number')) { throw new TypeError('invalid validOptions', { cause: { found: validOptions, wanted: 'number[]', }, }); } const validate = val ? val : undefined; return { ...rest, default: def, validate, validOptions, type: 'number', multiple: true, }; } function opt(o = {}) { const { default: def, validate: val, validOptions, ...rest } = o; if (def !== undefined && !isValidValue(def, 'string', false)) { throw new TypeError('invalid default value', { cause: { found: def, wanted: 'string', }, }); } if (!undefOrTypeArray(validOptions, 'string')) { throw new TypeError('invalid validOptions', { cause: { found: validOptions, wanted: 'string[]', }, }); } const validate = val ? val : undefined; return { ...rest, default: def, validate, validOptions, type: 'string', multiple: false, }; } function optList(o = {}) { const { default: def, validate: val, validOptions, ...rest } = o; if (def !== undefined && !isValidValue(def, 'string', true)) { throw new TypeError('invalid default value', { cause: { found: def, wanted: 'string[]', }, }); } if (!undefOrTypeArray(validOptions, 'string')) { throw new TypeError('invalid validOptions', { cause: { found: validOptions, wanted: 'string[]', }, }); } const validate = val ? val : undefined; return { ...rest, default: def, validate, validOptions, type: 'string', multiple: true, }; } function flag(o = {}) { const { hint, default: def, validate: val, ...rest } = o; delete rest.validOptions; if (def !== undefined && !isValidValue(def, 'boolean', false)) { throw new TypeError('invalid default value'); } const validate = val ? val : undefined; if (hint !== undefined) { throw new TypeError('cannot provide hint for flag'); } return { ...rest, default: def, validate, type: 'boolean', multiple: false, }; } function flagList(o = {}) { const { hint, default: def, validate: val, ...rest } = o; delete rest.validOptions; if (def !== undefined && !isValidValue(def, 'boolean', true)) { throw new TypeError('invalid default value'); } const validate = val ? val : undefined; if (hint !== undefined) { throw new TypeError('cannot provide hint for flag list'); } return { ...rest, default: def, validate, type: 'boolean', multiple: true, }; } const toParseArgsOptionsConfig = (options) => { const c = {}; for (const longOption in options) { const config = options[longOption]; /* c8 ignore start */ if (!config) { throw new Error('config must be an object: ' + longOption); } /* c8 ignore start */ if ((0, exports.isConfigOption)(config, 'number', true)) { c[longOption] = { type: 'string', multiple: true, default: config.default?.map(c => String(c)), }; } else if ((0, exports.isConfigOption)(config, 'number', false)) { c[longOption] = { type: 'string', multiple: false, default: config.default === undefined ? undefined : String(config.default), }; } else { const conf = config; c[longOption] = { type: conf.type, multiple: !!conf.multiple, default: conf.default, }; } const clo = c[longOption]; if (typeof config.short === 'string') { clo.short = config.short; } if (config.type === 'boolean' && !longOption.startsWith('no-') && !options[`no-${longOption}`]) { c[`no-${longOption}`] = { type: 'boolean', multiple: config.multiple, }; } } return c; }; const isHeading = (r) => r.type === 'heading'; const isDescription = (r) => r.type === 'description'; /** * Class returned by the {@link jack} function and all configuration * definition methods. This is what gets chained together. */ class Jack { #configSet; #shorts; #options; #fields = []; #env; #envPrefix; #allowPositionals; #usage; #usageMarkdown; constructor(options = {}) { this.#options = options; this.#allowPositionals = options.allowPositionals !== false; this.#env = this.#options.env === undefined ? process.env : this.#options.env; this.#envPrefix = options.envPrefix; // We need to fib a little, because it's always the same object, but it // starts out as having an empty config set. Then each method that adds // fields returns `this as Jack` this.#configSet = Object.create(null); this.#shorts = Object.create(null); } /** * Set the default value (which will still be overridden by env or cli) * as if from a parsed config file. The optional `source` param, if * provided, will be included in error messages if a value is invalid or * unknown. */ setConfigValues(values, source = '') { try { this.validate(values); } catch (er) { const e = er; if (source && e && typeof e === 'object') { if (e.cause && typeof e.cause === 'object') { Object.assign(e.cause, { path: source }); } else { e.cause = { path: source }; } } throw e; } for (const [field, value] of Object.entries(values)) { const my = this.#configSet[field]; // already validated, just for TS's benefit /* c8 ignore start */ if (!my) { throw new Error('unexpected field in config set: ' + field, { cause: { found: field }, }); } /* c8 ignore stop */ my.default = value; } return this; } /** * Parse a string of arguments, and return the resulting * `{ values, positionals }` object. * * If an {@link JackOptions#envPrefix} is set, then it will read default * values from the environment, and write the resulting values back * to the environment as well. * * Environment values always take precedence over any other value, except * an explicit CLI setting. */ parse(args = process.argv) { if (args === process.argv) { args = args.slice(process._eval !== undefined ? 1 : 2); } if (this.#envPrefix) { for (const [field, my] of Object.entries(this.#configSet)) { const ek = toEnvKey(this.#envPrefix, field); const env = this.#env[ek]; if (env !== undefined) { my.default = fromEnvVal(env, my.type, !!my.multiple, my.delim); } } } const options = toParseArgsOptionsConfig(this.#configSet); const result = (0, parse_args_js_1.parseArgs)({ args, options, // always strict, but using our own logic strict: false, allowPositionals: this.#allowPositionals, tokens: true, }); const p = { values: {}, positionals: [], }; for (const token of result.tokens) { if (token.kind === 'positional') { p.positionals.push(token.value); if (this.#options.stopAtPositional) { p.positionals.push(...args.slice(token.index + 1)); return p; } } else if (token.kind === 'option') { let value = undefined; if (token.name.startsWith('no-')) { const my = this.#configSet[token.name]; const pname = token.name.substring('no-'.length); const pos = this.#configSet[pname]; if (pos && pos.type === 'boolean' && (!my || (my.type === 'boolean' && !!my.multiple === !!pos.multiple))) { value = false; token.name = pname; } } const my = this.#configSet[token.name]; if (!my) { throw new Error(`Unknown option '${token.rawName}'. ` + `To specify a positional argument starting with a '-', ` + `place it at the end of the command after '--', as in ` + `'-- ${token.rawName}'`, { cause: { found: token.rawName + (token.value ? `=${token.value}` : ''), }, }); } if (value === undefined) { if (token.value === undefined) { if (my.type !== 'boolean') { throw new Error(`No value provided for ${token.rawName}, expected ${my.type}`, { cause: { name: token.rawName, wanted: valueType(my), }, }); } value = true; } else { if (my.type === 'boolean') { throw new Error(`Flag ${token.rawName} does not take a value, received '${token.value}'`, { cause: { found: token } }); } if (my.type === 'string') { value = token.value; } else { value = +token.value; if (value !== value) { throw new Error(`Invalid value '${token.value}' provided for ` + `'${token.rawName}' option, expected number`, { cause: { name: token.rawName, found: token.value, wanted: 'number', }, }); } } } } if (my.multiple) { const pv = p.values; const tn = pv[token.name] ?? []; pv[token.name] = tn; tn.push(value); } else { const pv = p.values; pv[token.name] = value; } } } for (const [field, c] of Object.entries(this.#configSet)) { if (c.default !== undefined && !(field in p.values)) { //@ts-ignore p.values[field] = c.default; } } for (const [field, value] of Object.entries(p.values)) { const valid = this.#configSet[field]?.validate; const validOptions = this.#configSet[field]?.validOptions; let cause; if (validOptions && !isValidOption(value, validOptions)) { cause = { name: field, found: value, validOptions: validOptions }; } if (valid && !valid(value)) { cause ??= { name: field, found: value }; } if (cause) { throw new Error(`Invalid value provided for --${field}: ${JSON.stringify(value)}`, { cause }); } } this.#writeEnv(p); return p; } /** * do not set fields as 'no-foo' if 'foo' exists and both are bools * just set foo. */ #noNoFields(f, val, s = f) { if (!f.startsWith('no-') || typeof val !== 'boolean') return; const yes = f.substring('no-'.length); // recurse so we get the core config key we care about. this.#noNoFields(yes, val, s); if (this.#configSet[yes]?.type === 'boolean') { throw new Error(`do not set '${s}', instead set '${yes}' as desired.`, { cause: { found: s, wanted: yes } }); } } /** * Validate that any arbitrary object is a valid configuration `values` * object. Useful when loading config files or other sources. */ validate(o) { if (!o || typeof o !== 'object') { throw new Error('Invalid config: not an object', { cause: { found: o }, }); } const opts = o; for (const field in o) { const value = opts[field]; /* c8 ignore next - for TS */ if (value === undefined) continue; this.#noNoFields(field, value); const config = this.#configSet[field]; if (!config) { throw new Error(`Unknown config option: ${field}`, { cause: { found: field }, }); } if (!isValidValue(value, config.type, !!config.multiple)) { throw new Error(`Invalid value ${valueType(value)} for ${field}, expected ${valueType(config)}`, { cause: { name: field, found: value, wanted: valueType(config), }, }); } let cause; if (config.validOptions && !isValidOption(value, config.validOptions)) { cause = { name: field, found: value, validOptions: config.validOptions, }; } if (config.validate && !config.validate(value)) { cause ??= { name: field, found: value }; } if (cause) { throw new Error(`Invalid config value for ${field}: ${value}`, { cause, }); } } } #writeEnv(p) { if (!this.#env || !this.#envPrefix) return; for (const [field, value] of Object.entries(p.values)) { const my = this.#configSet[field]; this.#env[toEnvKey(this.#envPrefix, field)] = toEnvVal(value, my?.delim); } } /** * Add a heading to the usage output banner */ heading(text, level, { pre = false } = {}) { if (level === undefined) { level = this.#fields.some(r => isHeading(r)) ? 2 : 1; } this.#fields.push({ type: 'heading', text, level, pre }); return this; } /** * Add a long-form description to the usage output at this position. */ description(text, { pre } = {}) { this.#fields.push({ type: 'description', text, pre }); return this; } /** * Add one or more number fields. */ num(fields) { return this.#addFields(fields, num); } /** * Add one or more multiple number fields. */ numList(fields) { return this.#addFields(fields, numList); } /** * Add one or more string option fields. */ opt(fields) { return this.#addFields(fields, opt); } /** * Add one or more multiple string option fields. */ optList(fields) { return this.#addFields(fields, optList); } /** * Add one or more flag fields. */ flag(fields) { return this.#addFields(fields, flag); } /** * Add one or more multiple flag fields. */ flagList(fields) { return this.#addFields(fields, flagList); } /** * Generic field definition method. Similar to flag/flagList/number/etc, * but you must specify the `type` (and optionally `multiple` and `delim`) * fields on each one, or Jack won't know how to define them. */ addFields(fields) { const next = this; for (const [name, field] of Object.entries(fields)) { this.#validateName(name, field); next.#fields.push({ type: 'config', name, value: field, }); } Object.assign(next.#configSet, fields); return next; } #addFields(fields, fn) { const next = this; Object.assign(next.#configSet, Object.fromEntries(Object.entries(fields).map(([name, field]) => { this.#validateName(name, field); const option = fn(field); next.#fields.push({ type: 'config', name, value: option, }); return [name, option]; }))); return next; } #validateName(name, field) { if (!/^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$/.test(name)) { throw new TypeError(`Invalid option name: ${name}, ` + `must be '-' delimited ASCII alphanumeric`); } if (this.#configSet[name]) { throw new TypeError(`Cannot redefine option ${field}`); } if (this.#shorts[name]) { throw new TypeError(`Cannot redefine option ${name}, already ` + `in use for ${this.#shorts[name]}`); } if (field.short) { if (!/^[a-zA-Z0-9]$/.test(field.short)) { throw new TypeError(`Invalid ${name} short option: ${field.short}, ` + 'must be 1 ASCII alphanumeric character'); } if (this.#shorts[field.short]) { throw new TypeError(`Invalid ${name} short option: ${field.short}, ` + `already in use for ${this.#shorts[field.short]}`); } this.#shorts[field.short] = name; this.#shorts[name] = name; } } /** * Return the usage banner for the given configuration */ usage() { if (this.#usage) return this.#usage; let headingLevel = 1; const ui = (0, cliui_1.default)({ width }); const first = this.#fields[0]; let start = first?.type === 'heading' ? 1 : 0; if (first?.type === 'heading') { ui.div({ padding: [0, 0, 0, 0], text: normalize(first.text), }); } ui.div({ padding: [0, 0, 0, 0], text: 'Usage:' }); if (this.#options.usage) { ui.div({ text: this.#options.usage, padding: [0, 0, 0, 2], }); } else { const cmd = (0, node_path_1.basename)(String(process.argv[1])); const shortFlags = []; const shorts = []; const flags = []; const opts = []; for (const [field, config] of Object.entries(this.#configSet)) { if (config.short) { if (config.type === 'boolean') shortFlags.push(config.short); else shorts.push([config.short, config.hint || field]); } else { if (config.type === 'boolean') flags.push(field); else opts.push([field, config.hint || field]); } } const sf = shortFlags.length ? ' -' + shortFlags.join('') : ''; const so = shorts.map(([k, v]) => ` --${k}=<${v}>`).join(''); const lf = flags.map(k => ` --${k}`).join(''); const lo = opts.map(([k, v]) => ` --${k}=<${v}>`).join(''); const usage = `${cmd}${sf}${so}${lf}${lo}`.trim(); ui.div({ text: usage, padding: [0, 0, 0, 2], }); } ui.div({ padding: [0, 0, 0, 0], text: '' }); const maybeDesc = this.#fields[start]; if (maybeDesc && isDescription(maybeDesc)) { const print = normalize(maybeDesc.text, maybeDesc.pre); start++; ui.div({ padding: [0, 0, 0, 0], text: print }); ui.div({ padding: [0, 0, 0, 0], text: '' }); } const { rows, maxWidth } = this.#usageRows(start); // every heading/description after the first gets indented by 2 // extra spaces. for (const row of rows) { if (row.left) { // If the row is too long, don't wrap it // Bump the right-hand side down a line to make room const configIndent = indent(Math.max(headingLevel, 2)); if (row.left.length > maxWidth - 3) { ui.div({ text: row.left, padding: [0, 0, 0, configIndent] }); ui.div({ text: row.text, padding: [0, 0, 0, maxWidth] }); } else { ui.div({ text: row.left, padding: [0, 1, 0, configIndent], width: maxWidth, }, { padding: [0, 0, 0, 0], text: row.text }); } if (row.skipLine) { ui.div({ padding: [0, 0, 0, 0], text: '' }); } } else { if (isHeading(row)) { const { level } = row; headingLevel = level; // only h1 and h2 have bottom padding // h3-h6 do not const b = level <= 2 ? 1 : 0; ui.div({ ...row, padding: [0, 0, b, indent(level)] }); } else { ui.div({ ...row, padding: [0, 0, 1, indent(headingLevel + 1)] }); } } } return (this.#usage = ui.toString()); } /** * Return the usage banner markdown for the given configuration */ usageMarkdown() { if (this.#usageMarkdown) return this.#usageMarkdown; const out = []; let headingLevel = 1; const first = this.#fields[0]; let start = first?.type === 'heading' ? 1 : 0; if (first?.type === 'heading') { out.push(`# ${normalizeOneLine(first.text)}`); } out.push('Usage:'); if (this.#options.usage) { out.push(normalizeMarkdown(this.#options.usage, true)); } else { const cmd = (0, node_path_1.basename)(String(process.argv[1])); const shortFlags = []; const shorts = []; const flags = []; const opts = []; for (const [field, config] of Object.entries(this.#configSet)) { if (config.short) { if (config.type === 'boolean') shortFlags.push(config.short); else shorts.push([config.short, config.hint || field]); } else { if (config.type === 'boolean') flags.push(field); else opts.push([field, config.hint || field]); } } const sf = shortFlags.length ? ' -' + shortFlags.join('') : ''; const so = shorts.map(([k, v]) => ` --${k}=<${v}>`).join(''); const lf = flags.map(k => ` --${k}`).join(''); const lo = opts.map(([k, v]) => ` --${k}=<${v}>`).join(''); const usage = `${cmd}${sf}${so}${lf}${lo}`.trim(); out.push(normalizeMarkdown(usage, true)); } const maybeDesc = this.#fields[start]; if (maybeDesc && isDescription(maybeDesc)) { out.push(normalizeMarkdown(maybeDesc.text, maybeDesc.pre)); start++; } const { rows } = this.#usageRows(start); // heading level in markdown is number of # ahead of text for (const row of rows) { if (row.left) { out.push('#'.repeat(headingLevel + 1) + ' ' + normalizeOneLine(row.left, true)); if (row.text) out.push(normalizeMarkdown(row.text)); } else if (isHeading(row)) { const { level } = row; headingLevel = level; out.push(`${'#'.repeat(headingLevel)} ${normalizeOneLine(row.text, row.pre)}`); } else { out.push(normalizeMarkdown(row.text, !!row.pre)); } } return (this.#usageMarkdown = out.join('\n\n') + '\n'); } #usageRows(start) { // turn each config type into a row, and figure out the width of the // left hand indentation for the option descriptions. let maxMax = Math.max(12, Math.min(26, Math.floor(width / 3))); let maxWidth = 8; let prev = undefined; const rows = []; for (const field of this.#fields.slice(start)) { if (field.type !== 'config') { if (prev?.type === 'config') prev.skipLine = true; prev = undefined; field.text = normalize(field.text, !!field.pre); rows.push(field); continue; } const { value } = field; const desc = value.description || ''; const mult = value.multiple ? 'Can be set multiple times' : ''; const opts = value.validOptions?.length ? `Valid options:${value.validOptions.map(v => ` ${JSON.stringify(v)}`)}` : ''; const dmDelim = desc.includes('\n') ? '\n\n' : '\n'; const extra = [opts, mult].join(dmDelim).trim(); const text = (normalize(desc) + dmDelim + extra).trim(); const hint = value.hint || (value.type === 'number' ? 'n' : value.type === 'string' ? field.name : undefined); const short = !value.short ? '' : value.type === 'boolean' ? `-${value.short} ` : `-${value.short}<${hint}> `; const left = value.type === 'boolean' ? `${short}--${field.name}` : `${short}--${field.name}=<${hint}>`; const row = { text, left, type: 'config' }; if (text.length > width - maxMax) { row.skipLine = true; } if (prev && left.length > maxMax) prev.skipLine = true; prev = row; const len = left.length + 4; if (len > maxWidth && len < maxMax) { maxWidth = len; } rows.push(row); } return { rows, maxWidth }; } /** * Return the configuration options as a plain object */ toJSON() { return Object.fromEntries(Object.entries(this.#configSet).map(([field, def]) => [ field, { type: def.type, ...(def.multiple ? { multiple: true } : {}), ...(def.delim ? { delim: def.delim } : {}), ...(def.short ? { short: def.short } : {}), ...(def.description ? { description: normalize(def.description) } : {}), ...(def.validate ? { validate: def.validate } : {}), ...(def.validOptions ? { validOptions: def.validOptions } : {}), ...(def.default !== undefined ? { default: def.default } : {}), }, ])); } /** * Custom printer for `util.inspect` */ [node_util_1.inspect.custom](_, options) { return `Jack ${(0, node_util_1.inspect)(this.toJSON(), options)}`; } } exports.Jack = Jack; // Unwrap and un-indent, so we can wrap description // strings however makes them look nice in the code. const normalize = (s, pre = false) => pre ? // prepend a ZWSP to each line so cliui doesn't strip it. s .split('\n') .map(l => `\u200b${l}`) .join('\n') : s // remove single line breaks, except for lists .replace(/([^\n])\n[ \t]*([^\n])/g, (_, $1, $2) => !/^[-*]/.test($2) ? `${$1} ${$2}` : `${$1}\n${$2}`) // normalize mid-line whitespace .replace(/([^\n])[ \t]+([^\n])/g, '$1 $2') // two line breaks are enough .replace(/\n{3,}/g, '\n\n') // remove any spaces at the start of a line .replace(/\n[ \t]+/g, '\n') .trim(); // normalize for markdown printing, remove leading spaces on lines const normalizeMarkdown = (s, pre = false) => { const n = normalize(s, pre).replace(/\\/g, '\\\\'); return pre ? `\`\`\`\n${n.replace(/\u200b/g, '')}\n\`\`\`` : n.replace(/\n +/g, '\n').trim(); }; const normalizeOneLine = (s, pre = false) => { const n = normalize(s, pre) .replace(/[\s\u200b]+/g, ' ') .trim(); return pre ? `\`${n}\`` : n; }; /** * Main entry point. Create and return a {@link Jack} object. */ const jack = (options = {}) => new Jack(options); exports.jack = jack; //# sourceMappingURL=index.js.mapPK ~\##@ jackspeak/dist/esm/parse-args.jsnu[import * as util from 'util'; const pv = typeof process === 'object' && !!process && typeof process.version === 'string' ? process.version : 'v0.0.0'; const pvs = pv .replace(/^v/, '') .split('.') .map(s => parseInt(s, 10)); /* c8 ignore start */ const [major = 0, minor = 0] = pvs; /* c8 ignore stop */ let { parseArgs: pa, } = util; /* c8 ignore start - version specific */ if (!pa || major < 16 || (major === 18 && minor < 11) || (major === 16 && minor < 19)) { // Ignore because we will clobber it for commonjs //@ts-ignore pa = (await import('@pkgjs/parseargs')).parseArgs; } /* c8 ignore stop */ export const parseArgs = pa; //# sourceMappingURL=parse-args.js.mapPK ~\xjackspeak/dist/esm/package.jsonnu[{ "type": "module" } PK ~\g̅̅jackspeak/dist/esm/index.jsnu[import { inspect } from 'node:util'; import { parseArgs } from './parse-args.js'; // it's a tiny API, just cast it inline, it's fine //@ts-ignore import cliui from '@isaacs/cliui'; import { basename } from 'node:path'; const width = Math.min((process && process.stdout && process.stdout.columns) || 80, 80); // indentation spaces from heading level const indent = (n) => (n - 1) * 2; const toEnvKey = (pref, key) => { return [pref, key.replace(/[^a-zA-Z0-9]+/g, ' ')] .join(' ') .trim() .toUpperCase() .replace(/ /g, '_'); }; const toEnvVal = (value, delim = '\n') => { const str = typeof value === 'string' ? value : typeof value === 'boolean' ? value ? '1' : '0' : typeof value === 'number' ? String(value) : Array.isArray(value) ? value.map((v) => toEnvVal(v)).join(delim) : /* c8 ignore start */ undefined; if (typeof str !== 'string') { throw new Error(`could not serialize value to environment: ${JSON.stringify(value)}`); } /* c8 ignore stop */ return str; }; const fromEnvVal = (env, type, multiple, delim = '\n') => (multiple ? env ? env.split(delim).map(v => fromEnvVal(v, type, false)) : [] : type === 'string' ? env : type === 'boolean' ? env === '1' : +env.trim()); export const isConfigType = (t) => typeof t === 'string' && (t === 'string' || t === 'number' || t === 'boolean'); const undefOrType = (v, t) => v === undefined || typeof v === t; const undefOrTypeArray = (v, t) => v === undefined || (Array.isArray(v) && v.every(x => typeof x === t)); const isValidOption = (v, vo) => Array.isArray(v) ? v.every(x => isValidOption(x, vo)) : vo.includes(v); // print the value type, for error message reporting const valueType = (v) => typeof v === 'string' ? 'string' : typeof v === 'boolean' ? 'boolean' : typeof v === 'number' ? 'number' : Array.isArray(v) ? joinTypes([...new Set(v.map(v => valueType(v)))]) + '[]' : `${v.type}${v.multiple ? '[]' : ''}`; const joinTypes = (types) => types.length === 1 && typeof types[0] === 'string' ? types[0] : `(${types.join('|')})`; const isValidValue = (v, type, multi) => { if (multi) { if (!Array.isArray(v)) return false; return !v.some((v) => !isValidValue(v, type, false)); } if (Array.isArray(v)) return false; return typeof v === type; }; export const isConfigOption = (o, type, multi) => !!o && typeof o === 'object' && isConfigType(o.type) && o.type === type && undefOrType(o.short, 'string') && undefOrType(o.description, 'string') && undefOrType(o.hint, 'string') && undefOrType(o.validate, 'function') && (o.type === 'boolean' ? o.validOptions === undefined : undefOrTypeArray(o.validOptions, o.type)) && (o.default === undefined || isValidValue(o.default, type, multi)) && !!o.multiple === multi; function num(o = {}) { const { default: def, validate: val, validOptions, ...rest } = o; if (def !== undefined && !isValidValue(def, 'number', false)) { throw new TypeError('invalid default value', { cause: { found: def, wanted: 'number', }, }); } if (!undefOrTypeArray(validOptions, 'number')) { throw new TypeError('invalid validOptions', { cause: { found: validOptions, wanted: 'number[]', }, }); } const validate = val ? val : undefined; return { ...rest, default: def, validate, validOptions, type: 'number', multiple: false, }; } function numList(o = {}) { const { default: def, validate: val, validOptions, ...rest } = o; if (def !== undefined && !isValidValue(def, 'number', true)) { throw new TypeError('invalid default value', { cause: { found: def, wanted: 'number[]', }, }); } if (!undefOrTypeArray(validOptions, 'number')) { throw new TypeError('invalid validOptions', { cause: { found: validOptions, wanted: 'number[]', }, }); } const validate = val ? val : undefined; return { ...rest, default: def, validate, validOptions, type: 'number', multiple: true, }; } function opt(o = {}) { const { default: def, validate: val, validOptions, ...rest } = o; if (def !== undefined && !isValidValue(def, 'string', false)) { throw new TypeError('invalid default value', { cause: { found: def, wanted: 'string', }, }); } if (!undefOrTypeArray(validOptions, 'string')) { throw new TypeError('invalid validOptions', { cause: { found: validOptions, wanted: 'string[]', }, }); } const validate = val ? val : undefined; return { ...rest, default: def, validate, validOptions, type: 'string', multiple: false, }; } function optList(o = {}) { const { default: def, validate: val, validOptions, ...rest } = o; if (def !== undefined && !isValidValue(def, 'string', true)) { throw new TypeError('invalid default value', { cause: { found: def, wanted: 'string[]', }, }); } if (!undefOrTypeArray(validOptions, 'string')) { throw new TypeError('invalid validOptions', { cause: { found: validOptions, wanted: 'string[]', }, }); } const validate = val ? val : undefined; return { ...rest, default: def, validate, validOptions, type: 'string', multiple: true, }; } function flag(o = {}) { const { hint, default: def, validate: val, ...rest } = o; delete rest.validOptions; if (def !== undefined && !isValidValue(def, 'boolean', false)) { throw new TypeError('invalid default value'); } const validate = val ? val : undefined; if (hint !== undefined) { throw new TypeError('cannot provide hint for flag'); } return { ...rest, default: def, validate, type: 'boolean', multiple: false, }; } function flagList(o = {}) { const { hint, default: def, validate: val, ...rest } = o; delete rest.validOptions; if (def !== undefined && !isValidValue(def, 'boolean', true)) { throw new TypeError('invalid default value'); } const validate = val ? val : undefined; if (hint !== undefined) { throw new TypeError('cannot provide hint for flag list'); } return { ...rest, default: def, validate, type: 'boolean', multiple: true, }; } const toParseArgsOptionsConfig = (options) => { const c = {}; for (const longOption in options) { const config = options[longOption]; /* c8 ignore start */ if (!config) { throw new Error('config must be an object: ' + longOption); } /* c8 ignore start */ if (isConfigOption(config, 'number', true)) { c[longOption] = { type: 'string', multiple: true, default: config.default?.map(c => String(c)), }; } else if (isConfigOption(config, 'number', false)) { c[longOption] = { type: 'string', multiple: false, default: config.default === undefined ? undefined : String(config.default), }; } else { const conf = config; c[longOption] = { type: conf.type, multiple: !!conf.multiple, default: conf.default, }; } const clo = c[longOption]; if (typeof config.short === 'string') { clo.short = config.short; } if (config.type === 'boolean' && !longOption.startsWith('no-') && !options[`no-${longOption}`]) { c[`no-${longOption}`] = { type: 'boolean', multiple: config.multiple, }; } } return c; }; const isHeading = (r) => r.type === 'heading'; const isDescription = (r) => r.type === 'description'; /** * Class returned by the {@link jack} function and all configuration * definition methods. This is what gets chained together. */ export class Jack { #configSet; #shorts; #options; #fields = []; #env; #envPrefix; #allowPositionals; #usage; #usageMarkdown; constructor(options = {}) { this.#options = options; this.#allowPositionals = options.allowPositionals !== false; this.#env = this.#options.env === undefined ? process.env : this.#options.env; this.#envPrefix = options.envPrefix; // We need to fib a little, because it's always the same object, but it // starts out as having an empty config set. Then each method that adds // fields returns `this as Jack` this.#configSet = Object.create(null); this.#shorts = Object.create(null); } /** * Set the default value (which will still be overridden by env or cli) * as if from a parsed config file. The optional `source` param, if * provided, will be included in error messages if a value is invalid or * unknown. */ setConfigValues(values, source = '') { try { this.validate(values); } catch (er) { const e = er; if (source && e && typeof e === 'object') { if (e.cause && typeof e.cause === 'object') { Object.assign(e.cause, { path: source }); } else { e.cause = { path: source }; } } throw e; } for (const [field, value] of Object.entries(values)) { const my = this.#configSet[field]; // already validated, just for TS's benefit /* c8 ignore start */ if (!my) { throw new Error('unexpected field in config set: ' + field, { cause: { found: field }, }); } /* c8 ignore stop */ my.default = value; } return this; } /** * Parse a string of arguments, and return the resulting * `{ values, positionals }` object. * * If an {@link JackOptions#envPrefix} is set, then it will read default * values from the environment, and write the resulting values back * to the environment as well. * * Environment values always take precedence over any other value, except * an explicit CLI setting. */ parse(args = process.argv) { if (args === process.argv) { args = args.slice(process._eval !== undefined ? 1 : 2); } if (this.#envPrefix) { for (const [field, my] of Object.entries(this.#configSet)) { const ek = toEnvKey(this.#envPrefix, field); const env = this.#env[ek]; if (env !== undefined) { my.default = fromEnvVal(env, my.type, !!my.multiple, my.delim); } } } const options = toParseArgsOptionsConfig(this.#configSet); const result = parseArgs({ args, options, // always strict, but using our own logic strict: false, allowPositionals: this.#allowPositionals, tokens: true, }); const p = { values: {}, positionals: [], }; for (const token of result.tokens) { if (token.kind === 'positional') { p.positionals.push(token.value); if (this.#options.stopAtPositional) { p.positionals.push(...args.slice(token.index + 1)); return p; } } else if (token.kind === 'option') { let value = undefined; if (token.name.startsWith('no-')) { const my = this.#configSet[token.name]; const pname = token.name.substring('no-'.length); const pos = this.#configSet[pname]; if (pos && pos.type === 'boolean' && (!my || (my.type === 'boolean' && !!my.multiple === !!pos.multiple))) { value = false; token.name = pname; } } const my = this.#configSet[token.name]; if (!my) { throw new Error(`Unknown option '${token.rawName}'. ` + `To specify a positional argument starting with a '-', ` + `place it at the end of the command after '--', as in ` + `'-- ${token.rawName}'`, { cause: { found: token.rawName + (token.value ? `=${token.value}` : ''), }, }); } if (value === undefined) { if (token.value === undefined) { if (my.type !== 'boolean') { throw new Error(`No value provided for ${token.rawName}, expected ${my.type}`, { cause: { name: token.rawName, wanted: valueType(my), }, }); } value = true; } else { if (my.type === 'boolean') { throw new Error(`Flag ${token.rawName} does not take a value, received '${token.value}'`, { cause: { found: token } }); } if (my.type === 'string') { value = token.value; } else { value = +token.value; if (value !== value) { throw new Error(`Invalid value '${token.value}' provided for ` + `'${token.rawName}' option, expected number`, { cause: { name: token.rawName, found: token.value, wanted: 'number', }, }); } } } } if (my.multiple) { const pv = p.values; const tn = pv[token.name] ?? []; pv[token.name] = tn; tn.push(value); } else { const pv = p.values; pv[token.name] = value; } } } for (const [field, c] of Object.entries(this.#configSet)) { if (c.default !== undefined && !(field in p.values)) { //@ts-ignore p.values[field] = c.default; } } for (const [field, value] of Object.entries(p.values)) { const valid = this.#configSet[field]?.validate; const validOptions = this.#configSet[field]?.validOptions; let cause; if (validOptions && !isValidOption(value, validOptions)) { cause = { name: field, found: value, validOptions: validOptions }; } if (valid && !valid(value)) { cause ??= { name: field, found: value }; } if (cause) { throw new Error(`Invalid value provided for --${field}: ${JSON.stringify(value)}`, { cause }); } } this.#writeEnv(p); return p; } /** * do not set fields as 'no-foo' if 'foo' exists and both are bools * just set foo. */ #noNoFields(f, val, s = f) { if (!f.startsWith('no-') || typeof val !== 'boolean') return; const yes = f.substring('no-'.length); // recurse so we get the core config key we care about. this.#noNoFields(yes, val, s); if (this.#configSet[yes]?.type === 'boolean') { throw new Error(`do not set '${s}', instead set '${yes}' as desired.`, { cause: { found: s, wanted: yes } }); } } /** * Validate that any arbitrary object is a valid configuration `values` * object. Useful when loading config files or other sources. */ validate(o) { if (!o || typeof o !== 'object') { throw new Error('Invalid config: not an object', { cause: { found: o }, }); } const opts = o; for (const field in o) { const value = opts[field]; /* c8 ignore next - for TS */ if (value === undefined) continue; this.#noNoFields(field, value); const config = this.#configSet[field]; if (!config) { throw new Error(`Unknown config option: ${field}`, { cause: { found: field }, }); } if (!isValidValue(value, config.type, !!config.multiple)) { throw new Error(`Invalid value ${valueType(value)} for ${field}, expected ${valueType(config)}`, { cause: { name: field, found: value, wanted: valueType(config), }, }); } let cause; if (config.validOptions && !isValidOption(value, config.validOptions)) { cause = { name: field, found: value, validOptions: config.validOptions, }; } if (config.validate && !config.validate(value)) { cause ??= { name: field, found: value }; } if (cause) { throw new Error(`Invalid config value for ${field}: ${value}`, { cause, }); } } } #writeEnv(p) { if (!this.#env || !this.#envPrefix) return; for (const [field, value] of Object.entries(p.values)) { const my = this.#configSet[field]; this.#env[toEnvKey(this.#envPrefix, field)] = toEnvVal(value, my?.delim); } } /** * Add a heading to the usage output banner */ heading(text, level, { pre = false } = {}) { if (level === undefined) { level = this.#fields.some(r => isHeading(r)) ? 2 : 1; } this.#fields.push({ type: 'heading', text, level, pre }); return this; } /** * Add a long-form description to the usage output at this position. */ description(text, { pre } = {}) { this.#fields.push({ type: 'description', text, pre }); return this; } /** * Add one or more number fields. */ num(fields) { return this.#addFields(fields, num); } /** * Add one or more multiple number fields. */ numList(fields) { return this.#addFields(fields, numList); } /** * Add one or more string option fields. */ opt(fields) { return this.#addFields(fields, opt); } /** * Add one or more multiple string option fields. */ optList(fields) { return this.#addFields(fields, optList); } /** * Add one or more flag fields. */ flag(fields) { return this.#addFields(fields, flag); } /** * Add one or more multiple flag fields. */ flagList(fields) { return this.#addFields(fields, flagList); } /** * Generic field definition method. Similar to flag/flagList/number/etc, * but you must specify the `type` (and optionally `multiple` and `delim`) * fields on each one, or Jack won't know how to define them. */ addFields(fields) { const next = this; for (const [name, field] of Object.entries(fields)) { this.#validateName(name, field); next.#fields.push({ type: 'config', name, value: field, }); } Object.assign(next.#configSet, fields); return next; } #addFields(fields, fn) { const next = this; Object.assign(next.#configSet, Object.fromEntries(Object.entries(fields).map(([name, field]) => { this.#validateName(name, field); const option = fn(field); next.#fields.push({ type: 'config', name, value: option, }); return [name, option]; }))); return next; } #validateName(name, field) { if (!/^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$/.test(name)) { throw new TypeError(`Invalid option name: ${name}, ` + `must be '-' delimited ASCII alphanumeric`); } if (this.#configSet[name]) { throw new TypeError(`Cannot redefine option ${field}`); } if (this.#shorts[name]) { throw new TypeError(`Cannot redefine option ${name}, already ` + `in use for ${this.#shorts[name]}`); } if (field.short) { if (!/^[a-zA-Z0-9]$/.test(field.short)) { throw new TypeError(`Invalid ${name} short option: ${field.short}, ` + 'must be 1 ASCII alphanumeric character'); } if (this.#shorts[field.short]) { throw new TypeError(`Invalid ${name} short option: ${field.short}, ` + `already in use for ${this.#shorts[field.short]}`); } this.#shorts[field.short] = name; this.#shorts[name] = name; } } /** * Return the usage banner for the given configuration */ usage() { if (this.#usage) return this.#usage; let headingLevel = 1; const ui = cliui({ width }); const first = this.#fields[0]; let start = first?.type === 'heading' ? 1 : 0; if (first?.type === 'heading') { ui.div({ padding: [0, 0, 0, 0], text: normalize(first.text), }); } ui.div({ padding: [0, 0, 0, 0], text: 'Usage:' }); if (this.#options.usage) { ui.div({ text: this.#options.usage, padding: [0, 0, 0, 2], }); } else { const cmd = basename(String(process.argv[1])); const shortFlags = []; const shorts = []; const flags = []; const opts = []; for (const [field, config] of Object.entries(this.#configSet)) { if (config.short) { if (config.type === 'boolean') shortFlags.push(config.short); else shorts.push([config.short, config.hint || field]); } else { if (config.type === 'boolean') flags.push(field); else opts.push([field, config.hint || field]); } } const sf = shortFlags.length ? ' -' + shortFlags.join('') : ''; const so = shorts.map(([k, v]) => ` --${k}=<${v}>`).join(''); const lf = flags.map(k => ` --${k}`).join(''); const lo = opts.map(([k, v]) => ` --${k}=<${v}>`).join(''); const usage = `${cmd}${sf}${so}${lf}${lo}`.trim(); ui.div({ text: usage, padding: [0, 0, 0, 2], }); } ui.div({ padding: [0, 0, 0, 0], text: '' }); const maybeDesc = this.#fields[start]; if (maybeDesc && isDescription(maybeDesc)) { const print = normalize(maybeDesc.text, maybeDesc.pre); start++; ui.div({ padding: [0, 0, 0, 0], text: print }); ui.div({ padding: [0, 0, 0, 0], text: '' }); } const { rows, maxWidth } = this.#usageRows(start); // every heading/description after the first gets indented by 2 // extra spaces. for (const row of rows) { if (row.left) { // If the row is too long, don't wrap it // Bump the right-hand side down a line to make room const configIndent = indent(Math.max(headingLevel, 2)); if (row.left.length > maxWidth - 3) { ui.div({ text: row.left, padding: [0, 0, 0, configIndent] }); ui.div({ text: row.text, padding: [0, 0, 0, maxWidth] }); } else { ui.div({ text: row.left, padding: [0, 1, 0, configIndent], width: maxWidth, }, { padding: [0, 0, 0, 0], text: row.text }); } if (row.skipLine) { ui.div({ padding: [0, 0, 0, 0], text: '' }); } } else { if (isHeading(row)) { const { level } = row; headingLevel = level; // only h1 and h2 have bottom padding // h3-h6 do not const b = level <= 2 ? 1 : 0; ui.div({ ...row, padding: [0, 0, b, indent(level)] }); } else { ui.div({ ...row, padding: [0, 0, 1, indent(headingLevel + 1)] }); } } } return (this.#usage = ui.toString()); } /** * Return the usage banner markdown for the given configuration */ usageMarkdown() { if (this.#usageMarkdown) return this.#usageMarkdown; const out = []; let headingLevel = 1; const first = this.#fields[0]; let start = first?.type === 'heading' ? 1 : 0; if (first?.type === 'heading') { out.push(`# ${normalizeOneLine(first.text)}`); } out.push('Usage:'); if (this.#options.usage) { out.push(normalizeMarkdown(this.#options.usage, true)); } else { const cmd = basename(String(process.argv[1])); const shortFlags = []; const shorts = []; const flags = []; const opts = []; for (const [field, config] of Object.entries(this.#configSet)) { if (config.short) { if (config.type === 'boolean') shortFlags.push(config.short); else shorts.push([config.short, config.hint || field]); } else { if (config.type === 'boolean') flags.push(field); else opts.push([field, config.hint || field]); } } const sf = shortFlags.length ? ' -' + shortFlags.join('') : ''; const so = shorts.map(([k, v]) => ` --${k}=<${v}>`).join(''); const lf = flags.map(k => ` --${k}`).join(''); const lo = opts.map(([k, v]) => ` --${k}=<${v}>`).join(''); const usage = `${cmd}${sf}${so}${lf}${lo}`.trim(); out.push(normalizeMarkdown(usage, true)); } const maybeDesc = this.#fields[start]; if (maybeDesc && isDescription(maybeDesc)) { out.push(normalizeMarkdown(maybeDesc.text, maybeDesc.pre)); start++; } const { rows } = this.#usageRows(start); // heading level in markdown is number of # ahead of text for (const row of rows) { if (row.left) { out.push('#'.repeat(headingLevel + 1) + ' ' + normalizeOneLine(row.left, true)); if (row.text) out.push(normalizeMarkdown(row.text)); } else if (isHeading(row)) { const { level } = row; headingLevel = level; out.push(`${'#'.repeat(headingLevel)} ${normalizeOneLine(row.text, row.pre)}`); } else { out.push(normalizeMarkdown(row.text, !!row.pre)); } } return (this.#usageMarkdown = out.join('\n\n') + '\n'); } #usageRows(start) { // turn each config type into a row, and figure out the width of the // left hand indentation for the option descriptions. let maxMax = Math.max(12, Math.min(26, Math.floor(width / 3))); let maxWidth = 8; let prev = undefined; const rows = []; for (const field of this.#fields.slice(start)) { if (field.type !== 'config') { if (prev?.type === 'config') prev.skipLine = true; prev = undefined; field.text = normalize(field.text, !!field.pre); rows.push(field); continue; } const { value } = field; const desc = value.description || ''; const mult = value.multiple ? 'Can be set multiple times' : ''; const opts = value.validOptions?.length ? `Valid options:${value.validOptions.map(v => ` ${JSON.stringify(v)}`)}` : ''; const dmDelim = desc.includes('\n') ? '\n\n' : '\n'; const extra = [opts, mult].join(dmDelim).trim(); const text = (normalize(desc) + dmDelim + extra).trim(); const hint = value.hint || (value.type === 'number' ? 'n' : value.type === 'string' ? field.name : undefined); const short = !value.short ? '' : value.type === 'boolean' ? `-${value.short} ` : `-${value.short}<${hint}> `; const left = value.type === 'boolean' ? `${short}--${field.name}` : `${short}--${field.name}=<${hint}>`; const row = { text, left, type: 'config' }; if (text.length > width - maxMax) { row.skipLine = true; } if (prev && left.length > maxMax) prev.skipLine = true; prev = row; const len = left.length + 4; if (len > maxWidth && len < maxMax) { maxWidth = len; } rows.push(row); } return { rows, maxWidth }; } /** * Return the configuration options as a plain object */ toJSON() { return Object.fromEntries(Object.entries(this.#configSet).map(([field, def]) => [ field, { type: def.type, ...(def.multiple ? { multiple: true } : {}), ...(def.delim ? { delim: def.delim } : {}), ...(def.short ? { short: def.short } : {}), ...(def.description ? { description: normalize(def.description) } : {}), ...(def.validate ? { validate: def.validate } : {}), ...(def.validOptions ? { validOptions: def.validOptions } : {}), ...(def.default !== undefined ? { default: def.default } : {}), }, ])); } /** * Custom printer for `util.inspect` */ [inspect.custom](_, options) { return `Jack ${inspect(this.toJSON(), options)}`; } } // Unwrap and un-indent, so we can wrap description // strings however makes them look nice in the code. const normalize = (s, pre = false) => pre ? // prepend a ZWSP to each line so cliui doesn't strip it. s .split('\n') .map(l => `\u200b${l}`) .join('\n') : s // remove single line breaks, except for lists .replace(/([^\n])\n[ \t]*([^\n])/g, (_, $1, $2) => !/^[-*]/.test($2) ? `${$1} ${$2}` : `${$1}\n${$2}`) // normalize mid-line whitespace .replace(/([^\n])[ \t]+([^\n])/g, '$1 $2') // two line breaks are enough .replace(/\n{3,}/g, '\n\n') // remove any spaces at the start of a line .replace(/\n[ \t]+/g, '\n') .trim(); // normalize for markdown printing, remove leading spaces on lines const normalizeMarkdown = (s, pre = false) => { const n = normalize(s, pre).replace(/\\/g, '\\\\'); return pre ? `\`\`\`\n${n.replace(/\u200b/g, '')}\n\`\`\`` : n.replace(/\n +/g, '\n').trim(); }; const normalizeOneLine = (s, pre = false) => { const n = normalize(s, pre) .replace(/[\s\u200b]+/g, ' ') .trim(); return pre ? `\`${n}\`` : n; }; /** * Main entry point. Create and return a {@link Jack} object. */ export const jack = (options = {}) => new Jack(options); //# sourceMappingURL=index.js.mapPK ~\쾇jackspeak/LICENSE.mdnu[# Blue Oak Model License Version 1.0.0 ## Purpose This license gives everyone as much permission to work with this software as possible, while protecting contributors from liability. ## Acceptance In order to receive this license, you must agree to its rules. The rules of this license are both obligations under that agreement and conditions to your license. You must not do anything with this software that triggers a rule that you cannot or will not follow. ## Copyright Each contributor licenses you to do everything with this software that would otherwise infringe that contributor's copyright in it. ## Notices You must ensure that everyone who gets a copy of any part of this software from you, with or without changes, also gets the text of this license or a link to . ## Excuse If anyone notifies you in writing that you have not complied with [Notices](#notices), you can keep your license by taking all practical steps to comply within 30 days after the notice. If you do not do so, your license ends immediately. ## Patent Each contributor licenses you to do everything with this software that would otherwise infringe any patent claims they can license or become able to license. ## Reliability No contributor can revoke this license. ## No Liability ***As far as the law allows, this software comes as is, without any warranty or condition, and no contributor will be liable to anyone for any damages related to this software or this license, under any kind of legal claim.*** PK ~\rwbinary-extensions/package.jsonnu[{ "_id": "binary-extensions@2.3.0", "_inBundle": true, "_location": "/npm/binary-extensions", "_phantomChildren": {}, "_requiredBy": [ "/npm/libnpmdiff" ], "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "bugs": { "url": "https://github.com/sindresorhus/binary-extensions/issues" }, "description": "List of binary file extensions", "devDependencies": { "ava": "^1.4.1", "tsd": "^0.7.2", "xo": "^0.24.0" }, "engines": { "node": ">=8" }, "files": [ "index.js", "index.d.ts", "binary-extensions.json", "binary-extensions.json.d.ts" ], "funding": "https://github.com/sponsors/sindresorhus", "homepage": "https://github.com/sindresorhus/binary-extensions#readme", "keywords": [ "binary", "extensions", "extension", "file", "json", "list", "array" ], "license": "MIT", "name": "binary-extensions", "repository": { "type": "git", "url": "git+https://github.com/sindresorhus/binary-extensions.git" }, "scripts": { "test": "xo && ava && tsd" }, "sideEffects": false, "version": "2.3.0" } PK ~\D66binary-extensions/index.jsnu[module.exports = require('./binary-extensions.json'); PK ~\zՏbinary-extensions/licensenu[MIT License Copyright (c) Sindre Sorhus (https://sindresorhus.com) Copyright (c) Paul Miller (https://paulmillr.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\ xۑ(binary-extensions/binary-extensions.jsonnu[[ "3dm", "3ds", "3g2", "3gp", "7z", "a", "aac", "adp", "afdesign", "afphoto", "afpub", "ai", "aif", "aiff", "alz", "ape", "apk", "appimage", "ar", "arj", "asf", "au", "avi", "bak", "baml", "bh", "bin", "bk", "bmp", "btif", "bz2", "bzip2", "cab", "caf", "cgm", "class", "cmx", "cpio", "cr2", "cur", "dat", "dcm", "deb", "dex", "djvu", "dll", "dmg", "dng", "doc", "docm", "docx", "dot", "dotm", "dra", "DS_Store", "dsk", "dts", "dtshd", "dvb", "dwg", "dxf", "ecelp4800", "ecelp7470", "ecelp9600", "egg", "eol", "eot", "epub", "exe", "f4v", "fbs", "fh", "fla", "flac", "flatpak", "fli", "flv", "fpx", "fst", "fvt", "g3", "gh", "gif", "graffle", "gz", "gzip", "h261", "h263", "h264", "icns", "ico", "ief", "img", "ipa", "iso", "jar", "jpeg", "jpg", "jpgv", "jpm", "jxr", "key", "ktx", "lha", "lib", "lvp", "lz", "lzh", "lzma", "lzo", "m3u", "m4a", "m4v", "mar", "mdi", "mht", "mid", "midi", "mj2", "mka", "mkv", "mmr", "mng", "mobi", "mov", "movie", "mp3", "mp4", "mp4a", "mpeg", "mpg", "mpga", "mxu", "nef", "npx", "numbers", "nupkg", "o", "odp", "ods", "odt", "oga", "ogg", "ogv", "otf", "ott", "pages", "pbm", "pcx", "pdb", "pdf", "pea", "pgm", "pic", "png", "pnm", "pot", "potm", "potx", "ppa", "ppam", "ppm", "pps", "ppsm", "ppsx", "ppt", "pptm", "pptx", "psd", "pya", "pyc", "pyo", "pyv", "qt", "rar", "ras", "raw", "resources", "rgb", "rip", "rlc", "rmf", "rmvb", "rpm", "rtf", "rz", "s3m", "s7z", "scpt", "sgi", "shar", "snap", "sil", "sketch", "slk", "smv", "snk", "so", "stl", "suo", "sub", "swf", "tar", "tbz", "tbz2", "tga", "tgz", "thmx", "tif", "tiff", "tlz", "ttc", "ttf", "txz", "udf", "uvh", "uvi", "uvm", "uvp", "uvs", "uvu", "viv", "vob", "war", "wav", "wax", "wbmp", "wdp", "weba", "webm", "webp", "whl", "wim", "wm", "wma", "wmv", "wmx", "woff", "woff2", "wrm", "wvx", "xbm", "xif", "xla", "xlam", "xls", "xlsb", "xlsm", "xlsx", "xlt", "xltm", "xltx", "xm", "xmind", "xpi", "xpm", "xwd", "xz", "z", "zip", "zipx" ] PK ~\Lcolor-convert/package.jsonnu[{ "_id": "color-convert@2.0.1", "_inBundle": true, "_location": "/npm/color-convert", "_phantomChildren": {}, "_requiredBy": [ "/npm/wrap-ansi-cjs/ansi-styles" ], "author": { "name": "Heather Arthur", "email": "fayearthur@gmail.com" }, "bugs": { "url": "https://github.com/Qix-/color-convert/issues" }, "dependencies": { "color-name": "~1.1.4" }, "description": "Plain color conversion functions", "devDependencies": { "chalk": "^2.4.2", "xo": "^0.24.0" }, "engines": { "node": ">=7.0.0" }, "files": [ "index.js", "conversions.js", "route.js" ], "homepage": "https://github.com/Qix-/color-convert#readme", "keywords": [ "color", "colour", "convert", "converter", "conversion", "rgb", "hsl", "hsv", "hwb", "cmyk", "ansi", "ansi16" ], "license": "MIT", "name": "color-convert", "repository": { "type": "git", "url": "git+https://github.com/Qix-/color-convert.git" }, "scripts": { "pretest": "xo", "test": "node test/basic.js" }, "version": "2.0.1", "xo": { "rules": { "default-case": 0, "no-inline-comments": 0, "operator-linebreak": 0 } } } PK ~\d>IՐBBcolor-convert/conversions.jsnu[/* MIT license */ /* eslint-disable no-mixed-operators */ const cssKeywords = require('color-name'); // NOTE: conversions should only return primitive values (i.e. arrays, or // values that give correct `typeof` results). // do not use box values types (i.e. Number(), String(), etc.) const reverseKeywords = {}; for (const key of Object.keys(cssKeywords)) { reverseKeywords[cssKeywords[key]] = key; } const convert = { rgb: {channels: 3, labels: 'rgb'}, hsl: {channels: 3, labels: 'hsl'}, hsv: {channels: 3, labels: 'hsv'}, hwb: {channels: 3, labels: 'hwb'}, cmyk: {channels: 4, labels: 'cmyk'}, xyz: {channels: 3, labels: 'xyz'}, lab: {channels: 3, labels: 'lab'}, lch: {channels: 3, labels: 'lch'}, hex: {channels: 1, labels: ['hex']}, keyword: {channels: 1, labels: ['keyword']}, ansi16: {channels: 1, labels: ['ansi16']}, ansi256: {channels: 1, labels: ['ansi256']}, hcg: {channels: 3, labels: ['h', 'c', 'g']}, apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, gray: {channels: 1, labels: ['gray']} }; module.exports = convert; // Hide .channels and .labels properties for (const model of Object.keys(convert)) { if (!('channels' in convert[model])) { throw new Error('missing channels property: ' + model); } if (!('labels' in convert[model])) { throw new Error('missing channel labels property: ' + model); } if (convert[model].labels.length !== convert[model].channels) { throw new Error('channel and label counts mismatch: ' + model); } const {channels, labels} = convert[model]; delete convert[model].channels; delete convert[model].labels; Object.defineProperty(convert[model], 'channels', {value: channels}); Object.defineProperty(convert[model], 'labels', {value: labels}); } convert.rgb.hsl = function (rgb) { const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const min = Math.min(r, g, b); const max = Math.max(r, g, b); const delta = max - min; let h; let s; if (max === min) { h = 0; } else if (r === max) { h = (g - b) / delta; } else if (g === max) { h = 2 + (b - r) / delta; } else if (b === max) { h = 4 + (r - g) / delta; } h = Math.min(h * 60, 360); if (h < 0) { h += 360; } const l = (min + max) / 2; if (max === min) { s = 0; } else if (l <= 0.5) { s = delta / (max + min); } else { s = delta / (2 - max - min); } return [h, s * 100, l * 100]; }; convert.rgb.hsv = function (rgb) { let rdif; let gdif; let bdif; let h; let s; const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const v = Math.max(r, g, b); const diff = v - Math.min(r, g, b); const diffc = function (c) { return (v - c) / 6 / diff + 1 / 2; }; if (diff === 0) { h = 0; s = 0; } else { s = diff / v; rdif = diffc(r); gdif = diffc(g); bdif = diffc(b); if (r === v) { h = bdif - gdif; } else if (g === v) { h = (1 / 3) + rdif - bdif; } else if (b === v) { h = (2 / 3) + gdif - rdif; } if (h < 0) { h += 1; } else if (h > 1) { h -= 1; } } return [ h * 360, s * 100, v * 100 ]; }; convert.rgb.hwb = function (rgb) { const r = rgb[0]; const g = rgb[1]; let b = rgb[2]; const h = convert.rgb.hsl(rgb)[0]; const w = 1 / 255 * Math.min(r, Math.min(g, b)); b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); return [h, w * 100, b * 100]; }; convert.rgb.cmyk = function (rgb) { const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const k = Math.min(1 - r, 1 - g, 1 - b); const c = (1 - r - k) / (1 - k) || 0; const m = (1 - g - k) / (1 - k) || 0; const y = (1 - b - k) / (1 - k) || 0; return [c * 100, m * 100, y * 100, k * 100]; }; function comparativeDistance(x, y) { /* See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance */ return ( ((x[0] - y[0]) ** 2) + ((x[1] - y[1]) ** 2) + ((x[2] - y[2]) ** 2) ); } convert.rgb.keyword = function (rgb) { const reversed = reverseKeywords[rgb]; if (reversed) { return reversed; } let currentClosestDistance = Infinity; let currentClosestKeyword; for (const keyword of Object.keys(cssKeywords)) { const value = cssKeywords[keyword]; // Compute comparative distance const distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest if (distance < currentClosestDistance) { currentClosestDistance = distance; currentClosestKeyword = keyword; } } return currentClosestKeyword; }; convert.keyword.rgb = function (keyword) { return cssKeywords[keyword]; }; convert.rgb.xyz = function (rgb) { let r = rgb[0] / 255; let g = rgb[1] / 255; let b = rgb[2] / 255; // Assume sRGB r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92); g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92); b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92); const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); return [x * 100, y * 100, z * 100]; }; convert.rgb.lab = function (rgb) { const xyz = convert.rgb.xyz(rgb); let x = xyz[0]; let y = xyz[1]; let z = xyz[2]; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); const l = (116 * y) - 16; const a = 500 * (x - y); const b = 200 * (y - z); return [l, a, b]; }; convert.hsl.rgb = function (hsl) { const h = hsl[0] / 360; const s = hsl[1] / 100; const l = hsl[2] / 100; let t2; let t3; let val; if (s === 0) { val = l * 255; return [val, val, val]; } if (l < 0.5) { t2 = l * (1 + s); } else { t2 = l + s - l * s; } const t1 = 2 * l - t2; const rgb = [0, 0, 0]; for (let i = 0; i < 3; i++) { t3 = h + 1 / 3 * -(i - 1); if (t3 < 0) { t3++; } if (t3 > 1) { t3--; } if (6 * t3 < 1) { val = t1 + (t2 - t1) * 6 * t3; } else if (2 * t3 < 1) { val = t2; } else if (3 * t3 < 2) { val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; } else { val = t1; } rgb[i] = val * 255; } return rgb; }; convert.hsl.hsv = function (hsl) { const h = hsl[0]; let s = hsl[1] / 100; let l = hsl[2] / 100; let smin = s; const lmin = Math.max(l, 0.01); l *= 2; s *= (l <= 1) ? l : 2 - l; smin *= lmin <= 1 ? lmin : 2 - lmin; const v = (l + s) / 2; const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); return [h, sv * 100, v * 100]; }; convert.hsv.rgb = function (hsv) { const h = hsv[0] / 60; const s = hsv[1] / 100; let v = hsv[2] / 100; const hi = Math.floor(h) % 6; const f = h - Math.floor(h); const p = 255 * v * (1 - s); const q = 255 * v * (1 - (s * f)); const t = 255 * v * (1 - (s * (1 - f))); v *= 255; switch (hi) { case 0: return [v, t, p]; case 1: return [q, v, p]; case 2: return [p, v, t]; case 3: return [p, q, v]; case 4: return [t, p, v]; case 5: return [v, p, q]; } }; convert.hsv.hsl = function (hsv) { const h = hsv[0]; const s = hsv[1] / 100; const v = hsv[2] / 100; const vmin = Math.max(v, 0.01); let sl; let l; l = (2 - s) * v; const lmin = (2 - s) * vmin; sl = s * vmin; sl /= (lmin <= 1) ? lmin : 2 - lmin; sl = sl || 0; l /= 2; return [h, sl * 100, l * 100]; }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb convert.hwb.rgb = function (hwb) { const h = hwb[0] / 360; let wh = hwb[1] / 100; let bl = hwb[2] / 100; const ratio = wh + bl; let f; // Wh + bl cant be > 1 if (ratio > 1) { wh /= ratio; bl /= ratio; } const i = Math.floor(6 * h); const v = 1 - bl; f = 6 * h - i; if ((i & 0x01) !== 0) { f = 1 - f; } const n = wh + f * (v - wh); // Linear interpolation let r; let g; let b; /* eslint-disable max-statements-per-line,no-multi-spaces */ switch (i) { default: case 6: case 0: r = v; g = n; b = wh; break; case 1: r = n; g = v; b = wh; break; case 2: r = wh; g = v; b = n; break; case 3: r = wh; g = n; b = v; break; case 4: r = n; g = wh; b = v; break; case 5: r = v; g = wh; b = n; break; } /* eslint-enable max-statements-per-line,no-multi-spaces */ return [r * 255, g * 255, b * 255]; }; convert.cmyk.rgb = function (cmyk) { const c = cmyk[0] / 100; const m = cmyk[1] / 100; const y = cmyk[2] / 100; const k = cmyk[3] / 100; const r = 1 - Math.min(1, c * (1 - k) + k); const g = 1 - Math.min(1, m * (1 - k) + k); const b = 1 - Math.min(1, y * (1 - k) + k); return [r * 255, g * 255, b * 255]; }; convert.xyz.rgb = function (xyz) { const x = xyz[0] / 100; const y = xyz[1] / 100; const z = xyz[2] / 100; let r; let g; let b; r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); // Assume sRGB r = r > 0.0031308 ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055) : r * 12.92; g = g > 0.0031308 ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055) : g * 12.92; b = b > 0.0031308 ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055) : b * 12.92; r = Math.min(Math.max(0, r), 1); g = Math.min(Math.max(0, g), 1); b = Math.min(Math.max(0, b), 1); return [r * 255, g * 255, b * 255]; }; convert.xyz.lab = function (xyz) { let x = xyz[0]; let y = xyz[1]; let z = xyz[2]; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); const l = (116 * y) - 16; const a = 500 * (x - y); const b = 200 * (y - z); return [l, a, b]; }; convert.lab.xyz = function (lab) { const l = lab[0]; const a = lab[1]; const b = lab[2]; let x; let y; let z; y = (l + 16) / 116; x = a / 500 + y; z = y - b / 200; const y2 = y ** 3; const x2 = x ** 3; const z2 = z ** 3; y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; x *= 95.047; y *= 100; z *= 108.883; return [x, y, z]; }; convert.lab.lch = function (lab) { const l = lab[0]; const a = lab[1]; const b = lab[2]; let h; const hr = Math.atan2(b, a); h = hr * 360 / 2 / Math.PI; if (h < 0) { h += 360; } const c = Math.sqrt(a * a + b * b); return [l, c, h]; }; convert.lch.lab = function (lch) { const l = lch[0]; const c = lch[1]; const h = lch[2]; const hr = h / 360 * 2 * Math.PI; const a = c * Math.cos(hr); const b = c * Math.sin(hr); return [l, a, b]; }; convert.rgb.ansi16 = function (args, saturation = null) { const [r, g, b] = args; let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization value = Math.round(value / 50); if (value === 0) { return 30; } let ansi = 30 + ((Math.round(b / 255) << 2) | (Math.round(g / 255) << 1) | Math.round(r / 255)); if (value === 2) { ansi += 60; } return ansi; }; convert.hsv.ansi16 = function (args) { // Optimization here; we already know the value and don't need to get // it converted for us. return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); }; convert.rgb.ansi256 = function (args) { const r = args[0]; const g = args[1]; const b = args[2]; // We use the extended greyscale palette here, with the exception of // black and white. normal palette only has 4 greyscale shades. if (r === g && g === b) { if (r < 8) { return 16; } if (r > 248) { return 231; } return Math.round(((r - 8) / 247) * 24) + 232; } const ansi = 16 + (36 * Math.round(r / 255 * 5)) + (6 * Math.round(g / 255 * 5)) + Math.round(b / 255 * 5); return ansi; }; convert.ansi16.rgb = function (args) { let color = args % 10; // Handle greyscale if (color === 0 || color === 7) { if (args > 50) { color += 3.5; } color = color / 10.5 * 255; return [color, color, color]; } const mult = (~~(args > 50) + 1) * 0.5; const r = ((color & 1) * mult) * 255; const g = (((color >> 1) & 1) * mult) * 255; const b = (((color >> 2) & 1) * mult) * 255; return [r, g, b]; }; convert.ansi256.rgb = function (args) { // Handle greyscale if (args >= 232) { const c = (args - 232) * 10 + 8; return [c, c, c]; } args -= 16; let rem; const r = Math.floor(args / 36) / 5 * 255; const g = Math.floor((rem = args % 36) / 6) / 5 * 255; const b = (rem % 6) / 5 * 255; return [r, g, b]; }; convert.rgb.hex = function (args) { const integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF); const string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert.hex.rgb = function (args) { const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); if (!match) { return [0, 0, 0]; } let colorString = match[0]; if (match[0].length === 3) { colorString = colorString.split('').map(char => { return char + char; }).join(''); } const integer = parseInt(colorString, 16); const r = (integer >> 16) & 0xFF; const g = (integer >> 8) & 0xFF; const b = integer & 0xFF; return [r, g, b]; }; convert.rgb.hcg = function (rgb) { const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const max = Math.max(Math.max(r, g), b); const min = Math.min(Math.min(r, g), b); const chroma = (max - min); let grayscale; let hue; if (chroma < 1) { grayscale = min / (1 - chroma); } else { grayscale = 0; } if (chroma <= 0) { hue = 0; } else if (max === r) { hue = ((g - b) / chroma) % 6; } else if (max === g) { hue = 2 + (b - r) / chroma; } else { hue = 4 + (r - g) / chroma; } hue /= 6; hue %= 1; return [hue * 360, chroma * 100, grayscale * 100]; }; convert.hsl.hcg = function (hsl) { const s = hsl[1] / 100; const l = hsl[2] / 100; const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l)); let f = 0; if (c < 1.0) { f = (l - 0.5 * c) / (1.0 - c); } return [hsl[0], c * 100, f * 100]; }; convert.hsv.hcg = function (hsv) { const s = hsv[1] / 100; const v = hsv[2] / 100; const c = s * v; let f = 0; if (c < 1.0) { f = (v - c) / (1 - c); } return [hsv[0], c * 100, f * 100]; }; convert.hcg.rgb = function (hcg) { const h = hcg[0] / 360; const c = hcg[1] / 100; const g = hcg[2] / 100; if (c === 0.0) { return [g * 255, g * 255, g * 255]; } const pure = [0, 0, 0]; const hi = (h % 1) * 6; const v = hi % 1; const w = 1 - v; let mg = 0; /* eslint-disable max-statements-per-line */ switch (Math.floor(hi)) { case 0: pure[0] = 1; pure[1] = v; pure[2] = 0; break; case 1: pure[0] = w; pure[1] = 1; pure[2] = 0; break; case 2: pure[0] = 0; pure[1] = 1; pure[2] = v; break; case 3: pure[0] = 0; pure[1] = w; pure[2] = 1; break; case 4: pure[0] = v; pure[1] = 0; pure[2] = 1; break; default: pure[0] = 1; pure[1] = 0; pure[2] = w; } /* eslint-enable max-statements-per-line */ mg = (1.0 - c) * g; return [ (c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255 ]; }; convert.hcg.hsv = function (hcg) { const c = hcg[1] / 100; const g = hcg[2] / 100; const v = c + g * (1.0 - c); let f = 0; if (v > 0.0) { f = c / v; } return [hcg[0], f * 100, v * 100]; }; convert.hcg.hsl = function (hcg) { const c = hcg[1] / 100; const g = hcg[2] / 100; const l = g * (1.0 - c) + 0.5 * c; let s = 0; if (l > 0.0 && l < 0.5) { s = c / (2 * l); } else if (l >= 0.5 && l < 1.0) { s = c / (2 * (1 - l)); } return [hcg[0], s * 100, l * 100]; }; convert.hcg.hwb = function (hcg) { const c = hcg[1] / 100; const g = hcg[2] / 100; const v = c + g * (1.0 - c); return [hcg[0], (v - c) * 100, (1 - v) * 100]; }; convert.hwb.hcg = function (hwb) { const w = hwb[1] / 100; const b = hwb[2] / 100; const v = 1 - b; const c = v - w; let g = 0; if (c < 1) { g = (v - c) / (1 - c); } return [hwb[0], c * 100, g * 100]; }; convert.apple.rgb = function (apple) { return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; }; convert.rgb.apple = function (rgb) { return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; }; convert.gray.rgb = function (args) { return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; }; convert.gray.hsl = function (args) { return [0, 0, args[0]]; }; convert.gray.hsv = convert.gray.hsl; convert.gray.hwb = function (gray) { return [0, 100, gray[0]]; }; convert.gray.cmyk = function (gray) { return [0, 0, 0, gray[0]]; }; convert.gray.lab = function (gray) { return [gray[0], 0, 0]; }; convert.gray.hex = function (gray) { const val = Math.round(gray[0] / 100 * 255) & 0xFF; const integer = (val << 16) + (val << 8) + val; const string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert.rgb.gray = function (rgb) { const val = (rgb[0] + rgb[1] + rgb[2]) / 3; return [val / 255 * 100]; }; PK ~\;W $??color-convert/LICENSEnu[Copyright (c) 2011-2016 Heather Arthur Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\w꿬color-convert/index.jsnu[const conversions = require('./conversions'); const route = require('./route'); const convert = {}; const models = Object.keys(conversions); function wrapRaw(fn) { const wrappedFn = function (...args) { const arg0 = args[0]; if (arg0 === undefined || arg0 === null) { return arg0; } if (arg0.length > 1) { args = arg0; } return fn(args); }; // Preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } function wrapRounded(fn) { const wrappedFn = function (...args) { const arg0 = args[0]; if (arg0 === undefined || arg0 === null) { return arg0; } if (arg0.length > 1) { args = arg0; } const result = fn(args); // We're assuming the result is an array here. // see notice in conversions.js; don't use box types // in conversion functions. if (typeof result === 'object') { for (let len = result.length, i = 0; i < len; i++) { result[i] = Math.round(result[i]); } } return result; }; // Preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } models.forEach(fromModel => { convert[fromModel] = {}; Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); const routes = route(fromModel); const routeModels = Object.keys(routes); routeModels.forEach(toModel => { const fn = routes[toModel]; convert[fromModel][toModel] = wrapRounded(fn); convert[fromModel][toModel].raw = wrapRaw(fn); }); }); module.exports = convert; PK ~\ɉ7color-convert/route.jsnu[const conversions = require('./conversions'); /* This function routes a model to all other models. all functions that are routed have a property `.conversion` attached to the returned synthetic function. This property is an array of strings, each with the steps in between the 'from' and 'to' color models (inclusive). conversions that are not possible simply are not included. */ function buildGraph() { const graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3 const models = Object.keys(conversions); for (let len = models.length, i = 0; i < len; i++) { graph[models[i]] = { // http://jsperf.com/1-vs-infinity // micro-opt, but this is simple. distance: -1, parent: null }; } return graph; } // https://en.wikipedia.org/wiki/Breadth-first_search function deriveBFS(fromModel) { const graph = buildGraph(); const queue = [fromModel]; // Unshift -> queue -> pop graph[fromModel].distance = 0; while (queue.length) { const current = queue.pop(); const adjacents = Object.keys(conversions[current]); for (let len = adjacents.length, i = 0; i < len; i++) { const adjacent = adjacents[i]; const node = graph[adjacent]; if (node.distance === -1) { node.distance = graph[current].distance + 1; node.parent = current; queue.unshift(adjacent); } } } return graph; } function link(from, to) { return function (args) { return to(from(args)); }; } function wrapConversion(toModel, graph) { const path = [graph[toModel].parent, toModel]; let fn = conversions[graph[toModel].parent][toModel]; let cur = graph[toModel].parent; while (graph[cur].parent) { path.unshift(graph[cur].parent); fn = link(conversions[graph[cur].parent][cur], fn); cur = graph[cur].parent; } fn.conversion = path; return fn; } module.exports = function (fromModel) { const graph = deriveBFS(fromModel); const conversion = {}; const models = Object.keys(graph); for (let len = models.length, i = 0; i < len; i++) { const toModel = models[i]; const node = graph[toModel]; if (node.parent === null) { // No possible conversion, or this node is the source model. continue; } conversion[toModel] = wrapConversion(toModel, graph); } return conversion; }; PK ~\ Vshebang-regex/package.jsonnu[{ "_id": "shebang-regex@3.0.0", "_inBundle": true, "_location": "/npm/shebang-regex", "_phantomChildren": {}, "_requiredBy": [ "/npm/shebang-command" ], "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "bugs": { "url": "https://github.com/sindresorhus/shebang-regex/issues" }, "description": "Regular expression for matching a shebang line", "devDependencies": { "ava": "^1.4.1", "tsd": "^0.7.2", "xo": "^0.24.0" }, "engines": { "node": ">=8" }, "files": [ "index.js", "index.d.ts" ], "homepage": "https://github.com/sindresorhus/shebang-regex#readme", "keywords": [ "regex", "regexp", "shebang", "match", "test", "line" ], "license": "MIT", "name": "shebang-regex", "repository": { "type": "git", "url": "git+https://github.com/sindresorhus/shebang-regex.git" }, "scripts": { "test": "xo && ava && tsd" }, "version": "3.0.0" } PK ~\Yx**shebang-regex/index.jsnu['use strict'; module.exports = /^#!(.*)/; PK ~\E}UUshebang-regex/licensenu[MIT License Copyright (c) Sindre Sorhus (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\¿kdiff/CONTRIBUTING.mdnu[# How to Contribute ## Pull Requests We also accept [pull requests][pull-request]! Generally we like to see pull requests that - Maintain the existing code style - Are focused on a single change (i.e. avoid large refactoring or style adjustments in untouched code if not the primary goal of the pull request) - Have [good commit messages](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html) - Have tests - Don't decrease the current code coverage (see coverage/lcov-report/index.html) ## Building ``` yarn yarn test ``` Running `yarn test -- dev` will watch for tests within Node and `karma start` may be used for manual testing in browsers. If you notice any problems, please report them to the GitHub issue tracker at [http://github.com/kpdecker/jsdiff/issues](http://github.com/kpdecker/jsdiff/issues). ## Releasing A full release may be completed with the following: ``` yarn clean yarn grunt yarn grunt uglify yarn publish ``` PK ~\Oc c diff/package.jsonnu[{ "_id": "diff@5.2.0", "_inBundle": true, "_location": "/npm/diff", "_phantomChildren": {}, "_requiredBy": [ "/npm/libnpmdiff" ], "browser": "./dist/diff.js", "bugs": { "url": "http://github.com/kpdecker/jsdiff/issues", "email": "kpdecker@gmail.com" }, "dependencies": {}, "description": "A JavaScript text diff implementation.", "devDependencies": { "@babel/cli": "^7.2.3", "@babel/core": "^7.2.2", "@babel/plugin-transform-modules-commonjs": "^7.2.0", "@babel/preset-env": "^7.2.3", "@babel/register": "^7.0.0", "@colors/colors": "^1.3.3", "babel-eslint": "^10.0.1", "babel-loader": "^8.0.5", "chai": "^4.2.0", "eslint": "^5.12.0", "grunt": "^1.0.3", "grunt-babel": "^8.0.0", "grunt-cli": "^1.3.2", "grunt-contrib-clean": "^2.0.0", "grunt-contrib-copy": "^1.0.0", "grunt-contrib-uglify": "^5.0.0", "grunt-contrib-watch": "^1.1.0", "grunt-eslint": "^23.0.0", "grunt-exec": "^3.0.0", "grunt-karma": "^4.0.0", "grunt-mocha-istanbul": "^5.0.2", "grunt-mocha-test": "^0.13.3", "grunt-webpack": "^3.1.3", "istanbul": "github:kpdecker/istanbul", "karma": "^6.3.16", "karma-chrome-launcher": "^3.1.0", "karma-mocha": "^2.0.1", "karma-mocha-reporter": "^2.0.0", "karma-sauce-launcher": "^4.1.5", "karma-sourcemap-loader": "^0.3.6", "karma-webpack": "^4.0.2", "mocha": "^6.0.0", "rollup": "^1.0.2", "rollup-plugin-babel": "^4.2.0", "semver": "^7.3.2", "webpack": "^4.28.3", "webpack-dev-server": "^3.1.14" }, "engines": { "node": ">=0.3.1" }, "exports": { ".": { "import": "./lib/index.mjs", "require": "./lib/index.js" }, "./package.json": "./package.json", "./": "./", "./*": "./*" }, "homepage": "https://github.com/kpdecker/jsdiff#readme", "keywords": [ "diff", "jsdiff", "compare", "patch", "text", "json", "css", "javascript" ], "license": "BSD-3-Clause", "main": "./lib/index.js", "maintainers": [ { "name": "Kevin Decker", "email": "kpdecker@gmail.com", "url": "http://incaseofstairs.com" }, { "name": "Mark Amery", "email": "markrobertamery+jsdiff@gmail.com" } ], "module": "./lib/index.es6.js", "name": "diff", "optionalDependencies": {}, "repository": { "type": "git", "url": "git://github.com/kpdecker/jsdiff.git" }, "scripts": { "build:node": "yarn babel --out-dir lib --source-maps=inline src", "clean": "rm -rf lib/ dist/", "test": "grunt" }, "unpkg": "./dist/diff.js", "version": "5.2.0" } PK ~\aـEEdiff/lib/patch/parse.jsnu[/*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parsePatch = parsePatch; /*istanbul ignore end*/ function parsePatch(uniDiff) { /*istanbul ignore start*/ var /*istanbul ignore end*/ options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/), delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [], list = [], i = 0; function parseIndex() { var index = {}; list.push(index); // Parse diff metadata while (i < diffstr.length) { var line = diffstr[i]; // File header found, end parsing diff metadata if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) { break; } // Diff index var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line); if (header) { index.index = header[1]; } i++; } // Parse file headers if they are defined. Unified diff requires them, but // there's no technical issues to have an isolated hunk without file header parseFileHeader(index); parseFileHeader(index); // Parse hunks index.hunks = []; while (i < diffstr.length) { var _line = diffstr[i]; if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) { break; } else if (/^@@/.test(_line)) { index.hunks.push(parseHunk()); } else if (_line && options.strict) { // Ignore unexpected content unless in strict mode throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line)); } else { i++; } } } // Parses the --- and +++ headers, if none are found, no lines // are consumed. function parseFileHeader(index) { var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]); if (fileHeader) { var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new'; var data = fileHeader[2].split('\t', 2); var fileName = data[0].replace(/\\\\/g, '\\'); if (/^".*"$/.test(fileName)) { fileName = fileName.substr(1, fileName.length - 2); } index[keyPrefix + 'FileName'] = fileName; index[keyPrefix + 'Header'] = (data[1] || '').trim(); i++; } } // Parses a hunk // This assumes that we are at the start of a hunk. function parseHunk() { var chunkHeaderIndex = i, chunkHeaderLine = diffstr[i++], chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); var hunk = { oldStart: +chunkHeader[1], oldLines: typeof chunkHeader[2] === 'undefined' ? 1 : +chunkHeader[2], newStart: +chunkHeader[3], newLines: typeof chunkHeader[4] === 'undefined' ? 1 : +chunkHeader[4], lines: [], linedelimiters: [] }; // Unified Diff Format quirk: If the chunk size is 0, // the first number is one lower than one would expect. // https://www.artima.com/weblogs/viewpost.jsp?thread=164293 if (hunk.oldLines === 0) { hunk.oldStart += 1; } if (hunk.newLines === 0) { hunk.newStart += 1; } var addCount = 0, removeCount = 0; for (; i < diffstr.length; i++) { // Lines starting with '---' could be mistaken for the "remove line" operation // But they could be the header for the next file. Therefore prune such cases out. if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) { break; } var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0]; if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { hunk.lines.push(diffstr[i]); hunk.linedelimiters.push(delimiters[i] || '\n'); if (operation === '+') { addCount++; } else if (operation === '-') { removeCount++; } else if (operation === ' ') { addCount++; removeCount++; } } else { break; } } // Handle the empty block count case if (!addCount && hunk.newLines === 1) { hunk.newLines = 0; } if (!removeCount && hunk.oldLines === 1) { hunk.oldLines = 0; } // Perform optional sanity checking if (options.strict) { if (addCount !== hunk.newLines) { throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); } if (removeCount !== hunk.oldLines) { throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); } } return hunk; } while (i < diffstr.length) { parseIndex(); } return list; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wYXRjaC9wYXJzZS5qcyJdLCJuYW1lcyI6WyJwYXJzZVBhdGNoIiwidW5pRGlmZiIsIm9wdGlvbnMiLCJkaWZmc3RyIiwic3BsaXQiLCJkZWxpbWl0ZXJzIiwibWF0Y2giLCJsaXN0IiwiaSIsInBhcnNlSW5kZXgiLCJpbmRleCIsInB1c2giLCJsZW5ndGgiLCJsaW5lIiwidGVzdCIsImhlYWRlciIsImV4ZWMiLCJwYXJzZUZpbGVIZWFkZXIiLCJodW5rcyIsInBhcnNlSHVuayIsInN0cmljdCIsIkVycm9yIiwiSlNPTiIsInN0cmluZ2lmeSIsImZpbGVIZWFkZXIiLCJrZXlQcmVmaXgiLCJkYXRhIiwiZmlsZU5hbWUiLCJyZXBsYWNlIiwic3Vic3RyIiwidHJpbSIsImNodW5rSGVhZGVySW5kZXgiLCJjaHVua0hlYWRlckxpbmUiLCJjaHVua0hlYWRlciIsImh1bmsiLCJvbGRTdGFydCIsIm9sZExpbmVzIiwibmV3U3RhcnQiLCJuZXdMaW5lcyIsImxpbmVzIiwibGluZWRlbGltaXRlcnMiLCJhZGRDb3VudCIsInJlbW92ZUNvdW50IiwiaW5kZXhP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9wdGlvbnMuc3RyaWN0KSB7XG4gICAgICBpZiAoYWRkQ291bnQgIT09IGh1bmsubmV3TGluZXMpIHtcbiAgICAgICAgdGhyb3cgbmV3IEVycm9yKCdBZGRlZCBsaW5lIGNvdW50IGRpZCBub3QgbWF0Y2ggZm9yIGh1bmsgYXQgbGluZSAnICsgKGNodW5rSGVhZGVySW5kZXggKyAxKSk7XG4gICAgICB9XG4gICAgICBpZiAocmVtb3ZlQ291bnQgIT09IGh1bmsub2xkTGluZXMpIHtcbiAgICAgICAgdGhyb3cgbmV3IEVycm9yKCdSZW1vdmVkIGxpbmUgY291bnQgZGlkIG5vdCBtYXRjaCBmb3IgaHVuayBhdCBsaW5lICcgKyAoY2h1bmtIZWFkZXJJbmRleCArIDEpKTtcbiAgICAgIH1cbiAgICB9XG5cbiAgICByZXR1cm4gaHVuaztcbiAgfVxuXG4gIHdoaWxlIChpIDwgZGlmZnN0ci5sZW5ndGgpIHtcbiAgICBwYXJzZUluZGV4KCk7XG4gIH1cblxuICByZXR1cm4gbGlzdDtcbn1cbiJdfQ== PK ~\91diff/lib/patch/merge.jsnu[/*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.calcLineCount = calcLineCount; exports.merge = merge; /*istanbul ignore end*/ var /*istanbul ignore start*/ _create = require("./create") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _parse = require("./parse") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _array = require("../util/array") /*istanbul ignore end*/ ; /*istanbul ignore start*/ function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } /*istanbul ignore end*/ function calcLineCount(hunk) { /*istanbul ignore start*/ var _calcOldNewLineCount = /*istanbul ignore end*/ calcOldNewLineCount(hunk.lines), oldLines = _calcOldNewLineCount.oldLines, newLines = _calcOldNewLineCount.newLines; if (oldLines !== undefined) { hunk.oldLines = oldLines; } else { delete hunk.oldLines; } if (newLines !== undefined) { hunk.newLines = newLines; } else { delete hunk.newLines; } } function merge(mine, theirs, base) { mine = loadPatch(mine, base); theirs = loadPatch(theirs, base); var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning. // Leaving sanity checks on this to the API consumer that may know more about the // meaning in their own context. if (mine.index || theirs.index) { ret.index = mine.index || theirs.index; } if (mine.newFileName || theirs.newFileName) { if (!fileNameChanged(mine)) { // No header or no change in ours, use theirs (and ours if theirs does not exist) ret.oldFileName = theirs.oldFileName || mine.oldFileName; ret.newFileName = theirs.newFileName || mine.newFileName; ret.oldHeader = theirs.oldHeader || mine.oldHeader; ret.newHeader = theirs.newHeader || mine.newHeader; } else if (!fileNameChanged(theirs)) { // No header or no change in theirs, use ours ret.oldFileName = mine.oldFileName; ret.newFileName = mine.newFileName; ret.oldHeader = mine.oldHeader; ret.newHeader = mine.newHeader; } else { // Both changed... figure it out ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName); ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName); ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader); ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader); } } ret.hunks = []; var mineIndex = 0, theirsIndex = 0, mineOffset = 0, theirsOffset = 0; while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) { var mineCurrent = mine.hunks[mineIndex] || { oldStart: Infinity }, theirsCurrent = theirs.hunks[theirsIndex] || { oldStart: Infinity }; if (hunkBefore(mineCurrent, theirsCurrent)) { // This patch does not overlap with any of the others, yay. ret.hunks.push(cloneHunk(mineCurrent, mineOffset)); mineIndex++; theirsOffset += mineCurrent.newLines - mineCurrent.oldLines; } else if (hunkBefore(theirsCurrent, mineCurrent)) { // This patch does not overlap with any of the others, yay. ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset)); theirsIndex++; mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines; } else { // Overlap, merge as best we can var mergedHunk = { oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart), oldLines: 0, newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset), newLines: 0, lines: [] }; mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines); theirsIndex++; mineIndex++; ret.hunks.push(mergedHunk); } } return ret; } function loadPatch(param, base) { if (typeof param === 'string') { if (/^@@/m.test(param) || /^Index:/m.test(param)) { return ( /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _parse /*istanbul ignore end*/ . /*istanbul ignore start*/ parsePatch) /*istanbul ignore end*/ (param)[0] ); } if (!base) { throw new Error('Must provide a base reference or pass in a patch'); } return ( /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _create /*istanbul ignore end*/ . /*istanbul ignore start*/ structuredPatch) /*istanbul ignore end*/ (undefined, undefined, base, param) ); } return param; } function fileNameChanged(patch) { return patch.newFileName && patch.newFileName !== patch.oldFileName; } function selectField(index, mine, theirs) { if (mine === theirs) { return mine; } else { index.conflict = true; return { mine: mine, theirs: theirs }; } } function hunkBefore(test, check) { return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart; } function cloneHunk(hunk, offset) { return { oldStart: hunk.oldStart, oldLines: hunk.oldLines, newStart: hunk.newStart + offset, newLines: hunk.newLines, lines: hunk.lines }; } function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) { // This will generally result in a conflicted hunk, but there are cases where the context // is the only overlap where we can successfully merge the content here. var mine = { offset: mineOffset, lines: mineLines, index: 0 }, their = { offset: theirOffset, lines: theirLines, index: 0 }; // Handle any leading content insertLeading(hunk, mine, their); insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each. while (mine.index < mine.lines.length && their.index < their.lines.length) { var mineCurrent = mine.lines[mine.index], theirCurrent = their.lines[their.index]; if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) { // Both modified ... mutualChange(hunk, mine, their); } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') { /*istanbul ignore start*/ var _hunk$lines; /*istanbul ignore end*/ // Mine inserted /*istanbul ignore start*/ /*istanbul ignore end*/ /*istanbul ignore start*/ (_hunk$lines = /*istanbul ignore end*/ hunk.lines).push.apply( /*istanbul ignore start*/ _hunk$lines /*istanbul ignore end*/ , /*istanbul ignore start*/ _toConsumableArray( /*istanbul ignore end*/ collectChange(mine))); } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') { /*istanbul ignore start*/ var _hunk$lines2; /*istanbul ignore end*/ // Theirs inserted /*istanbul ignore start*/ /*istanbul ignore end*/ /*istanbul ignore start*/ (_hunk$lines2 = /*istanbul ignore end*/ hunk.lines).push.apply( /*istanbul ignore start*/ _hunk$lines2 /*istanbul ignore end*/ , /*istanbul ignore start*/ _toConsumableArray( /*istanbul ignore end*/ collectChange(their))); } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') { // Mine removed or edited removal(hunk, mine, their); } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') { // Their removed or edited removal(hunk, their, mine, true); } else if (mineCurrent === theirCurrent) { // Context identity hunk.lines.push(mineCurrent); mine.index++; their.index++; } else { // Context mismatch conflict(hunk, collectChange(mine), collectChange(their)); } } // Now push anything that may be remaining insertTrailing(hunk, mine); insertTrailing(hunk, their); calcLineCount(hunk); } function mutualChange(hunk, mine, their) { var myChanges = collectChange(mine), theirChanges = collectChange(their); if (allRemoves(myChanges) && allRemoves(theirChanges)) { // Special case for remove changes that are supersets of one another if ( /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _array /*istanbul ignore end*/ . /*istanbul ignore start*/ arrayStartsWith) /*istanbul ignore end*/ (myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) { /*istanbul ignore start*/ var _hunk$lines3; /*istanbul ignore end*/ /*istanbul ignore start*/ /*istanbul ignore end*/ /*istanbul ignore start*/ (_hunk$lines3 = /*istanbul ignore end*/ hunk.lines).push.apply( /*istanbul ignore start*/ _hunk$lines3 /*istanbul ignore end*/ , /*istanbul ignore start*/ _toConsumableArray( /*istanbul ignore end*/ myChanges)); return; } else if ( /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _array /*istanbul ignore end*/ . /*istanbul ignore start*/ arrayStartsWith) /*istanbul ignore end*/ (theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) { /*istanbul ignore start*/ var _hunk$lines4; /*istanbul ignore end*/ /*istanbul ignore start*/ /*istanbul ignore end*/ /*istanbul ignore start*/ (_hunk$lines4 = /*istanbul ignore end*/ hunk.lines).push.apply( /*istanbul ignore start*/ _hunk$lines4 /*istanbul ignore end*/ , /*istanbul ignore start*/ _toConsumableArray( /*istanbul ignore end*/ theirChanges)); return; } } else if ( /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _array /*istanbul ignore end*/ . /*istanbul ignore start*/ arrayEqual) /*istanbul ignore end*/ (myChanges, theirChanges)) { /*istanbul ignore start*/ var _hunk$lines5; /*istanbul ignore end*/ /*istanbul ignore start*/ /*istanbul ignore end*/ /*istanbul ignore start*/ (_hunk$lines5 = /*istanbul ignore end*/ hunk.lines).push.apply( /*istanbul ignore start*/ _hunk$lines5 /*istanbul ignore end*/ , /*istanbul ignore start*/ _toConsumableArray( /*istanbul ignore end*/ myChanges)); return; } conflict(hunk, myChanges, theirChanges); } function removal(hunk, mine, their, swap) { var myChanges = collectChange(mine), theirChanges = collectContext(their, myChanges); if (theirChanges.merged) { /*istanbul ignore start*/ var _hunk$lines6; /*istanbul ignore end*/ /*istanbul ignore start*/ /*istanbul ignore end*/ /*istanbul ignore start*/ (_hunk$lines6 = /*istanbul ignore end*/ hunk.lines).push.apply( /*istanbul ignore start*/ _hunk$lines6 /*istanbul ignore end*/ , /*istanbul ignore start*/ _toConsumableArray( /*istanbul ignore end*/ theirChanges.merged)); } else { conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges); } } function conflict(hunk, mine, their) { hunk.conflict = true; hunk.lines.push({ conflict: true, mine: mine, theirs: their }); } function insertLeading(hunk, insert, their) { while (insert.offset < their.offset && insert.index < insert.lines.length) { var line = insert.lines[insert.index++]; hunk.lines.push(line); insert.offset++; } } function insertTrailing(hunk, insert) { while (insert.index < insert.lines.length) { var line = insert.lines[insert.index++]; hunk.lines.push(line); } } function collectChange(state) { var ret = [], operation = state.lines[state.index][0]; while (state.index < state.lines.length) { var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change. if (operation === '-' && line[0] === '+') { operation = '+'; } if (operation === line[0]) { ret.push(line); state.index++; } else { break; } } return ret; } function collectContext(state, matchChanges) { var changes = [], merged = [], matchIndex = 0, contextChanges = false, conflicted = false; while (matchIndex < matchChanges.length && state.index < state.lines.length) { var change = state.lines[state.index], match = matchChanges[matchIndex]; // Once we've hit our add, then we are done if (match[0] === '+') { break; } contextChanges = contextChanges || change[0] !== ' '; merged.push(match); matchIndex++; // Consume any additions in the other block as a conflict to attempt // to pull in the remaining context after this if (change[0] === '+') { conflicted = true; while (change[0] === '+') { changes.push(change); change = state.lines[++state.index]; } } if (match.substr(1) === change.substr(1)) { changes.push(change); state.index++; } else { conflicted = true; } } if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) { conflicted = true; } if (conflicted) { return changes; } while (matchIndex < matchChanges.length) { merged.push(matchChanges[matchIndex++]); } return { merged: merged, changes: changes }; } function allRemoves(changes) { return changes.reduce(function (prev, change) { return prev && change[0] === '-'; }, true); } function skipRemoveSuperset(state, removeChanges, delta) { for (var i = 0; i < delta; i++) { var changeContent = removeChanges[removeChanges.length - delta + i].substr(1); if (state.lines[state.index + i] !== ' ' + changeContent) { return false; } } state.index += delta; return true; } function calcOldNewLineCount(lines) { var oldLines = 0; var newLines = 0; lines.forEach(function (line) { if (typeof line !== 'string') { var myCount = calcOldNewLineCount(line.mine); var theirCount = calcOldNewLineCount(line.theirs); if (oldLines !== undefined) { if (myCount.oldLines === theirCount.oldLines) { oldLines += myCount.oldLines; } else { oldLines = undefined; } } if (newLines !== undefined) { if (myCount.newLines === theirCount.newLines) { newLines += myCount.newLines; } else { newLines = undefined; } } } else { if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) { newLines++; } if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) { oldLines++; } } }); return { oldLines: oldLines, newLines: newLines }; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wYXRjaC9tZXJnZS5qcyJdLCJuYW1lcyI6WyJjYWxjTGluZUNvdW50IiwiaHVuayIsImNhbGNPbGROZXdMaW5lQ291bnQiLCJsaW5lcyIsIm9sZExpbmVzIiwibmV3TGluZXMiLCJ1bmRlZmluZWQiLCJtZXJnZSIsIm1pbmUiLCJ0aGVpcnMiLCJiYXNlIiwibG9hZFBhdGNoIiwicmV0IiwiaW5kZXgiLC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xjT2xkTmV3TGluZUNvdW50KGxpbmVzKSB7XG4gIGxldCBvbGRMaW5lcyA9IDA7XG4gIGxldCBuZXdMaW5lcyA9IDA7XG5cbiAgbGluZXMuZm9yRWFjaChmdW5jdGlvbihsaW5lKSB7XG4gICAgaWYgKHR5cGVvZiBsaW5lICE9PSAnc3RyaW5nJykge1xuICAgICAgbGV0IG15Q291bnQgPSBjYWxjT2xkTmV3TGluZUNvdW50KGxpbmUubWluZSk7XG4gICAgICBsZXQgdGhlaXJDb3VudCA9IGNhbGNPbGROZXdMaW5lQ291bnQobGluZS50aGVpcnMpO1xuXG4gICAgICBpZiAob2xkTGluZXMgIT09IHVuZGVmaW5lZCkge1xuICAgICAgICBpZiAobXlDb3VudC5vbGRMaW5lcyA9PT0gdGhlaXJDb3VudC5vbGRMaW5lcykge1xuICAgICAgICAgIG9sZExpbmVzICs9IG15Q291bnQub2xkTGluZXM7XG4gICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgb2xkTGluZXMgPSB1bmRlZmluZWQ7XG4gICAgICAgIH1cbiAgICAgIH1cblxuICAgICAgaWYgKG5ld0xpbmVzICE9PSB1bmRlZmluZWQpIHtcbiAgICAgICAgaWYgKG15Q291bnQubmV3TGluZXMgPT09IHRoZWlyQ291bnQubmV3TGluZXMpIHtcbiAgICAgICAgICBuZXdMaW5lcyArPSBteUNvdW50Lm5ld0xpbmVzO1xuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgIG5ld0xpbmVzID0gdW5kZWZpbmVkO1xuICAgICAgICB9XG4gICAgICB9XG4gICAgfSBlbHNlIHtcbiAgICAgIGlmIChuZXdMaW5lcyAhPT0gdW5kZWZpbmVkICYmIChsaW5lWzBdID09PSAnKycgfHwgbGluZVswXSA9PT0gJyAnKSkge1xuICAgICAgICBuZXdMaW5lcysrO1xuICAgICAgfVxuICAgICAgaWYgKG9sZExpbmVzICE9PSB1bmRlZmluZWQgJiYgKGxpbmVbMF0gPT09ICctJyB8fCBsaW5lWzBdID09PSAnICcpKSB7XG4gICAgICAgIG9sZExpbmVzKys7XG4gICAgICB9XG4gICAgfVxuICB9KTtcblxuICByZXR1cm4ge29sZExpbmVzLCBuZXdMaW5lc307XG59XG4iXX0= PK ~\eHCdiff/lib/patch/reverse.jsnu[/*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.reversePatch = reversePatch; function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } /*istanbul ignore end*/ function reversePatch(structuredPatch) { if (Array.isArray(structuredPatch)) { return structuredPatch.map(reversePatch).reverse(); } return ( /*istanbul ignore start*/ _objectSpread(_objectSpread({}, /*istanbul ignore end*/ structuredPatch), {}, { oldFileName: structuredPatch.newFileName, oldHeader: structuredPatch.newHeader, newFileName: structuredPatch.oldFileName, newHeader: structuredPatch.oldHeader, hunks: structuredPatch.hunks.map(function (hunk) { return { oldLines: hunk.newLines, oldStart: hunk.newStart, newLines: hunk.oldLines, newStart: hunk.oldStart, linedelimiters: hunk.linedelimiters, lines: hunk.lines.map(function (l) { if (l.startsWith('-')) { return ( /*istanbul ignore start*/ "+".concat( /*istanbul ignore end*/ l.slice(1)) ); } if (l.startsWith('+')) { return ( /*istanbul ignore start*/ "-".concat( /*istanbul ignore end*/ l.slice(1)) ); } return l; }) }; }) }) ); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wYXRjaC9yZXZlcnNlLmpzIl0sIm5hbWVzIjpbInJldmVyc2VQYXRjaCIsInN0cnVjdHVyZWRQYXRjaCIsIkFycmF5IiwiaXNBcnJheSIsIm1hcCIsInJldmVyc2UiLCJvbGRGaWxlTmFtZSIsIm5ld0ZpbGVOYW1lIiwib2xkSGVhZGVyIiwibmV3SGVhZGVyIiwiaHVua3MiLCJodW5rIiwib2xkTGluZXMiLCJuZXdMaW5lcyIsIm9sZFN0YXJ0IiwibmV3U3RhcnQiLCJsaW5lZGVsaW1pdGVycyIsImxpbmVzIiwibCIsInN0YXJ0c1dpdGgiLCJzbGljZSJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7Ozs7O0FBQU8sU0FBU0EsWUFBVCxDQUFzQkMsZUFBdEIsRUFBdUM7QUFDNUMsTUFBSUMsS0FBSyxDQUFDQyxPQUFOLENBQWNGLGVBQWQsQ0FBSixFQUFvQztBQUNsQyxXQUFPQSxlQUFlLENBQUNHLEdBQWhCLENBQW9CSixZQUFwQixFQUFrQ0ssT0FBbEMsRUFBUDtBQUNEOztBQUVEO0FBQUE7QUFBQTtBQUFBO0FBQ0tKLElBQUFBLGVBREw7QUFFRUssTUFBQUEsV0FBVyxFQUFFTCxlQUFlLENBQUNNLFdBRi9CO0FBR0VDLE1BQUFBLFNBQVMsRUFBRVAsZUFBZSxDQUFDUSxTQUg3QjtBQUlFRixNQUFBQSxXQUFXLEVBQUVOLGVBQWUsQ0FBQ0ssV0FKL0I7QUFLRUcsTUFBQUEsU0FBUyxFQUFFUixlQUFlLENBQUNPLFNBTDdCO0FBTUVFLE1BQUFBLEtBQUssRUFBRVQsZUFBZSxDQUFDUyxLQUFoQixDQUFzQk4sR0F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SgpO1xuICB9XG5cbiAgcmV0dXJuIHtcbiAgICAuLi5zdHJ1Y3R1cmVkUGF0Y2gsXG4gICAgb2xkRmlsZU5hbWU6IHN0cnVjdHVyZWRQYXRjaC5uZXdGaWxlTmFtZSxcbiAgICBvbGRIZWFkZXI6IHN0cnVjdHVyZWRQYXRjaC5uZXdIZWFkZXIsXG4gICAgbmV3RmlsZU5hbWU6IHN0cnVjdHVyZWRQYXRjaC5vbGRGaWxlTmFtZSxcbiAgICBuZXdIZWFkZXI6IHN0cnVjdHVyZWRQYXRjaC5vbGRIZWFkZXIsXG4gICAgaHVua3M6IHN0cnVjdHVyZWRQYXRjaC5odW5rcy5tYXAoaHVuayA9PiB7XG4gICAgICByZXR1cm4ge1xuICAgICAgICBvbGRMaW5lczogaHVuay5uZXdMaW5lcyxcbiAgICAgICAgb2xkU3RhcnQ6IGh1bmsubmV3U3RhcnQsXG4gICAgICAgIG5ld0xpbmVzOiBodW5rLm9sZExpbmVzLFxuICAgICAgICBuZXdTdGFydDogaHVuay5vbGRTdGFydCxcbiAgICAgICAgbGluZWRlbGltaXRlcnM6IGh1bmsubGluZWRlbGltaXRlcnMsXG4gICAgICAgIGxpbmVzOiBodW5rLmxpbmVzLm1hcChsID0+IHtcbiAgICAgICAgICBpZiAobC5zdGFydHNXaXRoKCctJykpIHsgcmV0dXJuIGArJHtsLnNsaWNlKDEpfWA7IH1cbiAgICAgICAgICBpZiAobC5zdGFydHNXaXRoKCcrJykpIHsgcmV0dXJuIGAtJHtsLnNsaWNlKDEpfWA7IH1cbiAgICAgICAgICByZXR1cm4gbDtcbiAgICAgICAgfSlcbiAgICAgIH07XG4gICAgfSlcbiAgfTtcbn1cbiJdfQ== PK ~\02RNRNdiff/lib/patch/apply.jsnu[/*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.applyPatch = applyPatch; exports.applyPatches = applyPatches; /*istanbul ignore end*/ var /*istanbul ignore start*/ _parse = require("./parse") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _distanceIterator = _interopRequireDefault(require("../util/distance-iterator")) /*istanbul ignore end*/ ; /*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } /*istanbul ignore end*/ function applyPatch(source, uniDiff) { /*istanbul ignore start*/ var /*istanbul ignore end*/ options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; if (typeof uniDiff === 'string') { uniDiff = /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _parse /*istanbul ignore end*/ . /*istanbul ignore start*/ parsePatch) /*istanbul ignore end*/ (uniDiff); } if (Array.isArray(uniDiff)) { if (uniDiff.length > 1) { throw new Error('applyPatch only works with a single input.'); } uniDiff = uniDiff[0]; } // Apply the diff to the input var lines = source.split(/\r\n|[\n\v\f\r\x85]/), delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [], hunks = uniDiff.hunks, compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) /*istanbul ignore start*/ { return ( /*istanbul ignore end*/ line === patchContent ); }, errorCount = 0, fuzzFactor = options.fuzzFactor || 0, minLine = 0, offset = 0, removeEOFNL, addEOFNL; /** * Checks if the hunk exactly fits on the provided location */ function hunkFits(hunk, toPos) { for (var j = 0; j < hunk.lines.length; j++) { var line = hunk.lines[j], operation = line.length > 0 ? line[0] : ' ', content = line.length > 0 ? line.substr(1) : line; if (operation === ' ' || operation === '-') { // Context sanity check if (!compareLine(toPos + 1, lines[toPos], operation, content)) { errorCount++; if (errorCount > fuzzFactor) { return false; } } toPos++; } } return true; } // Search best fit offsets for each hunk based on the previous ones for (var i = 0; i < hunks.length; i++) { var hunk = hunks[i], maxLine = lines.length - hunk.oldLines, localOffset = 0, toPos = offset + hunk.oldStart - 1; var iterator = /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _distanceIterator /*istanbul ignore end*/ [ /*istanbul ignore start*/ "default" /*istanbul ignore end*/ ])(toPos, minLine, maxLine); for (; localOffset !== undefined; localOffset = iterator()) { if (hunkFits(hunk, toPos + localOffset)) { hunk.offset = offset += localOffset; break; } } if (localOffset === undefined) { return false; } // Set lower text limit to end of the current hunk, so next ones don't try // to fit over already patched text minLine = hunk.offset + hunk.oldStart + hunk.oldLines; } // Apply patch hunks var diffOffset = 0; for (var _i = 0; _i < hunks.length; _i++) { var _hunk = hunks[_i], _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1; diffOffset += _hunk.newLines - _hunk.oldLines; for (var j = 0; j < _hunk.lines.length; j++) { var line = _hunk.lines[j], operation = line.length > 0 ? line[0] : ' ', content = line.length > 0 ? line.substr(1) : line, delimiter = _hunk.linedelimiters && _hunk.linedelimiters[j] || '\n'; if (operation === ' ') { _toPos++; } else if (operation === '-') { lines.splice(_toPos, 1); delimiters.splice(_toPos, 1); /* istanbul ignore else */ } else if (operation === '+') { lines.splice(_toPos, 0, content); delimiters.splice(_toPos, 0, delimiter); _toPos++; } else if (operation === '\\') { var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null; if (previousOperation === '+') { removeEOFNL = true; } else if (previousOperation === '-') { addEOFNL = true; } } } } // Handle EOFNL insertion/removal if (removeEOFNL) { while (!lines[lines.length - 1]) { lines.pop(); delimiters.pop(); } } else if (addEOFNL) { lines.push(''); delimiters.push('\n'); } for (var _k = 0; _k < lines.length - 1; _k++) { lines[_k] = lines[_k] + delimiters[_k]; } return lines.join(''); } // Wrapper that supports multiple file patches via callbacks. function applyPatches(uniDiff, options) { if (typeof uniDiff === 'string') { uniDiff = /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _parse /*istanbul ignore end*/ . /*istanbul ignore start*/ parsePatch) /*istanbul ignore end*/ (uniDiff); } var currentIndex = 0; function processIndex() { var index = uniDiff[currentIndex++]; if (!index) { return options.complete(); } options.loadFile(index, function (err, data) { if (err) { return options.complete(err); } var updatedContent = applyPatch(data, index, options); options.patched(index, updatedContent, function (err) { if (err) { return options.complete(err); } processIndex(); }); }); } processIndex(); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wYXRjaC9hcHBseS5qcyJdLCJuYW1lcyI6WyJhcHBseVBhdGNoIiwic291cmNlIiwidW5pRGlmZiIsIm9wdGlvbnMiLCJwYXJzZVBhdGNoIiwiQXJyYXkiLCJpc0FycmF5IiwibGVuZ3RoIiwiRXJyb3IiLCJsaW5lcyIsInNwbGl0IiwiZGVsaW1pdGVycyIsIm1hdGNoIiwiaHVua3MiLCJjb21wYXJlTGluZSIsImxpbmVOdW1iZXIiLCJsaW5lIiwib3BlcmF0aW9uIiwicGF0Y2hDb250ZW50IiwiZXJyb3JDb3VudCIsImZ1enpGYWN0b3IiLCJtaW5MaW5lIiwib2Zmc2V0IiwicmVtb3ZlRU9GTkwiLCJhZGRFT0ZOTCIsImh1bmtGaXRzIiwiaHVuayIsInRvUG9zIiwiaiIsImNvbnRlbnQiLCJzdWJzdHIiLCJpIiwibWF4TGluZSIsIm9sZExpbmVzIiwibG9jYWxPZmZzZXQiLCJvbGRTdGFydCIsIml0ZXJhdG9yIiwiZGlzdGFuY2VJdGVyYXRvciIsInVuZGVmaW5lZCIsImRpZmZPZmZzZXQiLCJuZXdMaW5lcyIsImRlbGltaXRlciIsImxpbmVkZWxpbWl0ZXJzIiwic3BsaWNlIiwicHJldmlvdXNPcGVyYXRpb24iLCJwb3AiLCJwdXNoIiwiX2siLCJqb2luIiwiYXBwbHlQYXRjaGVzIiwiY3VycmVudEluZGV4IiwicHJvY2Vzc0luZGV4IiwiaW5kZXgiLCJjb21wbGV0ZSIsImxvYWRGaWxlIiwiZXJyIiwiZGF0YSIsInVwZGF0ZWRDb250ZW50IiwicGF0Y2hlZCJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7OztBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7O0FBQ0E7QUFBQTtBQUFBO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XRpb24gPSAobGluZS5sZW5ndGggPiAwID8gbGluZVswXSA6ICcgJyksXG4gICAgICAgICAgY29udGVudCA9IChsaW5lLmxlbmd0aCA+IDAgPyBsaW5lLnN1YnN0cigxKSA6IGxpbmUpLFxuICAgICAgICAgIGRlbGltaXRlciA9IGh1bmsubGluZWRlbGltaXRlcnMgJiYgaHVuay5saW5lZGVsaW1pdGVyc1tqXSB8fCAnXFxuJztcblxuICAgICAgaWYgKG9wZXJhdGlvbiA9PT0gJyAnKSB7XG4gICAgICAgIHRvUG9zKys7XG4gICAgICB9IGVsc2UgaWYgKG9wZXJhdGlvbiA9PT0gJy0nKSB7XG4gICAgICAgIGxpbmVzLnNwbGljZSh0b1BvcywgMSk7XG4gICAgICAgIGRlbGltaXRlcnMuc3BsaWNlKHRvUG9zLCAxKTtcbiAgICAgIC8qIGlzdGFuYnVsIGlnbm9yZSBlbHNlICovXG4gICAgICB9IGVsc2UgaWYgKG9wZXJhdGlvbiA9PT0gJysnKSB7XG4gICAgICAgIGxpbmVzLnNwbGljZSh0b1BvcywgMCwgY29udGVudCk7XG4gICAgICAgIGRlbGltaXRlcnMuc3BsaWNlKHRvUG9zLCAwLCBkZWxpbWl0ZXIpO1xuICAgICAgICB0b1BvcysrO1xuICAgICAgfSBlbHNlIGlmIChvcGVyYXRpb24gPT09ICdcXFxcJykge1xuICAgICAgICBsZXQgcHJldmlvdXNPcGVyYXRpb24gPSBodW5rLmxpbmVzW2ogLSAxXSA/IGh1bmsubGluZXNbaiAtIDFdWzBdIDogbnVsbDtcbiAgICAgICAgaWYgKHByZXZpb3VzT3BlcmF0aW9uID09PSAnKycpIHtcbiAgICAgICAgICByZW1vdmVFT0ZOTCA9IHRydWU7XG4gICAgICAgIH0gZWxzZSBpZiAocHJldmlvdXNPcGVyYXRpb24gPT09ICctJykge1xuICAgICAgICAgIGFkZEVPRk5MID0gdHJ1ZTtcbiAgICAgICAgfVxuICAgICAgfVxuICAgIH1cbiAgfVxuXG4gIC8vIEhh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tcbiAgICAgIH1cblxuICAgICAgbGV0IHVwZGF0ZWRDb250ZW50ID0gYXBwbHlQYXRjaChkYXRhLCBpbmRleCwgb3B0aW9ucyk7XG4gICAgICBvcHRpb25zLnBhdGNoZWQoaW5kZXgsIHVwZGF0ZWRDb250ZW50LCBmdW5jdGlvbihlcnIpIHtcbiAgICAgICAgaWYgKGVycikge1xuICAgICAgICAgIHJldHVybiBvcHRpb25zLmNvbXBsZXRlKGVycik7XG4gICAgICAgIH1cblxuICAgICAgICBwcm9jZXNzSW5kZXgoKTtcbiAgICAgIH0pO1xuICAgIH0pO1xuICB9XG4gIHByb2Nlc3NJbmRleCgpO1xufVxuIl19 PK ~\im]]diff/lib/patch/create.jsnu[/*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.structuredPatch = structuredPatch; exports.formatPatch = formatPatch; exports.createTwoFilesPatch = createTwoFilesPatch; exports.createPatch = createPatch; /*istanbul ignore end*/ var /*istanbul ignore start*/ _line = require("../diff/line") /*istanbul ignore end*/ ; /*istanbul ignore start*/ function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } /*istanbul ignore end*/ function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { if (!options) { options = {}; } if (typeof options.context === 'undefined') { options.context = 4; } var diff = /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _line /*istanbul ignore end*/ . /*istanbul ignore start*/ diffLines) /*istanbul ignore end*/ (oldStr, newStr, options); if (!diff) { return; } diff.push({ value: '', lines: [] }); // Append an empty value to make cleanup easier function contextLines(lines) { return lines.map(function (entry) { return ' ' + entry; }); } var hunks = []; var oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; /*istanbul ignore start*/ var _loop = function _loop( /*istanbul ignore end*/ i) { var current = diff[i], lines = current.lines || current.value.replace(/\n$/, '').split('\n'); current.lines = lines; if (current.added || current.removed) { /*istanbul ignore start*/ var _curRange; /*istanbul ignore end*/ // If we have previous context, start with that if (!oldRangeStart) { var prev = diff[i - 1]; oldRangeStart = oldLine; newRangeStart = newLine; if (prev) { curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : []; oldRangeStart -= curRange.length; newRangeStart -= curRange.length; } } // Output our changes /*istanbul ignore start*/ /*istanbul ignore end*/ /*istanbul ignore start*/ (_curRange = /*istanbul ignore end*/ curRange).push.apply( /*istanbul ignore start*/ _curRange /*istanbul ignore end*/ , /*istanbul ignore start*/ _toConsumableArray( /*istanbul ignore end*/ lines.map(function (entry) { return (current.added ? '+' : '-') + entry; }))); // Track the updated file position if (current.added) { newLine += lines.length; } else { oldLine += lines.length; } } else { // Identical context lines. Track line changes if (oldRangeStart) { // Close out any changes that have been output (or join overlapping) if (lines.length <= options.context * 2 && i < diff.length - 2) { /*istanbul ignore start*/ var _curRange2; /*istanbul ignore end*/ // Overlapping /*istanbul ignore start*/ /*istanbul ignore end*/ /*istanbul ignore start*/ (_curRange2 = /*istanbul ignore end*/ curRange).push.apply( /*istanbul ignore start*/ _curRange2 /*istanbul ignore end*/ , /*istanbul ignore start*/ _toConsumableArray( /*istanbul ignore end*/ contextLines(lines))); } else { /*istanbul ignore start*/ var _curRange3; /*istanbul ignore end*/ // end the range and output var contextSize = Math.min(lines.length, options.context); /*istanbul ignore start*/ /*istanbul ignore end*/ /*istanbul ignore start*/ (_curRange3 = /*istanbul ignore end*/ curRange).push.apply( /*istanbul ignore start*/ _curRange3 /*istanbul ignore end*/ , /*istanbul ignore start*/ _toConsumableArray( /*istanbul ignore end*/ contextLines(lines.slice(0, contextSize)))); var hunk = { oldStart: oldRangeStart, oldLines: oldLine - oldRangeStart + contextSize, newStart: newRangeStart, newLines: newLine - newRangeStart + contextSize, lines: curRange }; if (i >= diff.length - 2 && lines.length <= options.context) { // EOF is inside this hunk var oldEOFNewline = /\n$/.test(oldStr); var newEOFNewline = /\n$/.test(newStr); var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines; if (!oldEOFNewline && noNlBeforeAdds && oldStr.length > 0) { // special case: old has no eol and no trailing context; no-nl can end up before adds // however, if the old file is empty, do not output the no-nl line curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file'); } if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) { curRange.push('\\ No newline at end of file'); } } hunks.push(hunk); oldRangeStart = 0; newRangeStart = 0; curRange = []; } } oldLine += lines.length; newLine += lines.length; } }; for (var i = 0; i < diff.length; i++) { /*istanbul ignore start*/ _loop( /*istanbul ignore end*/ i); } return { oldFileName: oldFileName, newFileName: newFileName, oldHeader: oldHeader, newHeader: newHeader, hunks: hunks }; } function formatPatch(diff) { if (Array.isArray(diff)) { return diff.map(formatPatch).join('\n'); } var ret = []; if (diff.oldFileName == diff.newFileName) { ret.push('Index: ' + diff.oldFileName); } ret.push('==================================================================='); ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader)); ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader)); for (var i = 0; i < diff.hunks.length; i++) { var hunk = diff.hunks[i]; // Unified Diff Format quirk: If the chunk size is 0, // the first number is one lower than one would expect. // https://www.artima.com/weblogs/viewpost.jsp?thread=164293 if (hunk.oldLines === 0) { hunk.oldStart -= 1; } if (hunk.newLines === 0) { hunk.newStart -= 1; } ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@'); ret.push.apply(ret, hunk.lines); } return ret.join('\n') + '\n'; } function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { return formatPatch(structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options)); } function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wYXRjaC9jcmVhdGUuanMiXSwibmFtZXMiOlsic3RydWN0dXJlZFBhdGNoIiwib2xkRmlsZU5hbWUiLCJuZXdGaWxlTmFtZSIsIm9sZFN0ciIsIm5ld1N0ciIsIm9sZEhlYWRlciIsIm5ld0hlYWRlciIsIm9wdGlvbnMiLCJjb250ZXh0IiwiZGlmZiIsImRpZmZMaW5lcyIsInB1c2giLCJ2YWx1ZSIsImxpbmVzIiwiY29udGV4dExpbmVzIiwibWFwIiwiZW50cnkiLCJodW5rcyIsIm9sZFJhbmdlU3RhcnQiLCJuZXdSYW5nZVN0YXJ0IiwiY3VyUmFuZ2UiLCJvbGRMaW5lIiwibmV3TGluZSIsImkiLCJjdXJyZW50IiwicmVwbGFjZSIsInNwbGl0IiwiYWRkZWQiLCJyZW1vdmVkIiwicHJldiIsInNsaWNlIiwibGVuZ3RoIiwiY29udGV4dFNpemUiLCJNYXRoIiwibWluIiwiaHVuayIsIm9sZF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b25zKTtcbn1cbiJdfQ== PK ~\'diff/lib/convert/dmp.jsnu[/*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.convertChangesToDMP = convertChangesToDMP; /*istanbul ignore end*/ // See: http://code.google.com/p/google-diff-match-patch/wiki/API function convertChangesToDMP(changes) { var ret = [], change, operation; for (var i = 0; i < changes.length; i++) { change = changes[i]; if (change.added) { operation = 1; } else if (change.removed) { operation = -1; } else { operation = 0; } ret.push([operation, change.value]); } return ret; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9jb252ZXJ0L2RtcC5qcyJdLCJuYW1lcyI6WyJjb252ZXJ0Q2hhbmdlc1RvRE1QIiwiY2hhbmdlcyIsInJldCIsImNoYW5nZSIsIm9wZXJhdGlvbiIsImkiLCJsZW5ndGgiLCJhZGRlZCIsInJlbW92ZWQiLCJwdXNoIiwidmFsdWUiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7OztBQUFBO0FBQ08sU0FBU0EsbUJBQVQsQ0FBNkJDLE9BQTdCLEVBQXNDO0FBQzNDLE1BQUlDLEdBQUcsR0FBRyxFQUFWO0FBQUEsTUFDSUMsTUFESjtBQUFBLE1BRUlDLFNBRko7O0FBR0EsT0FBSyxJQUFJQyxDQUFDLEdBQUcsQ0FBYixFQUFnQkEsQ0FBQyxHQUFHSixPQUFPLENBQUNLLE1BQTVCLEVBQW9DRCxDQUFDLEVBQXJDLEVBQXlDO0FBQ3ZDRixJQUFBQSxNQUFNLEdBQUdGLE9BQU8sQ0FBQ0ksQ0FBRCxDQUFoQjs7QUFDQSxRQUFJRixNQUFNLENBQUNJLEtBQVgsRUFBa0I7QUFDaEJILE1BQUFBLFNBQVMsR0FBRyxDQUFaO0FBQ0QsS0FGRCxNQUVPLElBQUlELE1BQU0sQ0FBQ0ssT0FBWCxFQUFvQjtBQUN6QkosTUFBQUEsU0FBUyxHQUFHLENBQUMsQ0FBYjtBQUNELEtBRk0sTUFFQTtBQUNMQSxNQUFBQSxTQUFTLEdBQUcsQ0FBWjtBQUNEOztBQUVERixJQUFBQSxHQUFHLENBQUNPLElBQUosQ0FBUyxDQUFDTCxTQUFELEVBQVlELE1BQU0sQ0FBQ08sS0FBbkIsQ0FBVDtBQUNEOztBQUNELFNBQU9SLEdBQVA7QUFDRCIsInNvdXJjZXNDb250ZW50IjpbIi8vIFNlZTogaHR0cDovL2NvZGUuZ29vZ2xlLmNvbS9wL2dvb2dsZS1kaWZmLW1hdGNoLXBhdGNoL3dpa2kvQVBJXG5leHBvcnQgZnVuY3Rpb24gY29udmVydENoYW5nZXNUb0RNUChjaGFuZ2VzKSB7XG4gIGxldCByZXQgPSBbXSxcbiAgICAgIGNoYW5nZSxcbiAgICAgIG9wZXJhdGlvbjtcbiAgZm9yIChsZXQgaSA9IDA7IGkgPCBjaGFuZ2VzLmxlbmd0aDsgaSsrKSB7XG4gICAgY2hhbmdlID0gY2hhbmdlc1tpXTtcbiAgICBpZiAoY2hhbmdlLmFkZGVkKSB7XG4gICAgICBvcGVyYXRpb24gPSAxO1xuICAgIH0gZWxzZSBpZiAoY2hhbmdlLnJlbW92ZWQpIHtcbiAgICAgIG9wZXJhdGlvbiA9IC0xO1xuICAgIH0gZWxzZSB7XG4gICAgICBvcGVyYXRpb24gPSAwO1xuICAgIH1cblxuICAgIHJldC5wdXNoKFtvcGVyYXRpb24sIGNoYW5nZS52YWx1ZV0pO1xuICB9XG4gIHJldHVybiByZXQ7XG59XG4iXX0= PK ~\   diff/lib/convert/xml.jsnu[/*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.convertChangesToXML = convertChangesToXML; /*istanbul ignore end*/ function convertChangesToXML(changes) { var ret = []; for (var i = 0; i < changes.length; i++) { var change = changes[i]; if (change.added) { ret.push(''); } else if (change.removed) { ret.push(''); } ret.push(escapeHTML(change.value)); if (change.added) { ret.push(''); } else if (change.removed) { ret.push(''); } } return ret.join(''); } function escapeHTML(s) { var n = s; n = n.replace(/&/g, '&'); n = n.replace(//g, '>'); n = n.replace(/"/g, '"'); return n; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9jb252ZXJ0L3htbC5qcyJdLCJuYW1lcyI6WyJjb252ZXJ0Q2hhbmdlc1RvWE1MIiwiY2hhbmdlcyIsInJldCIsImkiLCJsZW5ndGgiLCJjaGFuZ2UiLCJhZGRlZCIsInB1c2giLCJyZW1vdmVkIiwiZXNjYXBlSFRNTCIsInZhbHVlIiwiam9pbiIsInMiLCJuIiwicmVwbGFjZSJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7O0FBQU8sU0FBU0EsbUJBQVQsQ0FBNkJDLE9BQTdCLEVBQXNDO0FBQzNDLE1BQUlDLEdBQUcsR0FBRyxFQUFWOztBQUNBLE9BQUssSUFBSUMsQ0FBQyxHQUFHLENBQWIsRUFBZ0JBLENBQUMsR0FBR0YsT0FBTyxDQUFDRyxNQUE1QixFQUFvQ0QsQ0FBQyxFQUFyQyxFQUF5QztBQUN2QyxRQUFJRSxNQUFNLEdBQUdKLE9BQU8sQ0FBQ0UsQ0FBRCxDQUFwQjs7QUFDQSxRQUFJRSxNQUFNLENBQUNDLEtBQVgsRUFBa0I7QUFDaEJKLE1BQUFBLEdBQUcsQ0FBQ0ssSUFBSixDQUFTLE9BQVQ7QUFDRCxLQUZELE1BRU8sSUFBSUYsTUFBTSxDQUFDRyxPQUFYLEVBQW9CO0FBQ3pCTixNQUFBQSxHQUFHLENBQUNLLElBQUosQ0FBUyxPQUFUO0FBQ0Q7O0FBRURMLElBQUFBLEdBQUcsQ0FBQ0ssSUFBSixDQUFTRSxVQUFVLENBQUNKLE1BQU0sQ0FBQ0ssS0FBUixDQUFuQjs7QUFFQSxRQUFJTCxNQUFNLENBQUNDLEtBQVgsRUFBa0I7QUFDaEJKLE1BQUFBLEdB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VxuXG4gICAgcmV0LnB1c2goZXNjYXBlSFRNTChjaGFuZ2UudmFsdWUpKTtcblxuICAgIGlmIChjaGFuZ2UuYWRkZWQpIHtcbiAgICAgIHJldC5wdXNoKCc8L2lucz4nKTtcbiAgICB9IGVsc2UgaWYgKGNoYW5nZS5yZW1vdmVkKSB7XG4gICAgICByZXQucHVzaCgnPC9kZWw+Jyk7XG4gICAgfVxuICB9XG4gIHJldHVybiByZXQuam9pbignJyk7XG59XG5cbmZ1bmN0aW9uIGVzY2FwZUhUTUwocykge1xuICBsZXQgbiA9IHM7XG4gIG4gPSBuLnJlcGxhY2UoLyYvZywgJyZhbXA7Jyk7XG4gIG4gPSBuLnJlcGxhY2UoLzwvZywgJyZsdDsnKTtcbiAgbiA9IG4ucmVwbGFjZSgvPi9nLCAnJmd0OycpO1xuICBuID0gbi5yZXBsYWNlKC9cIi9nLCAnJnF1b3Q7Jyk7XG5cbiAgcmV0dXJuIG47XG59XG4iXX0= PK ~\7;g"g"diff/lib/diff/word.jsnu[/*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.diffWords = diffWords; exports.diffWordsWithSpace = diffWordsWithSpace; exports.wordDiff = void 0; /*istanbul ignore end*/ var /*istanbul ignore start*/ _base = _interopRequireDefault(require("./base")) /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _params = require("../util/params") /*istanbul ignore end*/ ; /*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } /*istanbul ignore end*/ // Based on https://en.wikipedia.org/wiki/Latin_script_in_Unicode // // Ranges and exceptions: // Latin-1 Supplement, 0080–00FF // - U+00D7 × Multiplication sign // - U+00F7 ÷ Division sign // Latin Extended-A, 0100–017F // Latin Extended-B, 0180–024F // IPA Extensions, 0250–02AF // Spacing Modifier Letters, 02B0–02FF // - U+02C7 ˇ ˇ Caron // - U+02D8 ˘ ˘ Breve // - U+02D9 ˙ ˙ Dot Above // - U+02DA ˚ ˚ Ring Above // - U+02DB ˛ ˛ Ogonek // - U+02DC ˜ ˜ Small Tilde // - U+02DD ˝ ˝ Double Acute Accent // Latin Extended Additional, 1E00–1EFF var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/; var reWhitespace = /\S/; var wordDiff = new /*istanbul ignore start*/ _base /*istanbul ignore end*/ [ /*istanbul ignore start*/ "default" /*istanbul ignore end*/ ](); /*istanbul ignore start*/ exports.wordDiff = wordDiff; /*istanbul ignore end*/ wordDiff.equals = function (left, right) { if (this.options.ignoreCase) { left = left.toLowerCase(); right = right.toLowerCase(); } return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right); }; wordDiff.tokenize = function (value) { // All whitespace symbols except newline group into one token, each newline - in separate token var tokens = value.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set. for (var i = 0; i < tokens.length - 1; i++) { // If we have an empty string in the next field and we have only word chars before and after, merge if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) { tokens[i] += tokens[i + 2]; tokens.splice(i + 1, 2); i--; } } return tokens; }; function diffWords(oldStr, newStr, options) { options = /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _params /*istanbul ignore end*/ . /*istanbul ignore start*/ generateOptions) /*istanbul ignore end*/ (options, { ignoreWhitespace: true }); return wordDiff.diff(oldStr, newStr, options); } function diffWordsWithSpace(oldStr, newStr, options) { return wordDiff.diff(oldStr, newStr, options); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL3dvcmQuanMiXSwibmFtZXMiOlsiZXh0ZW5kZWRXb3JkQ2hhcnMiLCJyZVdoaXRlc3BhY2UiLCJ3b3JkRGlmZiIsIkRpZm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JkcyhvbGRTdHIsIG5ld1N0ciwgb3B0aW9ucykge1xuICBvcHRpb25zID0gZ2VuZXJhdGVPcHRpb25zKG9wdGlvbnMsIHtpZ25vcmVXaGl0ZXNwYWNlOiB0cnVlfSk7XG4gIHJldHVybiB3b3JkRGlmZi5kaWZmKG9sZFN0ciwgbmV3U3RyLCBvcHRpb25zKTtcbn1cblxuZXhwb3J0IGZ1bmN0aW9uIGRpZmZXb3Jkc1dpdGhTcGFjZShvbGRTdHIsIG5ld1N0ciwgb3B0aW9ucykge1xuICByZXR1cm4gd29yZERpZmYuZGlmZihvbGRTdHIsIG5ld1N0ciwgb3B0aW9ucyk7XG59XG4iXX0= PK ~\MNNdiff/lib/diff/base.jsnu[/*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = Diff; /*istanbul ignore end*/ function Diff() {} Diff.prototype = { /*istanbul ignore start*/ /*istanbul ignore end*/ diff: function diff(oldString, newString) { /*istanbul ignore start*/ var _options$timeout; var /*istanbul ignore end*/ options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var callback = options.callback; if (typeof options === 'function') { callback = options; options = {}; } this.options = options; var self = this; function done(value) { if (callback) { setTimeout(function () { callback(undefined, value); }, 0); return true; } else { return value; } } // Allow subclasses to massage the input prior to running oldString = this.castInput(oldString); newString = this.castInput(newString); oldString = this.removeEmpty(this.tokenize(oldString)); newString = this.removeEmpty(this.tokenize(newString)); var newLen = newString.length, oldLen = oldString.length; var editLength = 1; var maxEditLength = newLen + oldLen; if (options.maxEditLength) { maxEditLength = Math.min(maxEditLength, options.maxEditLength); } var maxExecutionTime = /*istanbul ignore start*/ (_options$timeout = /*istanbul ignore end*/ options.timeout) !== null && _options$timeout !== void 0 ? _options$timeout : Infinity; var abortAfterTimestamp = Date.now() + maxExecutionTime; var bestPath = [{ oldPos: -1, lastComponent: undefined }]; // Seed editLength = 0, i.e. the content starts with the same values var newPos = this.extractCommon(bestPath[0], newString, oldString, 0); if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) { // Identity per the equality and tokenizer return done([{ value: this.join(newString), count: newString.length }]); } // Once we hit the right edge of the edit graph on some diagonal k, we can // definitely reach the end of the edit graph in no more than k edits, so // there's no point in considering any moves to diagonal k+1 any more (from // which we're guaranteed to need at least k+1 more edits). // Similarly, once we've reached the bottom of the edit graph, there's no // point considering moves to lower diagonals. // We record this fact by setting minDiagonalToConsider and // maxDiagonalToConsider to some finite value once we've hit the edge of // the edit graph. // This optimization is not faithful to the original algorithm presented in // Myers's paper, which instead pointlessly extends D-paths off the end of // the edit graph - see page 7 of Myers's paper which notes this point // explicitly and illustrates it with a diagram. This has major performance // implications for some common scenarios. For instance, to compute a diff // where the new text simply appends d characters on the end of the // original text of length n, the true Myers algorithm will take O(n+d^2) // time while this optimization needs only O(n+d) time. var minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity; // Main worker method. checks all permutations of a given edit length for acceptance. function execEditLength() { for (var diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) { var basePath = /*istanbul ignore start*/ void 0 /*istanbul ignore end*/ ; var removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1]; if (removePath) { // No one else is going to attempt to use this value, clear it bestPath[diagonalPath - 1] = undefined; } var canAdd = false; if (addPath) { // what newPos will be after we do an insertion: var addPathNewPos = addPath.oldPos - diagonalPath; canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen; } var canRemove = removePath && removePath.oldPos + 1 < oldLen; if (!canAdd && !canRemove) { // If this path is a terminal then prune bestPath[diagonalPath] = undefined; continue; } // Select the diagonal that we want to branch from. We select the prior // path whose position in the old string is the farthest from the origin // and does not pass the bounds of the diff graph // TODO: Remove the `+ 1` here to make behavior match Myers algorithm // and prefer to order removals before insertions. if (!canRemove || canAdd && removePath.oldPos + 1 < addPath.oldPos) { basePath = self.addToPath(addPath, true, undefined, 0); } else { basePath = self.addToPath(removePath, undefined, true, 1); } newPos = self.extractCommon(basePath, newString, oldString, diagonalPath); if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) { // If we have hit the end of both strings, then we are done return done(buildValues(self, basePath.lastComponent, newString, oldString, self.useLongestToken)); } else { bestPath[diagonalPath] = basePath; if (basePath.oldPos + 1 >= oldLen) { maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1); } if (newPos + 1 >= newLen) { minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1); } } } editLength++; } // Performs the length of edit iteration. Is a bit fugly as this has to support the // sync and async mode which is never fun. Loops over execEditLength until a value // is produced, or until the edit length exceeds options.maxEditLength (if given), // in which case it will return undefined. if (callback) { (function exec() { setTimeout(function () { if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) { return callback(); } if (!execEditLength()) { exec(); } }, 0); })(); } else { while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) { var ret = execEditLength(); if (ret) { return ret; } } } }, /*istanbul ignore start*/ /*istanbul ignore end*/ addToPath: function addToPath(path, added, removed, oldPosInc) { var last = path.lastComponent; if (last && last.added === added && last.removed === removed) { return { oldPos: path.oldPos + oldPosInc, lastComponent: { count: last.count + 1, added: added, removed: removed, previousComponent: last.previousComponent } }; } else { return { oldPos: path.oldPos + oldPosInc, lastComponent: { count: 1, added: added, removed: removed, previousComponent: last } }; } }, /*istanbul ignore start*/ /*istanbul ignore end*/ extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) { var newLen = newString.length, oldLen = oldString.length, oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0; while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { newPos++; oldPos++; commonCount++; } if (commonCount) { basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent }; } basePath.oldPos = oldPos; return newPos; }, /*istanbul ignore start*/ /*istanbul ignore end*/ equals: function equals(left, right) { if (this.options.comparator) { return this.options.comparator(left, right); } else { return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase(); } }, /*istanbul ignore start*/ /*istanbul ignore end*/ removeEmpty: function removeEmpty(array) { var ret = []; for (var i = 0; i < array.length; i++) { if (array[i]) { ret.push(array[i]); } } return ret; }, /*istanbul ignore start*/ /*istanbul ignore end*/ castInput: function castInput(value) { return value; }, /*istanbul ignore start*/ /*istanbul ignore end*/ tokenize: function tokenize(value) { return value.split(''); }, /*istanbul ignore start*/ /*istanbul ignore end*/ join: function join(chars) { return chars.join(''); } }; function buildValues(diff, lastComponent, newString, oldString, useLongestToken) { // First we convert our linked list of components in reverse order to an // array in the right order: var components = []; var nextComponent; while (lastComponent) { components.push(lastComponent); nextComponent = lastComponent.previousComponent; delete lastComponent.previousComponent; lastComponent = nextComponent; } components.reverse(); var componentPos = 0, componentLen = components.length, newPos = 0, oldPos = 0; for (; componentPos < componentLen; componentPos++) { var component = components[componentPos]; if (!component.removed) { if (!component.added && useLongestToken) { var value = newString.slice(newPos, newPos + component.count); value = value.map(function (value, i) { var oldValue = oldString[oldPos + i]; return oldValue.length > value.length ? oldValue : value; }); component.value = diff.join(value); } else { component.value = diff.join(newString.slice(newPos, newPos + component.count)); } newPos += component.count; // Common case if (!component.added) { oldPos += component.count; } } else { component.value = diff.join(oldString.slice(oldPos, oldPos + component.count)); oldPos += component.count; // Reverse add and remove so removes are output first to match common convention // The diffing algorithm is tied to add then remove output and this is the simplest // route to get the desired output with minimal overhead. if (componentPos && components[componentPos - 1].added) { var tmp = components[componentPos - 1]; components[componentPos - 1] = components[componentPos]; components[componentPos] = tmp; } } } // Special case handle for when one terminal is ignored (i.e. whitespace). // For this case we merge the terminal into the prior string and drop the change. // This is only available for string mode. var finalComponent = components[componentLen - 1]; if (componentLen > 1 && typeof finalComponent.value === 'string' && (finalComponent.added || finalComponent.removed) && diff.equals('', finalComponent.value)) { components[componentLen - 2].value += finalComponent.value; components.pop(); } return components; } //# sourceMappingURL=data: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cG9uZW50LnJlbW92ZWQpXG4gICAgICAmJiBkaWZmLmVxdWFscygnJywgZmluYWxDb21wb25lbnQudmFsdWUpKSB7XG4gICAgY29tcG9uZW50c1tjb21wb25lbnRMZW4gLSAyXS52YWx1ZSArPSBmaW5hbENvbXBvbmVudC52YWx1ZTtcbiAgICBjb21wb25lbnRzLnBvcCgpO1xuICB9XG5cbiAgcmV0dXJuIGNvbXBvbmVudHM7XG59XG4iXX0= PK ~\0|diff/lib/diff/array.jsnu[/*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.diffArrays = diffArrays; exports.arrayDiff = void 0; /*istanbul ignore end*/ var /*istanbul ignore start*/ _base = _interopRequireDefault(require("./base")) /*istanbul ignore end*/ ; /*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } /*istanbul ignore end*/ var arrayDiff = new /*istanbul ignore start*/ _base /*istanbul ignore end*/ [ /*istanbul ignore start*/ "default" /*istanbul ignore end*/ ](); /*istanbul ignore start*/ exports.arrayDiff = arrayDiff; /*istanbul ignore end*/ arrayDiff.tokenize = function (value) { return value.slice(); }; arrayDiff.join = arrayDiff.removeEmpty = function (value) { return value; }; function diffArrays(oldArr, newArr, callback) { return arrayDiff.diff(oldArr, newArr, callback); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2FycmF5LmpzIl0sIm5hbWVzIjpbImFycmF5RGlmZiIsIkRpZmYiLCJ0b2tlbml6ZSIsInZhbHVlIiwic2xpY2UiLCJqb2luIiwicmVtb3ZlRW1wdHkiLCJkaWZmQXJyYXlzIiwib2xkQXJyIiwibmV3QXJyIiwiY2FsbGJhY2siLCJkaWZmIl0sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7O0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTs7Ozs7QUFFTyxJQUFNQSxTQUFTLEdBQUc7QUFBSUM7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUEsQ0FBSixFQUFsQjs7Ozs7O0FBQ1BELFNBQVMsQ0FBQ0UsUUFBVixHQUFxQixVQUFTQyxLQUFULEVBQWdCO0FBQ25DLFNBQU9BLEtBQUssQ0FBQ0MsS0FBTixFQUFQO0FBQ0QsQ0FGRDs7QUFHQUosU0FBUyxDQUFDSyxJQUFWLEdBQWlCTCxTQUFTLENBQUNNLFdBQVYsR0FBd0IsVUFBU0gsS0FBVCxFQUFnQjtBQUN2RCxTQUFPQSxLQUFQO0FBQ0QsQ0FGRDs7QUFJTyxTQUFTSSxVQUFULENBQW9CQyxNQUFwQixFQUE0QkMsTUFBNUIsRUFBb0NDLFFBQXBDLEVBQThDO0FBQUUsU0FBT1YsU0FBUyxDQUFDVyxJQUFWLENBQWVILE1BQWYsRUFBdUJDLE1BQXZCLEVBQStCQyxRQUEvQixDQUFQO0FBQWtEIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IERpZmYgZnJvbSAnLi9iYXNlJztcblxuZXhwb3J0IGNvbnN0IGFycmF5RGlmZiA9IG5ldyBEaWZmKCk7XG5hcnJheURpZmYudG9rZW5pemUgPSBmdW5jdGlvbih2YWx1ZSkge1xuICByZXR1cm4gdmFsdWUuc2xpY2UoKTtcbn07XG5hcnJheURpZmYuam9pbiA9IGFycmF5RGlmZi5yZW1vdmVFbXB0eSA9IGZ1bmN0aW9uKHZhbHVlKSB7XG4gIHJldHVybiB2YWx1ZTtcbn07XG5cbmV4cG9ydCBmdW5jdGlvbiBkaWZmQXJyYXlzKG9sZEFyciwgbmV3QXJyLCBjYWxsYmFjaykgeyByZXR1cm4gYXJyYXlEaWZmLmRpZmYob2xkQXJyLCBuZXdBcnIsIGNhbGxiYWNrKTsgfVxuIl19 PK ~\v7diff/lib/diff/line.jsnu[/*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.diffLines = diffLines; exports.diffTrimmedLines = diffTrimmedLines; exports.lineDiff = void 0; /*istanbul ignore end*/ var /*istanbul ignore start*/ _base = _interopRequireDefault(require("./base")) /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _params = require("../util/params") /*istanbul ignore end*/ ; /*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } /*istanbul ignore end*/ var lineDiff = new /*istanbul ignore start*/ _base /*istanbul ignore end*/ [ /*istanbul ignore start*/ "default" /*istanbul ignore end*/ ](); /*istanbul ignore start*/ exports.lineDiff = lineDiff; /*istanbul ignore end*/ lineDiff.tokenize = function (value) { if (this.options.stripTrailingCr) { // remove one \r before \n to match GNU diff's --strip-trailing-cr behavior value = value.replace(/\r\n/g, '\n'); } var retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line if (!linesAndNewlines[linesAndNewlines.length - 1]) { linesAndNewlines.pop(); } // Merge the content and line separators into single tokens for (var i = 0; i < linesAndNewlines.length; i++) { var line = linesAndNewlines[i]; if (i % 2 && !this.options.newlineIsToken) { retLines[retLines.length - 1] += line; } else { if (this.options.ignoreWhitespace) { line = line.trim(); } retLines.push(line); } } return retLines; }; function diffLines(oldStr, newStr, callback) { return lineDiff.diff(oldStr, newStr, callback); } function diffTrimmedLines(oldStr, newStr, callback) { var options = /*istanbul ignore start*/ (0, /*istanbul ignore end*/ /*istanbul ignore start*/ _params /*istanbul ignore end*/ . /*istanbul ignore start*/ generateOptions) /*istanbul ignore end*/ (callback, { ignoreWhitespace: true }); return lineDiff.diff(oldStr, newStr, options); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2xpbmUuanMiXSwibmFtZXMiOlsibGluZURpZmYiLCJEaWZmIiwidG9rZW5pemUiLCJ2YWx1ZSIsIm9wdGlvbnMiLCJzdHJpcFRyYWlsaW5nQ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BbmROZXdsaW5lc1tpXTtcblxuICAgIGlmIChpICUgMiAmJiAhdGhpcy5vcHRpb25zLm5ld2xpbmVJc1Rva2VuKSB7XG4gICAgICByZXRMaW5lc1tyZXRMaW5lcy5sZW5ndGggLSAxXSArPSBsaW5lO1xuICAgIH0gZWxzZSB7XG4gICAgICBpZiAodGhpcy5vcHRpb25zLmlnbm9yZVdoaXRlc3BhY2UpIHtcbiAgICAgICAgbGluZSA9IGxpbmUudHJpbSgpO1xuICAgICAgfVxuICAgICAgcmV0TGluZXMucHVzaChsaW5lKTtcbiAgICB9XG4gIH1cblxuICByZXR1cm4gcmV0TGluZXM7XG59O1xuXG5leHBvcnQgZnVuY3Rpb24gZGlmZkxpbmVzKG9sZFN0ciwgbmV3U3RyLCBjYWxsYmFjaykgeyByZXR1cm4gbGluZURpZmYuZGlmZihvbGRTdHIsIG5ld1N0ciwgY2FsbGJhY2spOyB9XG5leHBvcnQgZnVuY3Rpb24gZGlmZlRyaW1tZWRMaW5lcyhvbGRTdHIsIG5ld1N0ciwgY2FsbGJhY2spIHtcbiAgbGV0IG9wdGlvbnMgPSBnZW5lcmF0ZU9wdGlvbnMoY2FsbGJhY2ssIHtpZ25vcmVXaGl0ZXNwYWNlOiB0cnVlfSk7XG4gIHJldHVybiBsaW5lRGlmZi5kaWZmKG9sZFN0ciwgbmV3U3RyLCBvcHRpb25zKTtcbn1cbiJdfQ== PK ~\Y 5diff/lib/diff/character.jsnu[/*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.diffChars = diffChars; exports.characterDiff = void 0; /*istanbul ignore end*/ var /*istanbul ignore start*/ _base = _interopRequireDefault(require("./base")) /*istanbul ignore end*/ ; /*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } /*istanbul ignore end*/ var characterDiff = new /*istanbul ignore start*/ _base /*istanbul ignore end*/ [ /*istanbul ignore start*/ "default" /*istanbul ignore end*/ ](); /*istanbul ignore start*/ exports.characterDiff = characterDiff; /*istanbul ignore end*/ function diffChars(oldStr, newStr, options) { return characterDiff.diff(oldStr, newStr, options); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2NoYXJhY3Rlci5qcyJdLCJuYW1lcyI6WyJjaGFyYWN0ZXJEaWZmIiwiRGlmZiIsImRpZmZDaGFycyIsIm9sZFN0ciIsIm5ld1N0ciIsIm9wdGlvbnMiLCJkaWZmIl0sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7O0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTs7Ozs7QUFFTyxJQUFNQSxhQUFhLEdBQUc7QUFBSUM7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUEsQ0FBSixFQUF0Qjs7Ozs7O0FBQ0EsU0FBU0MsU0FBVCxDQUFtQkMsTUFBbkIsRUFBMkJDLE1BQTNCLEVBQW1DQyxPQUFuQyxFQUE0QztBQUFFLFNBQU9MLGFBQWEsQ0FBQ00sSUFBZCxDQUFtQkgsTUFBbkIsRUFBMkJDLE1BQTNCLEVBQW1DQyxPQUFuQyxDQUFQO0FBQXFEIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IERpZmYgZnJvbSAnLi9iYXNlJztcblxuZXhwb3J0IGNvbnN0IGNoYXJhY3RlckRpZmYgPSBuZXcgRGlmZigpO1xuZXhwb3J0IGZ1bmN0aW9uIGRpZmZDaGFycyhvbGRTdHIsIG5ld1N0ciwgb3B0aW9ucykgeyByZXR1cm4gY2hhcmFjdGVyRGlmZi5kaWZmKG9sZFN0ciwgbmV3U3RyLCBvcHRpb25zKTsgfVxuIl19 PK ~\?#diff/lib/diff/css.jsnu[/*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.diffCss = diffCss; exports.cssDiff = void 0; /*istanbul ignore end*/ var /*istanbul ignore start*/ _base = _interopRequireDefault(require("./base")) /*istanbul ignore end*/ ; /*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } /*istanbul ignore end*/ var cssDiff = new /*istanbul ignore start*/ _base /*istanbul ignore end*/ [ /*istanbul ignore start*/ "default" /*istanbul ignore end*/ ](); /*istanbul ignore start*/ exports.cssDiff = cssDiff; /*istanbul ignore end*/ cssDiff.tokenize = function (value) { return value.split(/([{}:;,]|\s+)/); }; function diffCss(oldStr, newStr, callback) { return cssDiff.diff(oldStr, newStr, callback); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2Nzcy5qcyJdLCJuYW1lcyI6WyJjc3NEaWZmIiwiRGlmZiIsInRva2VuaXplIiwidmFsdWUiLCJzcGxpdCIsImRpZmZDc3MiLCJvbGRTdHIiLCJuZXdTdHIiLCJjYWxsYmFjayIsImRpZmYiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBOzs7OztBQUVPLElBQU1BLE9BQU8sR0FBRztBQUFJQztBQUFBQTtBQUFBQTtBQUFBQTtBQUFBQTtBQUFBQTtBQUFBQTtBQUFBQSxDQUFKLEVBQWhCOzs7Ozs7QUFDUEQsT0FBTyxDQUFDRSxRQUFSLEdBQW1CLFVBQVNDLEtBQVQsRUFBZ0I7QUFDakMsU0FBT0EsS0FBSyxDQUFDQyxLQUFOLENBQVksZUFBWixDQUFQO0FBQ0QsQ0FGRDs7QUFJTyxTQUFTQyxPQUFULENBQWlCQyxNQUFqQixFQUF5QkMsTUFBekIsRUFBaUNDLFFBQWpDLEVBQTJDO0FBQUUsU0FBT1IsT0FBTyxDQUFDUyxJQUFSLENBQWFILE1BQWIsRUFBcUJDLE1BQXJCLEVBQTZCQyxRQUE3QixDQUFQO0FBQWdEIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IERpZmYgZnJvbSAnLi9iYXNlJztcblxuZXhwb3J0IGNvbnN0IGNzc0RpZmYgPSBuZXcgRGlmZigpO1xuY3NzRGlmZi50b2tlbml6ZSA9IGZ1bmN0aW9uKHZhbHVlKSB7XG4gIHJldHVybiB2YWx1ZS5zcGxpdCgvKFt7fTo7LF18XFxzKykvKTtcbn07XG5cbmV4cG9ydCBmdW5jdGlvbiBkaWZmQ3NzKG9sZFN0ciwgbmV3U3RyLCBjYWxsYmFjaykgeyByZXR1cm4gY3NzRGlmZi5kaWZmKG9sZFN0ciwgbmV3U3RyLCBjYWxsYmFjayk7IH1cbiJdfQ== PK ~\P[**diff/lib/diff/sentence.jsnu[/*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.diffSentences = diffSentences; exports.sentenceDiff = void 0; /*istanbul ignore end*/ var /*istanbul ignore start*/ _base = _interopRequireDefault(require("./base")) /*istanbul ignore end*/ ; /*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } /*istanbul ignore end*/ var sentenceDiff = new /*istanbul ignore start*/ _base /*istanbul ignore end*/ [ /*istanbul ignore start*/ "default" /*istanbul ignore end*/ ](); /*istanbul ignore start*/ exports.sentenceDiff = sentenceDiff; /*istanbul ignore end*/ sentenceDiff.tokenize = function (value) { return value.split(/(\S.+?[.!?])(?=\s+|$)/); }; function diffSentences(oldStr, newStr, callback) { return sentenceDiff.diff(oldStr, newStr, callback); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL3NlbnRlbmNlLmpzIl0sIm5hbWVzIjpbInNlbnRlbmNlRGlmZiIsIkRpZmYiLCJ0b2tlbml6ZSIsInZhbHVlIiwic3BsaXQiLCJkaWZmU2VudGVuY2VzIiwib2xkU3RyIiwibmV3U3RyIiwiY2FsbGJhY2siLCJkaWZmIl0sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7O0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTs7Ozs7QUFHTyxJQUFNQSxZQUFZLEdBQUc7QUFBSUM7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUEsQ0FBSixFQUFyQjs7Ozs7O0FBQ1BELFlBQVksQ0FBQ0UsUUFBYixHQUF3QixVQUFTQyxLQUFULEVBQWdCO0FBQ3RDLFNBQU9BLEtBQUssQ0FBQ0MsS0FBTixDQUFZLHVCQUFaLENBQVA7QUFDRCxDQUZEOztBQUlPLFNBQVNDLGFBQVQsQ0FBdUJDLE1BQXZCLEVBQStCQyxNQUEvQixFQUF1Q0MsUUFBdkMsRUFBaUQ7QUFBRSxTQUFPUixZQUFZLENBQUNTLElBQWIsQ0FBa0JILE1BQWxCLEVBQTBCQyxNQUExQixFQUFrQ0MsUUFBbEMsQ0FBUDtBQUFxRCIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBEaWZmIGZyb20gJy4vYmFzZSc7XG5cblxuZXhwb3J0IGNvbnN0IHNlbnRlbmNlRGlmZiA9IG5ldyBEaWZmKCk7XG5zZW50ZW5jZURpZmYudG9rZW5pemUgPSBmdW5jdGlvbih2YWx1ZSkge1xuICByZXR1cm4gdmFsdWUuc3BsaXQoLyhcXFMuKz9bLiE/XSkoPz1cXHMrfCQpLyk7XG59O1xuXG5leHBvcnQgZnVuY3Rpb24gZGlmZlNlbnRlbmNlcyhvbGRTdHIsIG5ld1N0ciwgY2FsbGJhY2spIHsgcmV0dXJuIHNlbnRlbmNlRGlmZi5kaWZmKG9sZFN0ciwgbmV3U3RyLCBjYWxsYmFjayk7IH1cbiJdfQ== PK ~\p&22diff/lib/diff/json.jsnu[/*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.diffJson = diffJson; exports.canonicalize = canonicalize; exports.jsonDiff = void 0; /*istanbul ignore end*/ var /*istanbul ignore start*/ _base = _interopRequireDefault(require("./base")) /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _line = require("./line") /*istanbul ignore end*/ ; /*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } /*istanbul ignore end*/ var objectPrototypeToString = Object.prototype.toString; var jsonDiff = new /*istanbul ignore start*/ _base /*istanbul ignore end*/ [ /*istanbul ignore start*/ "default" /*istanbul ignore end*/ ](); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: /*istanbul ignore start*/ exports.jsonDiff = jsonDiff; /*istanbul ignore end*/ jsonDiff.useLongestToken = true; jsonDiff.tokenize = /*istanbul ignore start*/ _line /*istanbul ignore end*/ . /*istanbul ignore start*/ lineDiff /*istanbul ignore end*/ .tokenize; jsonDiff.castInput = function (value) { /*istanbul ignore start*/ var _this$options = /*istanbul ignore end*/ this.options, undefinedReplacement = _this$options.undefinedReplacement, _this$options$stringi = _this$options.stringifyReplacer, stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) /*istanbul ignore start*/ { return ( /*istanbul ignore end*/ typeof v === 'undefined' ? undefinedReplacement : v ); } : _this$options$stringi; return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' '); }; jsonDiff.equals = function (left, right) { return ( /*istanbul ignore start*/ _base /*istanbul ignore end*/ [ /*istanbul ignore start*/ "default" /*istanbul ignore end*/ ].prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1')) ); }; function diffJson(oldObj, newObj, options) { return jsonDiff.diff(oldObj, newObj, options); } // This function handles the presence of circular references by bailing out when encountering an // object that is already on the "stack" of items being processed. Accepts an optional replacer function canonicalize(obj, stack, replacementStack, replacer, key) { stack = stack || []; replacementStack = replacementStack || []; if (replacer) { obj = replacer(key, obj); } var i; for (i = 0; i < stack.length; i += 1) { if (stack[i] === obj) { return replacementStack[i]; } } var canonicalizedObj; if ('[object Array]' === objectPrototypeToString.call(obj)) { stack.push(obj); canonicalizedObj = new Array(obj.length); replacementStack.push(canonicalizedObj); for (i = 0; i < obj.length; i += 1) { canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key); } stack.pop(); replacementStack.pop(); return canonicalizedObj; } if (obj && obj.toJSON) { obj = obj.toJSON(); } if ( /*istanbul ignore start*/ _typeof( /*istanbul ignore end*/ obj) === 'object' && obj !== null) { stack.push(obj); canonicalizedObj = {}; replacementStack.push(canonicalizedObj); var sortedKeys = [], _key; for (_key in obj) { /* istanbul ignore else */ if (obj.hasOwnProperty(_key)) { sortedKeys.push(_key); } } sortedKeys.sort(); for (i = 0; i < sortedKeys.length; i += 1) { _key = sortedKeys[i]; canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key); } stack.pop(); replacementStack.pop(); } else { canonicalizedObj = obj; } return canonicalizedObj; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2pzb24uanMiXSwibmFtZXMiOlsib2JqZWN0UHJvdG90eXBlVG9TdHJpbmciLCJPYmplY3QiLCJwcm90b3R5cGUiLCJ0b1N0cmluZyIsImpzb25EaWZmIiwiRGlmZiIsInVzZUxvbmdlc3RUb2tlbiIsInRva2VuaXplIiwibGluZURpZmYiLCJjYXN0SW5wdXQiLCJ2YWx1ZSIsIm9wdGlvbnMiLCJ1bmRlZmluZWRSZXBsYWNlbWVudCIsInN0cmluZ2lmeVJlcGxhY2VyIiwiayIsInYiLCJKU09OIiwic3RyaW5naWZ5Iiw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IFtdLFxuICAgICAgICBrZXk7XG4gICAgZm9yIChrZXkgaW4gb2JqKSB7XG4gICAgICAvKiBpc3RhbmJ1bCBpZ25vcmUgZWxzZSAqL1xuICAgICAgaWYgKG9iai5oYXNPd25Qcm9wZXJ0eShrZXkpKSB7XG4gICAgICAgIHNvcnRlZEtleXMucHVzaChrZXkpO1xuICAgICAgfVxuICAgIH1cbiAgICBzb3J0ZWRLZXlzLnNvcnQoKTtcbiAgICBmb3IgKGkgPSAwOyBpIDwgc29ydGVkS2V5cy5sZW5ndGg7IGkgKz0gMSkge1xuICAgICAga2V5ID0gc29ydGVkS2V5c1tpXTtcbiAgICAgIGNhbm9uaWNhbGl6ZWRPYmpba2V5XSA9IGNhbm9uaWNhbGl6ZShvYmpba2V5XSwgc3RhY2ssIHJlcGxhY2VtZW50U3RhY2ssIHJlcGxhY2VyLCBrZXkpO1xuICAgIH1cbiAgICBzdGFjay5wb3AoKTtcbiAgICByZXBsYWNlbWVudFN0YWNrLnBvcCgpO1xuICB9IGVsc2Uge1xuICAgIGNhbm9uaWNhbGl6ZWRPYmogPSBvYmo7XG4gIH1cbiAgcmV0dXJuIGNhbm9uaWNhbGl6ZWRPYmo7XG59XG4iXX0= PK ~\!RRdiff/lib/index.jsnu[/*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "Diff", { enumerable: true, get: function get() { return _base["default"]; } }); Object.defineProperty(exports, "diffChars", { enumerable: true, get: function get() { return _character.diffChars; } }); Object.defineProperty(exports, "diffWords", { enumerable: true, get: function get() { return _word.diffWords; } }); Object.defineProperty(exports, "diffWordsWithSpace", { enumerable: true, get: function get() { return _word.diffWordsWithSpace; } }); Object.defineProperty(exports, "diffLines", { enumerable: true, get: function get() { return _line.diffLines; } }); Object.defineProperty(exports, "diffTrimmedLines", { enumerable: true, get: function get() { return _line.diffTrimmedLines; } }); Object.defineProperty(exports, "diffSentences", { enumerable: true, get: function get() { return _sentence.diffSentences; } }); Object.defineProperty(exports, "diffCss", { enumerable: true, get: function get() { return _css.diffCss; } }); Object.defineProperty(exports, "diffJson", { enumerable: true, get: function get() { return _json.diffJson; } }); Object.defineProperty(exports, "canonicalize", { enumerable: true, get: function get() { return _json.canonicalize; } }); Object.defineProperty(exports, "diffArrays", { enumerable: true, get: function get() { return _array.diffArrays; } }); Object.defineProperty(exports, "applyPatch", { enumerable: true, get: function get() { return _apply.applyPatch; } }); Object.defineProperty(exports, "applyPatches", { enumerable: true, get: function get() { return _apply.applyPatches; } }); Object.defineProperty(exports, "parsePatch", { enumerable: true, get: function get() { return _parse.parsePatch; } }); Object.defineProperty(exports, "merge", { enumerable: true, get: function get() { return _merge.merge; } }); Object.defineProperty(exports, "reversePatch", { enumerable: true, get: function get() { return _reverse.reversePatch; } }); Object.defineProperty(exports, "structuredPatch", { enumerable: true, get: function get() { return _create.structuredPatch; } }); Object.defineProperty(exports, "createTwoFilesPatch", { enumerable: true, get: function get() { return _create.createTwoFilesPatch; } }); Object.defineProperty(exports, "createPatch", { enumerable: true, get: function get() { return _create.createPatch; } }); Object.defineProperty(exports, "formatPatch", { enumerable: true, get: function get() { return _create.formatPatch; } }); Object.defineProperty(exports, "convertChangesToDMP", { enumerable: true, get: function get() { return _dmp.convertChangesToDMP; } }); Object.defineProperty(exports, "convertChangesToXML", { enumerable: true, get: function get() { return _xml.convertChangesToXML; } }); /*istanbul ignore end*/ var /*istanbul ignore start*/ _base = _interopRequireDefault(require("./diff/base")) /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _character = require("./diff/character") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _word = require("./diff/word") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _line = require("./diff/line") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _sentence = require("./diff/sentence") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _css = require("./diff/css") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _json = require("./diff/json") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _array = require("./diff/array") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _apply = require("./patch/apply") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _parse = require("./patch/parse") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _merge = require("./patch/merge") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _reverse = require("./patch/reverse") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _create = require("./patch/create") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _dmp = require("./convert/dmp") /*istanbul ignore end*/ ; var /*istanbul ignore start*/ _xml = require("./convert/xml") /*istanbul ignore end*/ ; /*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } /*istanbul ignore end*/ //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uL3NyYy9pbmRleC5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7OztBQWdCQTtBQUFBO0FBQUE7QUFBQTtBQUFBOztBQUNBO0FBQUE7QUFBQTtBQUFBO0FBQUE7O0FBQ0E7QUFBQTtBQUFBO0FBQUE7QUFBQTs7QUFDQTtBQUFBO0FBQUE7QUFBQTtBQUFBOztBQUNBO0FBQUE7QUFBQTtBQUFBO0FBQUE7O0FBRUE7QUFBQTtBQUFBO0FBQUE7QUFBQTs7QUFDQTtBQUFBO0FBQUE7QUFBQTtBQUFBOztBQUVBO0FBQUE7QUFBQTtBQUFBO0FBQUE7O0FBRU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RpZmZMaW5lcyxcbiAgZGlmZlRyaW1tZWRMaW5lcyxcbiAgZGlmZlNlbnRlbmNlcyxcblxuICBkaWZmQ3NzLFxuICBkaWZmSnNvbixcblxuICBkaWZmQXJyYXlzLFxuXG4gIHN0cnVjdHVyZWRQYXRjaCxcbiAgY3JlYXRlVHdvRmlsZXNQYXRjaCxcbiAgY3JlYXRlUGF0Y2gsXG4gIGZvcm1hdFBhdGNoLFxuICBhcHBseVBhdGNoLFxuICBhcHBseVBhdGNoZXMsXG4gIHBhcnNlUGF0Y2gsXG4gIG1lcmdlLFxuICByZXZlcnNlUGF0Y2gsXG4gIGNvbnZlcnRDaGFuZ2VzVG9ETVAsXG4gIGNvbnZlcnRDaGFuZ2VzVG9YTUwsXG4gIGNhbm9uaWNhbGl6ZVxufTtcbiJdfQ== PK ~\> QQdiff/lib/index.es6.jsnu[function Diff() {} Diff.prototype = { diff: function diff(oldString, newString) { var _options$timeout; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var callback = options.callback; if (typeof options === 'function') { callback = options; options = {}; } this.options = options; var self = this; function done(value) { if (callback) { setTimeout(function () { callback(undefined, value); }, 0); return true; } else { return value; } } // Allow subclasses to massage the input prior to running oldString = this.castInput(oldString); newString = this.castInput(newString); oldString = this.removeEmpty(this.tokenize(oldString)); newString = this.removeEmpty(this.tokenize(newString)); var newLen = newString.length, oldLen = oldString.length; var editLength = 1; var maxEditLength = newLen + oldLen; if (options.maxEditLength) { maxEditLength = Math.min(maxEditLength, options.maxEditLength); } var maxExecutionTime = (_options$timeout = options.timeout) !== null && _options$timeout !== void 0 ? _options$timeout : Infinity; var abortAfterTimestamp = Date.now() + maxExecutionTime; var bestPath = [{ oldPos: -1, lastComponent: undefined }]; // Seed editLength = 0, i.e. the content starts with the same values var newPos = this.extractCommon(bestPath[0], newString, oldString, 0); if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) { // Identity per the equality and tokenizer return done([{ value: this.join(newString), count: newString.length }]); } // Once we hit the right edge of the edit graph on some diagonal k, we can // definitely reach the end of the edit graph in no more than k edits, so // there's no point in considering any moves to diagonal k+1 any more (from // which we're guaranteed to need at least k+1 more edits). // Similarly, once we've reached the bottom of the edit graph, there's no // point considering moves to lower diagonals. // We record this fact by setting minDiagonalToConsider and // maxDiagonalToConsider to some finite value once we've hit the edge of // the edit graph. // This optimization is not faithful to the original algorithm presented in // Myers's paper, which instead pointlessly extends D-paths off the end of // the edit graph - see page 7 of Myers's paper which notes this point // explicitly and illustrates it with a diagram. This has major performance // implications for some common scenarios. For instance, to compute a diff // where the new text simply appends d characters on the end of the // original text of length n, the true Myers algorithm will take O(n+d^2) // time while this optimization needs only O(n+d) time. var minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity; // Main worker method. checks all permutations of a given edit length for acceptance. function execEditLength() { for (var diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) { var basePath = void 0; var removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1]; if (removePath) { // No one else is going to attempt to use this value, clear it bestPath[diagonalPath - 1] = undefined; } var canAdd = false; if (addPath) { // what newPos will be after we do an insertion: var addPathNewPos = addPath.oldPos - diagonalPath; canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen; } var canRemove = removePath && removePath.oldPos + 1 < oldLen; if (!canAdd && !canRemove) { // If this path is a terminal then prune bestPath[diagonalPath] = undefined; continue; } // Select the diagonal that we want to branch from. We select the prior // path whose position in the old string is the farthest from the origin // and does not pass the bounds of the diff graph // TODO: Remove the `+ 1` here to make behavior match Myers algorithm // and prefer to order removals before insertions. if (!canRemove || canAdd && removePath.oldPos + 1 < addPath.oldPos) { basePath = self.addToPath(addPath, true, undefined, 0); } else { basePath = self.addToPath(removePath, undefined, true, 1); } newPos = self.extractCommon(basePath, newString, oldString, diagonalPath); if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) { // If we have hit the end of both strings, then we are done return done(buildValues(self, basePath.lastComponent, newString, oldString, self.useLongestToken)); } else { bestPath[diagonalPath] = basePath; if (basePath.oldPos + 1 >= oldLen) { maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1); } if (newPos + 1 >= newLen) { minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1); } } } editLength++; } // Performs the length of edit iteration. Is a bit fugly as this has to support the // sync and async mode which is never fun. Loops over execEditLength until a value // is produced, or until the edit length exceeds options.maxEditLength (if given), // in which case it will return undefined. if (callback) { (function exec() { setTimeout(function () { if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) { return callback(); } if (!execEditLength()) { exec(); } }, 0); })(); } else { while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) { var ret = execEditLength(); if (ret) { return ret; } } } }, addToPath: function addToPath(path, added, removed, oldPosInc) { var last = path.lastComponent; if (last && last.added === added && last.removed === removed) { return { oldPos: path.oldPos + oldPosInc, lastComponent: { count: last.count + 1, added: added, removed: removed, previousComponent: last.previousComponent } }; } else { return { oldPos: path.oldPos + oldPosInc, lastComponent: { count: 1, added: added, removed: removed, previousComponent: last } }; } }, extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) { var newLen = newString.length, oldLen = oldString.length, oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0; while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { newPos++; oldPos++; commonCount++; } if (commonCount) { basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent }; } basePath.oldPos = oldPos; return newPos; }, equals: function equals(left, right) { if (this.options.comparator) { return this.options.comparator(left, right); } else { return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase(); } }, removeEmpty: function removeEmpty(array) { var ret = []; for (var i = 0; i < array.length; i++) { if (array[i]) { ret.push(array[i]); } } return ret; }, castInput: function castInput(value) { return value; }, tokenize: function tokenize(value) { return value.split(''); }, join: function join(chars) { return chars.join(''); } }; function buildValues(diff, lastComponent, newString, oldString, useLongestToken) { // First we convert our linked list of components in reverse order to an // array in the right order: var components = []; var nextComponent; while (lastComponent) { components.push(lastComponent); nextComponent = lastComponent.previousComponent; delete lastComponent.previousComponent; lastComponent = nextComponent; } components.reverse(); var componentPos = 0, componentLen = components.length, newPos = 0, oldPos = 0; for (; componentPos < componentLen; componentPos++) { var component = components[componentPos]; if (!component.removed) { if (!component.added && useLongestToken) { var value = newString.slice(newPos, newPos + component.count); value = value.map(function (value, i) { var oldValue = oldString[oldPos + i]; return oldValue.length > value.length ? oldValue : value; }); component.value = diff.join(value); } else { component.value = diff.join(newString.slice(newPos, newPos + component.count)); } newPos += component.count; // Common case if (!component.added) { oldPos += component.count; } } else { component.value = diff.join(oldString.slice(oldPos, oldPos + component.count)); oldPos += component.count; // Reverse add and remove so removes are output first to match common convention // The diffing algorithm is tied to add then remove output and this is the simplest // route to get the desired output with minimal overhead. if (componentPos && components[componentPos - 1].added) { var tmp = components[componentPos - 1]; components[componentPos - 1] = components[componentPos]; components[componentPos] = tmp; } } } // Special case handle for when one terminal is ignored (i.e. whitespace). // For this case we merge the terminal into the prior string and drop the change. // This is only available for string mode. var finalComponent = components[componentLen - 1]; if (componentLen > 1 && typeof finalComponent.value === 'string' && (finalComponent.added || finalComponent.removed) && diff.equals('', finalComponent.value)) { components[componentLen - 2].value += finalComponent.value; components.pop(); } return components; } var characterDiff = new Diff(); function diffChars(oldStr, newStr, options) { return characterDiff.diff(oldStr, newStr, options); } function generateOptions(options, defaults) { if (typeof options === 'function') { defaults.callback = options; } else if (options) { for (var name in options) { /* istanbul ignore else */ if (options.hasOwnProperty(name)) { defaults[name] = options[name]; } } } return defaults; } // // Ranges and exceptions: // Latin-1 Supplement, 0080–00FF // - U+00D7 × Multiplication sign // - U+00F7 ÷ Division sign // Latin Extended-A, 0100–017F // Latin Extended-B, 0180–024F // IPA Extensions, 0250–02AF // Spacing Modifier Letters, 02B0–02FF // - U+02C7 ˇ ˇ Caron // - U+02D8 ˘ ˘ Breve // - U+02D9 ˙ ˙ Dot Above // - U+02DA ˚ ˚ Ring Above // - U+02DB ˛ ˛ Ogonek // - U+02DC ˜ ˜ Small Tilde // - U+02DD ˝ ˝ Double Acute Accent // Latin Extended Additional, 1E00–1EFF var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/; var reWhitespace = /\S/; var wordDiff = new Diff(); wordDiff.equals = function (left, right) { if (this.options.ignoreCase) { left = left.toLowerCase(); right = right.toLowerCase(); } return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right); }; wordDiff.tokenize = function (value) { // All whitespace symbols except newline group into one token, each newline - in separate token var tokens = value.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set. for (var i = 0; i < tokens.length - 1; i++) { // If we have an empty string in the next field and we have only word chars before and after, merge if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) { tokens[i] += tokens[i + 2]; tokens.splice(i + 1, 2); i--; } } return tokens; }; function diffWords(oldStr, newStr, options) { options = generateOptions(options, { ignoreWhitespace: true }); return wordDiff.diff(oldStr, newStr, options); } function diffWordsWithSpace(oldStr, newStr, options) { return wordDiff.diff(oldStr, newStr, options); } var lineDiff = new Diff(); lineDiff.tokenize = function (value) { if (this.options.stripTrailingCr) { // remove one \r before \n to match GNU diff's --strip-trailing-cr behavior value = value.replace(/\r\n/g, '\n'); } var retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line if (!linesAndNewlines[linesAndNewlines.length - 1]) { linesAndNewlines.pop(); } // Merge the content and line separators into single tokens for (var i = 0; i < linesAndNewlines.length; i++) { var line = linesAndNewlines[i]; if (i % 2 && !this.options.newlineIsToken) { retLines[retLines.length - 1] += line; } else { if (this.options.ignoreWhitespace) { line = line.trim(); } retLines.push(line); } } return retLines; }; function diffLines(oldStr, newStr, callback) { return lineDiff.diff(oldStr, newStr, callback); } function diffTrimmedLines(oldStr, newStr, callback) { var options = generateOptions(callback, { ignoreWhitespace: true }); return lineDiff.diff(oldStr, newStr, options); } var sentenceDiff = new Diff(); sentenceDiff.tokenize = function (value) { return value.split(/(\S.+?[.!?])(?=\s+|$)/); }; function diffSentences(oldStr, newStr, callback) { return sentenceDiff.diff(oldStr, newStr, callback); } var cssDiff = new Diff(); cssDiff.tokenize = function (value) { return value.split(/([{}:;,]|\s+)/); }; function diffCss(oldStr, newStr, callback) { return cssDiff.diff(oldStr, newStr, callback); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function (obj) { return typeof obj; }; } else { _typeof = function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var objectPrototypeToString = Object.prototype.toString; var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: jsonDiff.useLongestToken = true; jsonDiff.tokenize = lineDiff.tokenize; jsonDiff.castInput = function (value) { var _this$options = this.options, undefinedReplacement = _this$options.undefinedReplacement, _this$options$stringi = _this$options.stringifyReplacer, stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) { return typeof v === 'undefined' ? undefinedReplacement : v; } : _this$options$stringi; return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' '); }; jsonDiff.equals = function (left, right) { return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1')); }; function diffJson(oldObj, newObj, options) { return jsonDiff.diff(oldObj, newObj, options); } // This function handles the presence of circular references by bailing out when encountering an // object that is already on the "stack" of items being processed. Accepts an optional replacer function canonicalize(obj, stack, replacementStack, replacer, key) { stack = stack || []; replacementStack = replacementStack || []; if (replacer) { obj = replacer(key, obj); } var i; for (i = 0; i < stack.length; i += 1) { if (stack[i] === obj) { return replacementStack[i]; } } var canonicalizedObj; if ('[object Array]' === objectPrototypeToString.call(obj)) { stack.push(obj); canonicalizedObj = new Array(obj.length); replacementStack.push(canonicalizedObj); for (i = 0; i < obj.length; i += 1) { canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key); } stack.pop(); replacementStack.pop(); return canonicalizedObj; } if (obj && obj.toJSON) { obj = obj.toJSON(); } if (_typeof(obj) === 'object' && obj !== null) { stack.push(obj); canonicalizedObj = {}; replacementStack.push(canonicalizedObj); var sortedKeys = [], _key; for (_key in obj) { /* istanbul ignore else */ if (obj.hasOwnProperty(_key)) { sortedKeys.push(_key); } } sortedKeys.sort(); for (i = 0; i < sortedKeys.length; i += 1) { _key = sortedKeys[i]; canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key); } stack.pop(); replacementStack.pop(); } else { canonicalizedObj = obj; } return canonicalizedObj; } var arrayDiff = new Diff(); arrayDiff.tokenize = function (value) { return value.slice(); }; arrayDiff.join = arrayDiff.removeEmpty = function (value) { return value; }; function diffArrays(oldArr, newArr, callback) { return arrayDiff.diff(oldArr, newArr, callback); } function parsePatch(uniDiff) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/), delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [], list = [], i = 0; function parseIndex() { var index = {}; list.push(index); // Parse diff metadata while (i < diffstr.length) { var line = diffstr[i]; // File header found, end parsing diff metadata if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) { break; } // Diff index var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line); if (header) { index.index = header[1]; } i++; } // Parse file headers if they are defined. Unified diff requires them, but // there's no technical issues to have an isolated hunk without file header parseFileHeader(index); parseFileHeader(index); // Parse hunks index.hunks = []; while (i < diffstr.length) { var _line = diffstr[i]; if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) { break; } else if (/^@@/.test(_line)) { index.hunks.push(parseHunk()); } else if (_line && options.strict) { // Ignore unexpected content unless in strict mode throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line)); } else { i++; } } } // Parses the --- and +++ headers, if none are found, no lines // are consumed. function parseFileHeader(index) { var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]); if (fileHeader) { var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new'; var data = fileHeader[2].split('\t', 2); var fileName = data[0].replace(/\\\\/g, '\\'); if (/^".*"$/.test(fileName)) { fileName = fileName.substr(1, fileName.length - 2); } index[keyPrefix + 'FileName'] = fileName; index[keyPrefix + 'Header'] = (data[1] || '').trim(); i++; } } // Parses a hunk // This assumes that we are at the start of a hunk. function parseHunk() { var chunkHeaderIndex = i, chunkHeaderLine = diffstr[i++], chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); var hunk = { oldStart: +chunkHeader[1], oldLines: typeof chunkHeader[2] === 'undefined' ? 1 : +chunkHeader[2], newStart: +chunkHeader[3], newLines: typeof chunkHeader[4] === 'undefined' ? 1 : +chunkHeader[4], lines: [], linedelimiters: [] }; // Unified Diff Format quirk: If the chunk size is 0, // the first number is one lower than one would expect. // https://www.artima.com/weblogs/viewpost.jsp?thread=164293 if (hunk.oldLines === 0) { hunk.oldStart += 1; } if (hunk.newLines === 0) { hunk.newStart += 1; } var addCount = 0, removeCount = 0; for (; i < diffstr.length; i++) { // Lines starting with '---' could be mistaken for the "remove line" operation // But they could be the header for the next file. Therefore prune such cases out. if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) { break; } var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0]; if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { hunk.lines.push(diffstr[i]); hunk.linedelimiters.push(delimiters[i] || '\n'); if (operation === '+') { addCount++; } else if (operation === '-') { removeCount++; } else if (operation === ' ') { addCount++; removeCount++; } } else { break; } } // Handle the empty block count case if (!addCount && hunk.newLines === 1) { hunk.newLines = 0; } if (!removeCount && hunk.oldLines === 1) { hunk.oldLines = 0; } // Perform optional sanity checking if (options.strict) { if (addCount !== hunk.newLines) { throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); } if (removeCount !== hunk.oldLines) { throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); } } return hunk; } while (i < diffstr.length) { parseIndex(); } return list; } // Iterator that traverses in the range of [min, max], stepping // by distance from a given start position. I.e. for [0, 4], with // start of 2, this will iterate 2, 3, 1, 4, 0. function distanceIterator (start, minLine, maxLine) { var wantForward = true, backwardExhausted = false, forwardExhausted = false, localOffset = 1; return function iterator() { if (wantForward && !forwardExhausted) { if (backwardExhausted) { localOffset++; } else { wantForward = false; } // Check if trying to fit beyond text length, and if not, check it fits // after offset location (or desired location on first iteration) if (start + localOffset <= maxLine) { return localOffset; } forwardExhausted = true; } if (!backwardExhausted) { if (!forwardExhausted) { wantForward = true; } // Check if trying to fit before text beginning, and if not, check it fits // before offset location if (minLine <= start - localOffset) { return -localOffset++; } backwardExhausted = true; return iterator(); } // We tried to fit hunk before text beginning and beyond text length, then // hunk can't fit on the text. Return undefined }; } function applyPatch(source, uniDiff) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; if (typeof uniDiff === 'string') { uniDiff = parsePatch(uniDiff); } if (Array.isArray(uniDiff)) { if (uniDiff.length > 1) { throw new Error('applyPatch only works with a single input.'); } uniDiff = uniDiff[0]; } // Apply the diff to the input var lines = source.split(/\r\n|[\n\v\f\r\x85]/), delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [], hunks = uniDiff.hunks, compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) { return line === patchContent; }, errorCount = 0, fuzzFactor = options.fuzzFactor || 0, minLine = 0, offset = 0, removeEOFNL, addEOFNL; /** * Checks if the hunk exactly fits on the provided location */ function hunkFits(hunk, toPos) { for (var j = 0; j < hunk.lines.length; j++) { var line = hunk.lines[j], operation = line.length > 0 ? line[0] : ' ', content = line.length > 0 ? line.substr(1) : line; if (operation === ' ' || operation === '-') { // Context sanity check if (!compareLine(toPos + 1, lines[toPos], operation, content)) { errorCount++; if (errorCount > fuzzFactor) { return false; } } toPos++; } } return true; } // Search best fit offsets for each hunk based on the previous ones for (var i = 0; i < hunks.length; i++) { var hunk = hunks[i], maxLine = lines.length - hunk.oldLines, localOffset = 0, toPos = offset + hunk.oldStart - 1; var iterator = distanceIterator(toPos, minLine, maxLine); for (; localOffset !== undefined; localOffset = iterator()) { if (hunkFits(hunk, toPos + localOffset)) { hunk.offset = offset += localOffset; break; } } if (localOffset === undefined) { return false; } // Set lower text limit to end of the current hunk, so next ones don't try // to fit over already patched text minLine = hunk.offset + hunk.oldStart + hunk.oldLines; } // Apply patch hunks var diffOffset = 0; for (var _i = 0; _i < hunks.length; _i++) { var _hunk = hunks[_i], _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1; diffOffset += _hunk.newLines - _hunk.oldLines; for (var j = 0; j < _hunk.lines.length; j++) { var line = _hunk.lines[j], operation = line.length > 0 ? line[0] : ' ', content = line.length > 0 ? line.substr(1) : line, delimiter = _hunk.linedelimiters && _hunk.linedelimiters[j] || '\n'; if (operation === ' ') { _toPos++; } else if (operation === '-') { lines.splice(_toPos, 1); delimiters.splice(_toPos, 1); /* istanbul ignore else */ } else if (operation === '+') { lines.splice(_toPos, 0, content); delimiters.splice(_toPos, 0, delimiter); _toPos++; } else if (operation === '\\') { var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null; if (previousOperation === '+') { removeEOFNL = true; } else if (previousOperation === '-') { addEOFNL = true; } } } } // Handle EOFNL insertion/removal if (removeEOFNL) { while (!lines[lines.length - 1]) { lines.pop(); delimiters.pop(); } } else if (addEOFNL) { lines.push(''); delimiters.push('\n'); } for (var _k = 0; _k < lines.length - 1; _k++) { lines[_k] = lines[_k] + delimiters[_k]; } return lines.join(''); } // Wrapper that supports multiple file patches via callbacks. function applyPatches(uniDiff, options) { if (typeof uniDiff === 'string') { uniDiff = parsePatch(uniDiff); } var currentIndex = 0; function processIndex() { var index = uniDiff[currentIndex++]; if (!index) { return options.complete(); } options.loadFile(index, function (err, data) { if (err) { return options.complete(err); } var updatedContent = applyPatch(data, index, options); options.patched(index, updatedContent, function (err) { if (err) { return options.complete(err); } processIndex(); }); }); } processIndex(); } function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { if (!options) { options = {}; } if (typeof options.context === 'undefined') { options.context = 4; } var diff = diffLines(oldStr, newStr, options); if (!diff) { return; } diff.push({ value: '', lines: [] }); // Append an empty value to make cleanup easier function contextLines(lines) { return lines.map(function (entry) { return ' ' + entry; }); } var hunks = []; var oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; var _loop = function _loop(i) { var current = diff[i], lines = current.lines || current.value.replace(/\n$/, '').split('\n'); current.lines = lines; if (current.added || current.removed) { var _curRange; // If we have previous context, start with that if (!oldRangeStart) { var prev = diff[i - 1]; oldRangeStart = oldLine; newRangeStart = newLine; if (prev) { curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : []; oldRangeStart -= curRange.length; newRangeStart -= curRange.length; } } // Output our changes (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) { return (current.added ? '+' : '-') + entry; }))); // Track the updated file position if (current.added) { newLine += lines.length; } else { oldLine += lines.length; } } else { // Identical context lines. Track line changes if (oldRangeStart) { // Close out any changes that have been output (or join overlapping) if (lines.length <= options.context * 2 && i < diff.length - 2) { var _curRange2; // Overlapping (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines))); } else { var _curRange3; // end the range and output var contextSize = Math.min(lines.length, options.context); (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize)))); var hunk = { oldStart: oldRangeStart, oldLines: oldLine - oldRangeStart + contextSize, newStart: newRangeStart, newLines: newLine - newRangeStart + contextSize, lines: curRange }; if (i >= diff.length - 2 && lines.length <= options.context) { // EOF is inside this hunk var oldEOFNewline = /\n$/.test(oldStr); var newEOFNewline = /\n$/.test(newStr); var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines; if (!oldEOFNewline && noNlBeforeAdds && oldStr.length > 0) { // special case: old has no eol and no trailing context; no-nl can end up before adds // however, if the old file is empty, do not output the no-nl line curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file'); } if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) { curRange.push('\\ No newline at end of file'); } } hunks.push(hunk); oldRangeStart = 0; newRangeStart = 0; curRange = []; } } oldLine += lines.length; newLine += lines.length; } }; for (var i = 0; i < diff.length; i++) { _loop(i); } return { oldFileName: oldFileName, newFileName: newFileName, oldHeader: oldHeader, newHeader: newHeader, hunks: hunks }; } function formatPatch(diff) { if (Array.isArray(diff)) { return diff.map(formatPatch).join('\n'); } var ret = []; if (diff.oldFileName == diff.newFileName) { ret.push('Index: ' + diff.oldFileName); } ret.push('==================================================================='); ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader)); ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader)); for (var i = 0; i < diff.hunks.length; i++) { var hunk = diff.hunks[i]; // Unified Diff Format quirk: If the chunk size is 0, // the first number is one lower than one would expect. // https://www.artima.com/weblogs/viewpost.jsp?thread=164293 if (hunk.oldLines === 0) { hunk.oldStart -= 1; } if (hunk.newLines === 0) { hunk.newStart -= 1; } ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@'); ret.push.apply(ret, hunk.lines); } return ret.join('\n') + '\n'; } function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { return formatPatch(structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options)); } function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); } function arrayEqual(a, b) { if (a.length !== b.length) { return false; } return arrayStartsWith(a, b); } function arrayStartsWith(array, start) { if (start.length > array.length) { return false; } for (var i = 0; i < start.length; i++) { if (start[i] !== array[i]) { return false; } } return true; } function calcLineCount(hunk) { var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines), oldLines = _calcOldNewLineCount.oldLines, newLines = _calcOldNewLineCount.newLines; if (oldLines !== undefined) { hunk.oldLines = oldLines; } else { delete hunk.oldLines; } if (newLines !== undefined) { hunk.newLines = newLines; } else { delete hunk.newLines; } } function merge(mine, theirs, base) { mine = loadPatch(mine, base); theirs = loadPatch(theirs, base); var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning. // Leaving sanity checks on this to the API consumer that may know more about the // meaning in their own context. if (mine.index || theirs.index) { ret.index = mine.index || theirs.index; } if (mine.newFileName || theirs.newFileName) { if (!fileNameChanged(mine)) { // No header or no change in ours, use theirs (and ours if theirs does not exist) ret.oldFileName = theirs.oldFileName || mine.oldFileName; ret.newFileName = theirs.newFileName || mine.newFileName; ret.oldHeader = theirs.oldHeader || mine.oldHeader; ret.newHeader = theirs.newHeader || mine.newHeader; } else if (!fileNameChanged(theirs)) { // No header or no change in theirs, use ours ret.oldFileName = mine.oldFileName; ret.newFileName = mine.newFileName; ret.oldHeader = mine.oldHeader; ret.newHeader = mine.newHeader; } else { // Both changed... figure it out ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName); ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName); ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader); ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader); } } ret.hunks = []; var mineIndex = 0, theirsIndex = 0, mineOffset = 0, theirsOffset = 0; while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) { var mineCurrent = mine.hunks[mineIndex] || { oldStart: Infinity }, theirsCurrent = theirs.hunks[theirsIndex] || { oldStart: Infinity }; if (hunkBefore(mineCurrent, theirsCurrent)) { // This patch does not overlap with any of the others, yay. ret.hunks.push(cloneHunk(mineCurrent, mineOffset)); mineIndex++; theirsOffset += mineCurrent.newLines - mineCurrent.oldLines; } else if (hunkBefore(theirsCurrent, mineCurrent)) { // This patch does not overlap with any of the others, yay. ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset)); theirsIndex++; mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines; } else { // Overlap, merge as best we can var mergedHunk = { oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart), oldLines: 0, newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset), newLines: 0, lines: [] }; mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines); theirsIndex++; mineIndex++; ret.hunks.push(mergedHunk); } } return ret; } function loadPatch(param, base) { if (typeof param === 'string') { if (/^@@/m.test(param) || /^Index:/m.test(param)) { return parsePatch(param)[0]; } if (!base) { throw new Error('Must provide a base reference or pass in a patch'); } return structuredPatch(undefined, undefined, base, param); } return param; } function fileNameChanged(patch) { return patch.newFileName && patch.newFileName !== patch.oldFileName; } function selectField(index, mine, theirs) { if (mine === theirs) { return mine; } else { index.conflict = true; return { mine: mine, theirs: theirs }; } } function hunkBefore(test, check) { return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart; } function cloneHunk(hunk, offset) { return { oldStart: hunk.oldStart, oldLines: hunk.oldLines, newStart: hunk.newStart + offset, newLines: hunk.newLines, lines: hunk.lines }; } function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) { // This will generally result in a conflicted hunk, but there are cases where the context // is the only overlap where we can successfully merge the content here. var mine = { offset: mineOffset, lines: mineLines, index: 0 }, their = { offset: theirOffset, lines: theirLines, index: 0 }; // Handle any leading content insertLeading(hunk, mine, their); insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each. while (mine.index < mine.lines.length && their.index < their.lines.length) { var mineCurrent = mine.lines[mine.index], theirCurrent = their.lines[their.index]; if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) { // Both modified ... mutualChange(hunk, mine, their); } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') { var _hunk$lines; // Mine inserted (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine))); } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') { var _hunk$lines2; // Theirs inserted (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their))); } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') { // Mine removed or edited removal(hunk, mine, their); } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') { // Their removed or edited removal(hunk, their, mine, true); } else if (mineCurrent === theirCurrent) { // Context identity hunk.lines.push(mineCurrent); mine.index++; their.index++; } else { // Context mismatch conflict(hunk, collectChange(mine), collectChange(their)); } } // Now push anything that may be remaining insertTrailing(hunk, mine); insertTrailing(hunk, their); calcLineCount(hunk); } function mutualChange(hunk, mine, their) { var myChanges = collectChange(mine), theirChanges = collectChange(their); if (allRemoves(myChanges) && allRemoves(theirChanges)) { // Special case for remove changes that are supersets of one another if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) { var _hunk$lines3; (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges)); return; } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) { var _hunk$lines4; (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges)); return; } } else if (arrayEqual(myChanges, theirChanges)) { var _hunk$lines5; (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges)); return; } conflict(hunk, myChanges, theirChanges); } function removal(hunk, mine, their, swap) { var myChanges = collectChange(mine), theirChanges = collectContext(their, myChanges); if (theirChanges.merged) { var _hunk$lines6; (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged)); } else { conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges); } } function conflict(hunk, mine, their) { hunk.conflict = true; hunk.lines.push({ conflict: true, mine: mine, theirs: their }); } function insertLeading(hunk, insert, their) { while (insert.offset < their.offset && insert.index < insert.lines.length) { var line = insert.lines[insert.index++]; hunk.lines.push(line); insert.offset++; } } function insertTrailing(hunk, insert) { while (insert.index < insert.lines.length) { var line = insert.lines[insert.index++]; hunk.lines.push(line); } } function collectChange(state) { var ret = [], operation = state.lines[state.index][0]; while (state.index < state.lines.length) { var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change. if (operation === '-' && line[0] === '+') { operation = '+'; } if (operation === line[0]) { ret.push(line); state.index++; } else { break; } } return ret; } function collectContext(state, matchChanges) { var changes = [], merged = [], matchIndex = 0, contextChanges = false, conflicted = false; while (matchIndex < matchChanges.length && state.index < state.lines.length) { var change = state.lines[state.index], match = matchChanges[matchIndex]; // Once we've hit our add, then we are done if (match[0] === '+') { break; } contextChanges = contextChanges || change[0] !== ' '; merged.push(match); matchIndex++; // Consume any additions in the other block as a conflict to attempt // to pull in the remaining context after this if (change[0] === '+') { conflicted = true; while (change[0] === '+') { changes.push(change); change = state.lines[++state.index]; } } if (match.substr(1) === change.substr(1)) { changes.push(change); state.index++; } else { conflicted = true; } } if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) { conflicted = true; } if (conflicted) { return changes; } while (matchIndex < matchChanges.length) { merged.push(matchChanges[matchIndex++]); } return { merged: merged, changes: changes }; } function allRemoves(changes) { return changes.reduce(function (prev, change) { return prev && change[0] === '-'; }, true); } function skipRemoveSuperset(state, removeChanges, delta) { for (var i = 0; i < delta; i++) { var changeContent = removeChanges[removeChanges.length - delta + i].substr(1); if (state.lines[state.index + i] !== ' ' + changeContent) { return false; } } state.index += delta; return true; } function calcOldNewLineCount(lines) { var oldLines = 0; var newLines = 0; lines.forEach(function (line) { if (typeof line !== 'string') { var myCount = calcOldNewLineCount(line.mine); var theirCount = calcOldNewLineCount(line.theirs); if (oldLines !== undefined) { if (myCount.oldLines === theirCount.oldLines) { oldLines += myCount.oldLines; } else { oldLines = undefined; } } if (newLines !== undefined) { if (myCount.newLines === theirCount.newLines) { newLines += myCount.newLines; } else { newLines = undefined; } } } else { if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) { newLines++; } if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) { oldLines++; } } }); return { oldLines: oldLines, newLines: newLines }; } function reversePatch(structuredPatch) { if (Array.isArray(structuredPatch)) { return structuredPatch.map(reversePatch).reverse(); } return _objectSpread2(_objectSpread2({}, structuredPatch), {}, { oldFileName: structuredPatch.newFileName, oldHeader: structuredPatch.newHeader, newFileName: structuredPatch.oldFileName, newHeader: structuredPatch.oldHeader, hunks: structuredPatch.hunks.map(function (hunk) { return { oldLines: hunk.newLines, oldStart: hunk.newStart, newLines: hunk.oldLines, newStart: hunk.oldStart, linedelimiters: hunk.linedelimiters, lines: hunk.lines.map(function (l) { if (l.startsWith('-')) { return "+".concat(l.slice(1)); } if (l.startsWith('+')) { return "-".concat(l.slice(1)); } return l; }) }; }) }); } // See: http://code.google.com/p/google-diff-match-patch/wiki/API function convertChangesToDMP(changes) { var ret = [], change, operation; for (var i = 0; i < changes.length; i++) { change = changes[i]; if (change.added) { operation = 1; } else if (change.removed) { operation = -1; } else { operation = 0; } ret.push([operation, change.value]); } return ret; } function convertChangesToXML(changes) { var ret = []; for (var i = 0; i < changes.length; i++) { var change = changes[i]; if (change.added) { ret.push(''); } else if (change.removed) { ret.push(''); } ret.push(escapeHTML(change.value)); if (change.added) { ret.push(''); } else if (change.removed) { ret.push(''); } } return ret.join(''); } function escapeHTML(s) { var n = s; n = n.replace(/&/g, '&'); n = n.replace(//g, '>'); n = n.replace(/"/g, '"'); return n; } export { Diff, applyPatch, applyPatches, canonicalize, convertChangesToDMP, convertChangesToXML, createPatch, createTwoFilesPatch, diffArrays, diffChars, diffCss, diffJson, diffLines, diffSentences, diffTrimmedLines, diffWords, diffWordsWithSpace, formatPatch, merge, parsePatch, reversePatch, structuredPatch }; PK ~\> QQdiff/lib/index.mjsnu[function Diff() {} Diff.prototype = { diff: function diff(oldString, newString) { var _options$timeout; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var callback = options.callback; if (typeof options === 'function') { callback = options; options = {}; } this.options = options; var self = this; function done(value) { if (callback) { setTimeout(function () { callback(undefined, value); }, 0); return true; } else { return value; } } // Allow subclasses to massage the input prior to running oldString = this.castInput(oldString); newString = this.castInput(newString); oldString = this.removeEmpty(this.tokenize(oldString)); newString = this.removeEmpty(this.tokenize(newString)); var newLen = newString.length, oldLen = oldString.length; var editLength = 1; var maxEditLength = newLen + oldLen; if (options.maxEditLength) { maxEditLength = Math.min(maxEditLength, options.maxEditLength); } var maxExecutionTime = (_options$timeout = options.timeout) !== null && _options$timeout !== void 0 ? _options$timeout : Infinity; var abortAfterTimestamp = Date.now() + maxExecutionTime; var bestPath = [{ oldPos: -1, lastComponent: undefined }]; // Seed editLength = 0, i.e. the content starts with the same values var newPos = this.extractCommon(bestPath[0], newString, oldString, 0); if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) { // Identity per the equality and tokenizer return done([{ value: this.join(newString), count: newString.length }]); } // Once we hit the right edge of the edit graph on some diagonal k, we can // definitely reach the end of the edit graph in no more than k edits, so // there's no point in considering any moves to diagonal k+1 any more (from // which we're guaranteed to need at least k+1 more edits). // Similarly, once we've reached the bottom of the edit graph, there's no // point considering moves to lower diagonals. // We record this fact by setting minDiagonalToConsider and // maxDiagonalToConsider to some finite value once we've hit the edge of // the edit graph. // This optimization is not faithful to the original algorithm presented in // Myers's paper, which instead pointlessly extends D-paths off the end of // the edit graph - see page 7 of Myers's paper which notes this point // explicitly and illustrates it with a diagram. This has major performance // implications for some common scenarios. For instance, to compute a diff // where the new text simply appends d characters on the end of the // original text of length n, the true Myers algorithm will take O(n+d^2) // time while this optimization needs only O(n+d) time. var minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity; // Main worker method. checks all permutations of a given edit length for acceptance. function execEditLength() { for (var diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) { var basePath = void 0; var removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1]; if (removePath) { // No one else is going to attempt to use this value, clear it bestPath[diagonalPath - 1] = undefined; } var canAdd = false; if (addPath) { // what newPos will be after we do an insertion: var addPathNewPos = addPath.oldPos - diagonalPath; canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen; } var canRemove = removePath && removePath.oldPos + 1 < oldLen; if (!canAdd && !canRemove) { // If this path is a terminal then prune bestPath[diagonalPath] = undefined; continue; } // Select the diagonal that we want to branch from. We select the prior // path whose position in the old string is the farthest from the origin // and does not pass the bounds of the diff graph // TODO: Remove the `+ 1` here to make behavior match Myers algorithm // and prefer to order removals before insertions. if (!canRemove || canAdd && removePath.oldPos + 1 < addPath.oldPos) { basePath = self.addToPath(addPath, true, undefined, 0); } else { basePath = self.addToPath(removePath, undefined, true, 1); } newPos = self.extractCommon(basePath, newString, oldString, diagonalPath); if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) { // If we have hit the end of both strings, then we are done return done(buildValues(self, basePath.lastComponent, newString, oldString, self.useLongestToken)); } else { bestPath[diagonalPath] = basePath; if (basePath.oldPos + 1 >= oldLen) { maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1); } if (newPos + 1 >= newLen) { minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1); } } } editLength++; } // Performs the length of edit iteration. Is a bit fugly as this has to support the // sync and async mode which is never fun. Loops over execEditLength until a value // is produced, or until the edit length exceeds options.maxEditLength (if given), // in which case it will return undefined. if (callback) { (function exec() { setTimeout(function () { if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) { return callback(); } if (!execEditLength()) { exec(); } }, 0); })(); } else { while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) { var ret = execEditLength(); if (ret) { return ret; } } } }, addToPath: function addToPath(path, added, removed, oldPosInc) { var last = path.lastComponent; if (last && last.added === added && last.removed === removed) { return { oldPos: path.oldPos + oldPosInc, lastComponent: { count: last.count + 1, added: added, removed: removed, previousComponent: last.previousComponent } }; } else { return { oldPos: path.oldPos + oldPosInc, lastComponent: { count: 1, added: added, removed: removed, previousComponent: last } }; } }, extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) { var newLen = newString.length, oldLen = oldString.length, oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0; while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { newPos++; oldPos++; commonCount++; } if (commonCount) { basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent }; } basePath.oldPos = oldPos; return newPos; }, equals: function equals(left, right) { if (this.options.comparator) { return this.options.comparator(left, right); } else { return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase(); } }, removeEmpty: function removeEmpty(array) { var ret = []; for (var i = 0; i < array.length; i++) { if (array[i]) { ret.push(array[i]); } } return ret; }, castInput: function castInput(value) { return value; }, tokenize: function tokenize(value) { return value.split(''); }, join: function join(chars) { return chars.join(''); } }; function buildValues(diff, lastComponent, newString, oldString, useLongestToken) { // First we convert our linked list of components in reverse order to an // array in the right order: var components = []; var nextComponent; while (lastComponent) { components.push(lastComponent); nextComponent = lastComponent.previousComponent; delete lastComponent.previousComponent; lastComponent = nextComponent; } components.reverse(); var componentPos = 0, componentLen = components.length, newPos = 0, oldPos = 0; for (; componentPos < componentLen; componentPos++) { var component = components[componentPos]; if (!component.removed) { if (!component.added && useLongestToken) { var value = newString.slice(newPos, newPos + component.count); value = value.map(function (value, i) { var oldValue = oldString[oldPos + i]; return oldValue.length > value.length ? oldValue : value; }); component.value = diff.join(value); } else { component.value = diff.join(newString.slice(newPos, newPos + component.count)); } newPos += component.count; // Common case if (!component.added) { oldPos += component.count; } } else { component.value = diff.join(oldString.slice(oldPos, oldPos + component.count)); oldPos += component.count; // Reverse add and remove so removes are output first to match common convention // The diffing algorithm is tied to add then remove output and this is the simplest // route to get the desired output with minimal overhead. if (componentPos && components[componentPos - 1].added) { var tmp = components[componentPos - 1]; components[componentPos - 1] = components[componentPos]; components[componentPos] = tmp; } } } // Special case handle for when one terminal is ignored (i.e. whitespace). // For this case we merge the terminal into the prior string and drop the change. // This is only available for string mode. var finalComponent = components[componentLen - 1]; if (componentLen > 1 && typeof finalComponent.value === 'string' && (finalComponent.added || finalComponent.removed) && diff.equals('', finalComponent.value)) { components[componentLen - 2].value += finalComponent.value; components.pop(); } return components; } var characterDiff = new Diff(); function diffChars(oldStr, newStr, options) { return characterDiff.diff(oldStr, newStr, options); } function generateOptions(options, defaults) { if (typeof options === 'function') { defaults.callback = options; } else if (options) { for (var name in options) { /* istanbul ignore else */ if (options.hasOwnProperty(name)) { defaults[name] = options[name]; } } } return defaults; } // // Ranges and exceptions: // Latin-1 Supplement, 0080–00FF // - U+00D7 × Multiplication sign // - U+00F7 ÷ Division sign // Latin Extended-A, 0100–017F // Latin Extended-B, 0180–024F // IPA Extensions, 0250–02AF // Spacing Modifier Letters, 02B0–02FF // - U+02C7 ˇ ˇ Caron // - U+02D8 ˘ ˘ Breve // - U+02D9 ˙ ˙ Dot Above // - U+02DA ˚ ˚ Ring Above // - U+02DB ˛ ˛ Ogonek // - U+02DC ˜ ˜ Small Tilde // - U+02DD ˝ ˝ Double Acute Accent // Latin Extended Additional, 1E00–1EFF var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/; var reWhitespace = /\S/; var wordDiff = new Diff(); wordDiff.equals = function (left, right) { if (this.options.ignoreCase) { left = left.toLowerCase(); right = right.toLowerCase(); } return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right); }; wordDiff.tokenize = function (value) { // All whitespace symbols except newline group into one token, each newline - in separate token var tokens = value.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set. for (var i = 0; i < tokens.length - 1; i++) { // If we have an empty string in the next field and we have only word chars before and after, merge if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) { tokens[i] += tokens[i + 2]; tokens.splice(i + 1, 2); i--; } } return tokens; }; function diffWords(oldStr, newStr, options) { options = generateOptions(options, { ignoreWhitespace: true }); return wordDiff.diff(oldStr, newStr, options); } function diffWordsWithSpace(oldStr, newStr, options) { return wordDiff.diff(oldStr, newStr, options); } var lineDiff = new Diff(); lineDiff.tokenize = function (value) { if (this.options.stripTrailingCr) { // remove one \r before \n to match GNU diff's --strip-trailing-cr behavior value = value.replace(/\r\n/g, '\n'); } var retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line if (!linesAndNewlines[linesAndNewlines.length - 1]) { linesAndNewlines.pop(); } // Merge the content and line separators into single tokens for (var i = 0; i < linesAndNewlines.length; i++) { var line = linesAndNewlines[i]; if (i % 2 && !this.options.newlineIsToken) { retLines[retLines.length - 1] += line; } else { if (this.options.ignoreWhitespace) { line = line.trim(); } retLines.push(line); } } return retLines; }; function diffLines(oldStr, newStr, callback) { return lineDiff.diff(oldStr, newStr, callback); } function diffTrimmedLines(oldStr, newStr, callback) { var options = generateOptions(callback, { ignoreWhitespace: true }); return lineDiff.diff(oldStr, newStr, options); } var sentenceDiff = new Diff(); sentenceDiff.tokenize = function (value) { return value.split(/(\S.+?[.!?])(?=\s+|$)/); }; function diffSentences(oldStr, newStr, callback) { return sentenceDiff.diff(oldStr, newStr, callback); } var cssDiff = new Diff(); cssDiff.tokenize = function (value) { return value.split(/([{}:;,]|\s+)/); }; function diffCss(oldStr, newStr, callback) { return cssDiff.diff(oldStr, newStr, callback); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function (obj) { return typeof obj; }; } else { _typeof = function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var objectPrototypeToString = Object.prototype.toString; var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: jsonDiff.useLongestToken = true; jsonDiff.tokenize = lineDiff.tokenize; jsonDiff.castInput = function (value) { var _this$options = this.options, undefinedReplacement = _this$options.undefinedReplacement, _this$options$stringi = _this$options.stringifyReplacer, stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) { return typeof v === 'undefined' ? undefinedReplacement : v; } : _this$options$stringi; return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' '); }; jsonDiff.equals = function (left, right) { return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1')); }; function diffJson(oldObj, newObj, options) { return jsonDiff.diff(oldObj, newObj, options); } // This function handles the presence of circular references by bailing out when encountering an // object that is already on the "stack" of items being processed. Accepts an optional replacer function canonicalize(obj, stack, replacementStack, replacer, key) { stack = stack || []; replacementStack = replacementStack || []; if (replacer) { obj = replacer(key, obj); } var i; for (i = 0; i < stack.length; i += 1) { if (stack[i] === obj) { return replacementStack[i]; } } var canonicalizedObj; if ('[object Array]' === objectPrototypeToString.call(obj)) { stack.push(obj); canonicalizedObj = new Array(obj.length); replacementStack.push(canonicalizedObj); for (i = 0; i < obj.length; i += 1) { canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key); } stack.pop(); replacementStack.pop(); return canonicalizedObj; } if (obj && obj.toJSON) { obj = obj.toJSON(); } if (_typeof(obj) === 'object' && obj !== null) { stack.push(obj); canonicalizedObj = {}; replacementStack.push(canonicalizedObj); var sortedKeys = [], _key; for (_key in obj) { /* istanbul ignore else */ if (obj.hasOwnProperty(_key)) { sortedKeys.push(_key); } } sortedKeys.sort(); for (i = 0; i < sortedKeys.length; i += 1) { _key = sortedKeys[i]; canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key); } stack.pop(); replacementStack.pop(); } else { canonicalizedObj = obj; } return canonicalizedObj; } var arrayDiff = new Diff(); arrayDiff.tokenize = function (value) { return value.slice(); }; arrayDiff.join = arrayDiff.removeEmpty = function (value) { return value; }; function diffArrays(oldArr, newArr, callback) { return arrayDiff.diff(oldArr, newArr, callback); } function parsePatch(uniDiff) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/), delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [], list = [], i = 0; function parseIndex() { var index = {}; list.push(index); // Parse diff metadata while (i < diffstr.length) { var line = diffstr[i]; // File header found, end parsing diff metadata if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) { break; } // Diff index var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line); if (header) { index.index = header[1]; } i++; } // Parse file headers if they are defined. Unified diff requires them, but // there's no technical issues to have an isolated hunk without file header parseFileHeader(index); parseFileHeader(index); // Parse hunks index.hunks = []; while (i < diffstr.length) { var _line = diffstr[i]; if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) { break; } else if (/^@@/.test(_line)) { index.hunks.push(parseHunk()); } else if (_line && options.strict) { // Ignore unexpected content unless in strict mode throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line)); } else { i++; } } } // Parses the --- and +++ headers, if none are found, no lines // are consumed. function parseFileHeader(index) { var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]); if (fileHeader) { var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new'; var data = fileHeader[2].split('\t', 2); var fileName = data[0].replace(/\\\\/g, '\\'); if (/^".*"$/.test(fileName)) { fileName = fileName.substr(1, fileName.length - 2); } index[keyPrefix + 'FileName'] = fileName; index[keyPrefix + 'Header'] = (data[1] || '').trim(); i++; } } // Parses a hunk // This assumes that we are at the start of a hunk. function parseHunk() { var chunkHeaderIndex = i, chunkHeaderLine = diffstr[i++], chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); var hunk = { oldStart: +chunkHeader[1], oldLines: typeof chunkHeader[2] === 'undefined' ? 1 : +chunkHeader[2], newStart: +chunkHeader[3], newLines: typeof chunkHeader[4] === 'undefined' ? 1 : +chunkHeader[4], lines: [], linedelimiters: [] }; // Unified Diff Format quirk: If the chunk size is 0, // the first number is one lower than one would expect. // https://www.artima.com/weblogs/viewpost.jsp?thread=164293 if (hunk.oldLines === 0) { hunk.oldStart += 1; } if (hunk.newLines === 0) { hunk.newStart += 1; } var addCount = 0, removeCount = 0; for (; i < diffstr.length; i++) { // Lines starting with '---' could be mistaken for the "remove line" operation // But they could be the header for the next file. Therefore prune such cases out. if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) { break; } var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0]; if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { hunk.lines.push(diffstr[i]); hunk.linedelimiters.push(delimiters[i] || '\n'); if (operation === '+') { addCount++; } else if (operation === '-') { removeCount++; } else if (operation === ' ') { addCount++; removeCount++; } } else { break; } } // Handle the empty block count case if (!addCount && hunk.newLines === 1) { hunk.newLines = 0; } if (!removeCount && hunk.oldLines === 1) { hunk.oldLines = 0; } // Perform optional sanity checking if (options.strict) { if (addCount !== hunk.newLines) { throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); } if (removeCount !== hunk.oldLines) { throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); } } return hunk; } while (i < diffstr.length) { parseIndex(); } return list; } // Iterator that traverses in the range of [min, max], stepping // by distance from a given start position. I.e. for [0, 4], with // start of 2, this will iterate 2, 3, 1, 4, 0. function distanceIterator (start, minLine, maxLine) { var wantForward = true, backwardExhausted = false, forwardExhausted = false, localOffset = 1; return function iterator() { if (wantForward && !forwardExhausted) { if (backwardExhausted) { localOffset++; } else { wantForward = false; } // Check if trying to fit beyond text length, and if not, check it fits // after offset location (or desired location on first iteration) if (start + localOffset <= maxLine) { return localOffset; } forwardExhausted = true; } if (!backwardExhausted) { if (!forwardExhausted) { wantForward = true; } // Check if trying to fit before text beginning, and if not, check it fits // before offset location if (minLine <= start - localOffset) { return -localOffset++; } backwardExhausted = true; return iterator(); } // We tried to fit hunk before text beginning and beyond text length, then // hunk can't fit on the text. Return undefined }; } function applyPatch(source, uniDiff) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; if (typeof uniDiff === 'string') { uniDiff = parsePatch(uniDiff); } if (Array.isArray(uniDiff)) { if (uniDiff.length > 1) { throw new Error('applyPatch only works with a single input.'); } uniDiff = uniDiff[0]; } // Apply the diff to the input var lines = source.split(/\r\n|[\n\v\f\r\x85]/), delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [], hunks = uniDiff.hunks, compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) { return line === patchContent; }, errorCount = 0, fuzzFactor = options.fuzzFactor || 0, minLine = 0, offset = 0, removeEOFNL, addEOFNL; /** * Checks if the hunk exactly fits on the provided location */ function hunkFits(hunk, toPos) { for (var j = 0; j < hunk.lines.length; j++) { var line = hunk.lines[j], operation = line.length > 0 ? line[0] : ' ', content = line.length > 0 ? line.substr(1) : line; if (operation === ' ' || operation === '-') { // Context sanity check if (!compareLine(toPos + 1, lines[toPos], operation, content)) { errorCount++; if (errorCount > fuzzFactor) { return false; } } toPos++; } } return true; } // Search best fit offsets for each hunk based on the previous ones for (var i = 0; i < hunks.length; i++) { var hunk = hunks[i], maxLine = lines.length - hunk.oldLines, localOffset = 0, toPos = offset + hunk.oldStart - 1; var iterator = distanceIterator(toPos, minLine, maxLine); for (; localOffset !== undefined; localOffset = iterator()) { if (hunkFits(hunk, toPos + localOffset)) { hunk.offset = offset += localOffset; break; } } if (localOffset === undefined) { return false; } // Set lower text limit to end of the current hunk, so next ones don't try // to fit over already patched text minLine = hunk.offset + hunk.oldStart + hunk.oldLines; } // Apply patch hunks var diffOffset = 0; for (var _i = 0; _i < hunks.length; _i++) { var _hunk = hunks[_i], _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1; diffOffset += _hunk.newLines - _hunk.oldLines; for (var j = 0; j < _hunk.lines.length; j++) { var line = _hunk.lines[j], operation = line.length > 0 ? line[0] : ' ', content = line.length > 0 ? line.substr(1) : line, delimiter = _hunk.linedelimiters && _hunk.linedelimiters[j] || '\n'; if (operation === ' ') { _toPos++; } else if (operation === '-') { lines.splice(_toPos, 1); delimiters.splice(_toPos, 1); /* istanbul ignore else */ } else if (operation === '+') { lines.splice(_toPos, 0, content); delimiters.splice(_toPos, 0, delimiter); _toPos++; } else if (operation === '\\') { var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null; if (previousOperation === '+') { removeEOFNL = true; } else if (previousOperation === '-') { addEOFNL = true; } } } } // Handle EOFNL insertion/removal if (removeEOFNL) { while (!lines[lines.length - 1]) { lines.pop(); delimiters.pop(); } } else if (addEOFNL) { lines.push(''); delimiters.push('\n'); } for (var _k = 0; _k < lines.length - 1; _k++) { lines[_k] = lines[_k] + delimiters[_k]; } return lines.join(''); } // Wrapper that supports multiple file patches via callbacks. function applyPatches(uniDiff, options) { if (typeof uniDiff === 'string') { uniDiff = parsePatch(uniDiff); } var currentIndex = 0; function processIndex() { var index = uniDiff[currentIndex++]; if (!index) { return options.complete(); } options.loadFile(index, function (err, data) { if (err) { return options.complete(err); } var updatedContent = applyPatch(data, index, options); options.patched(index, updatedContent, function (err) { if (err) { return options.complete(err); } processIndex(); }); }); } processIndex(); } function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { if (!options) { options = {}; } if (typeof options.context === 'undefined') { options.context = 4; } var diff = diffLines(oldStr, newStr, options); if (!diff) { return; } diff.push({ value: '', lines: [] }); // Append an empty value to make cleanup easier function contextLines(lines) { return lines.map(function (entry) { return ' ' + entry; }); } var hunks = []; var oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; var _loop = function _loop(i) { var current = diff[i], lines = current.lines || current.value.replace(/\n$/, '').split('\n'); current.lines = lines; if (current.added || current.removed) { var _curRange; // If we have previous context, start with that if (!oldRangeStart) { var prev = diff[i - 1]; oldRangeStart = oldLine; newRangeStart = newLine; if (prev) { curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : []; oldRangeStart -= curRange.length; newRangeStart -= curRange.length; } } // Output our changes (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) { return (current.added ? '+' : '-') + entry; }))); // Track the updated file position if (current.added) { newLine += lines.length; } else { oldLine += lines.length; } } else { // Identical context lines. Track line changes if (oldRangeStart) { // Close out any changes that have been output (or join overlapping) if (lines.length <= options.context * 2 && i < diff.length - 2) { var _curRange2; // Overlapping (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines))); } else { var _curRange3; // end the range and output var contextSize = Math.min(lines.length, options.context); (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize)))); var hunk = { oldStart: oldRangeStart, oldLines: oldLine - oldRangeStart + contextSize, newStart: newRangeStart, newLines: newLine - newRangeStart + contextSize, lines: curRange }; if (i >= diff.length - 2 && lines.length <= options.context) { // EOF is inside this hunk var oldEOFNewline = /\n$/.test(oldStr); var newEOFNewline = /\n$/.test(newStr); var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines; if (!oldEOFNewline && noNlBeforeAdds && oldStr.length > 0) { // special case: old has no eol and no trailing context; no-nl can end up before adds // however, if the old file is empty, do not output the no-nl line curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file'); } if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) { curRange.push('\\ No newline at end of file'); } } hunks.push(hunk); oldRangeStart = 0; newRangeStart = 0; curRange = []; } } oldLine += lines.length; newLine += lines.length; } }; for (var i = 0; i < diff.length; i++) { _loop(i); } return { oldFileName: oldFileName, newFileName: newFileName, oldHeader: oldHeader, newHeader: newHeader, hunks: hunks }; } function formatPatch(diff) { if (Array.isArray(diff)) { return diff.map(formatPatch).join('\n'); } var ret = []; if (diff.oldFileName == diff.newFileName) { ret.push('Index: ' + diff.oldFileName); } ret.push('==================================================================='); ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader)); ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader)); for (var i = 0; i < diff.hunks.length; i++) { var hunk = diff.hunks[i]; // Unified Diff Format quirk: If the chunk size is 0, // the first number is one lower than one would expect. // https://www.artima.com/weblogs/viewpost.jsp?thread=164293 if (hunk.oldLines === 0) { hunk.oldStart -= 1; } if (hunk.newLines === 0) { hunk.newStart -= 1; } ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@'); ret.push.apply(ret, hunk.lines); } return ret.join('\n') + '\n'; } function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { return formatPatch(structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options)); } function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); } function arrayEqual(a, b) { if (a.length !== b.length) { return false; } return arrayStartsWith(a, b); } function arrayStartsWith(array, start) { if (start.length > array.length) { return false; } for (var i = 0; i < start.length; i++) { if (start[i] !== array[i]) { return false; } } return true; } function calcLineCount(hunk) { var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines), oldLines = _calcOldNewLineCount.oldLines, newLines = _calcOldNewLineCount.newLines; if (oldLines !== undefined) { hunk.oldLines = oldLines; } else { delete hunk.oldLines; } if (newLines !== undefined) { hunk.newLines = newLines; } else { delete hunk.newLines; } } function merge(mine, theirs, base) { mine = loadPatch(mine, base); theirs = loadPatch(theirs, base); var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning. // Leaving sanity checks on this to the API consumer that may know more about the // meaning in their own context. if (mine.index || theirs.index) { ret.index = mine.index || theirs.index; } if (mine.newFileName || theirs.newFileName) { if (!fileNameChanged(mine)) { // No header or no change in ours, use theirs (and ours if theirs does not exist) ret.oldFileName = theirs.oldFileName || mine.oldFileName; ret.newFileName = theirs.newFileName || mine.newFileName; ret.oldHeader = theirs.oldHeader || mine.oldHeader; ret.newHeader = theirs.newHeader || mine.newHeader; } else if (!fileNameChanged(theirs)) { // No header or no change in theirs, use ours ret.oldFileName = mine.oldFileName; ret.newFileName = mine.newFileName; ret.oldHeader = mine.oldHeader; ret.newHeader = mine.newHeader; } else { // Both changed... figure it out ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName); ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName); ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader); ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader); } } ret.hunks = []; var mineIndex = 0, theirsIndex = 0, mineOffset = 0, theirsOffset = 0; while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) { var mineCurrent = mine.hunks[mineIndex] || { oldStart: Infinity }, theirsCurrent = theirs.hunks[theirsIndex] || { oldStart: Infinity }; if (hunkBefore(mineCurrent, theirsCurrent)) { // This patch does not overlap with any of the others, yay. ret.hunks.push(cloneHunk(mineCurrent, mineOffset)); mineIndex++; theirsOffset += mineCurrent.newLines - mineCurrent.oldLines; } else if (hunkBefore(theirsCurrent, mineCurrent)) { // This patch does not overlap with any of the others, yay. ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset)); theirsIndex++; mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines; } else { // Overlap, merge as best we can var mergedHunk = { oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart), oldLines: 0, newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset), newLines: 0, lines: [] }; mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines); theirsIndex++; mineIndex++; ret.hunks.push(mergedHunk); } } return ret; } function loadPatch(param, base) { if (typeof param === 'string') { if (/^@@/m.test(param) || /^Index:/m.test(param)) { return parsePatch(param)[0]; } if (!base) { throw new Error('Must provide a base reference or pass in a patch'); } return structuredPatch(undefined, undefined, base, param); } return param; } function fileNameChanged(patch) { return patch.newFileName && patch.newFileName !== patch.oldFileName; } function selectField(index, mine, theirs) { if (mine === theirs) { return mine; } else { index.conflict = true; return { mine: mine, theirs: theirs }; } } function hunkBefore(test, check) { return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart; } function cloneHunk(hunk, offset) { return { oldStart: hunk.oldStart, oldLines: hunk.oldLines, newStart: hunk.newStart + offset, newLines: hunk.newLines, lines: hunk.lines }; } function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) { // This will generally result in a conflicted hunk, but there are cases where the context // is the only overlap where we can successfully merge the content here. var mine = { offset: mineOffset, lines: mineLines, index: 0 }, their = { offset: theirOffset, lines: theirLines, index: 0 }; // Handle any leading content insertLeading(hunk, mine, their); insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each. while (mine.index < mine.lines.length && their.index < their.lines.length) { var mineCurrent = mine.lines[mine.index], theirCurrent = their.lines[their.index]; if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) { // Both modified ... mutualChange(hunk, mine, their); } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') { var _hunk$lines; // Mine inserted (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine))); } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') { var _hunk$lines2; // Theirs inserted (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their))); } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') { // Mine removed or edited removal(hunk, mine, their); } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') { // Their removed or edited removal(hunk, their, mine, true); } else if (mineCurrent === theirCurrent) { // Context identity hunk.lines.push(mineCurrent); mine.index++; their.index++; } else { // Context mismatch conflict(hunk, collectChange(mine), collectChange(their)); } } // Now push anything that may be remaining insertTrailing(hunk, mine); insertTrailing(hunk, their); calcLineCount(hunk); } function mutualChange(hunk, mine, their) { var myChanges = collectChange(mine), theirChanges = collectChange(their); if (allRemoves(myChanges) && allRemoves(theirChanges)) { // Special case for remove changes that are supersets of one another if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) { var _hunk$lines3; (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges)); return; } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) { var _hunk$lines4; (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges)); return; } } else if (arrayEqual(myChanges, theirChanges)) { var _hunk$lines5; (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges)); return; } conflict(hunk, myChanges, theirChanges); } function removal(hunk, mine, their, swap) { var myChanges = collectChange(mine), theirChanges = collectContext(their, myChanges); if (theirChanges.merged) { var _hunk$lines6; (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged)); } else { conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges); } } function conflict(hunk, mine, their) { hunk.conflict = true; hunk.lines.push({ conflict: true, mine: mine, theirs: their }); } function insertLeading(hunk, insert, their) { while (insert.offset < their.offset && insert.index < insert.lines.length) { var line = insert.lines[insert.index++]; hunk.lines.push(line); insert.offset++; } } function insertTrailing(hunk, insert) { while (insert.index < insert.lines.length) { var line = insert.lines[insert.index++]; hunk.lines.push(line); } } function collectChange(state) { var ret = [], operation = state.lines[state.index][0]; while (state.index < state.lines.length) { var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change. if (operation === '-' && line[0] === '+') { operation = '+'; } if (operation === line[0]) { ret.push(line); state.index++; } else { break; } } return ret; } function collectContext(state, matchChanges) { var changes = [], merged = [], matchIndex = 0, contextChanges = false, conflicted = false; while (matchIndex < matchChanges.length && state.index < state.lines.length) { var change = state.lines[state.index], match = matchChanges[matchIndex]; // Once we've hit our add, then we are done if (match[0] === '+') { break; } contextChanges = contextChanges || change[0] !== ' '; merged.push(match); matchIndex++; // Consume any additions in the other block as a conflict to attempt // to pull in the remaining context after this if (change[0] === '+') { conflicted = true; while (change[0] === '+') { changes.push(change); change = state.lines[++state.index]; } } if (match.substr(1) === change.substr(1)) { changes.push(change); state.index++; } else { conflicted = true; } } if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) { conflicted = true; } if (conflicted) { return changes; } while (matchIndex < matchChanges.length) { merged.push(matchChanges[matchIndex++]); } return { merged: merged, changes: changes }; } function allRemoves(changes) { return changes.reduce(function (prev, change) { return prev && change[0] === '-'; }, true); } function skipRemoveSuperset(state, removeChanges, delta) { for (var i = 0; i < delta; i++) { var changeContent = removeChanges[removeChanges.length - delta + i].substr(1); if (state.lines[state.index + i] !== ' ' + changeContent) { return false; } } state.index += delta; return true; } function calcOldNewLineCount(lines) { var oldLines = 0; var newLines = 0; lines.forEach(function (line) { if (typeof line !== 'string') { var myCount = calcOldNewLineCount(line.mine); var theirCount = calcOldNewLineCount(line.theirs); if (oldLines !== undefined) { if (myCount.oldLines === theirCount.oldLines) { oldLines += myCount.oldLines; } else { oldLines = undefined; } } if (newLines !== undefined) { if (myCount.newLines === theirCount.newLines) { newLines += myCount.newLines; } else { newLines = undefined; } } } else { if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) { newLines++; } if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) { oldLines++; } } }); return { oldLines: oldLines, newLines: newLines }; } function reversePatch(structuredPatch) { if (Array.isArray(structuredPatch)) { return structuredPatch.map(reversePatch).reverse(); } return _objectSpread2(_objectSpread2({}, structuredPatch), {}, { oldFileName: structuredPatch.newFileName, oldHeader: structuredPatch.newHeader, newFileName: structuredPatch.oldFileName, newHeader: structuredPatch.oldHeader, hunks: structuredPatch.hunks.map(function (hunk) { return { oldLines: hunk.newLines, oldStart: hunk.newStart, newLines: hunk.oldLines, newStart: hunk.oldStart, linedelimiters: hunk.linedelimiters, lines: hunk.lines.map(function (l) { if (l.startsWith('-')) { return "+".concat(l.slice(1)); } if (l.startsWith('+')) { return "-".concat(l.slice(1)); } return l; }) }; }) }); } // See: http://code.google.com/p/google-diff-match-patch/wiki/API function convertChangesToDMP(changes) { var ret = [], change, operation; for (var i = 0; i < changes.length; i++) { change = changes[i]; if (change.added) { operation = 1; } else if (change.removed) { operation = -1; } else { operation = 0; } ret.push([operation, change.value]); } return ret; } function convertChangesToXML(changes) { var ret = []; for (var i = 0; i < changes.length; i++) { var change = changes[i]; if (change.added) { ret.push(''); } else if (change.removed) { ret.push(''); } ret.push(escapeHTML(change.value)); if (change.added) { ret.push(''); } else if (change.removed) { ret.push(''); } } return ret.join(''); } function escapeHTML(s) { var n = s; n = n.replace(/&/g, '&'); n = n.replace(//g, '>'); n = n.replace(/"/g, '"'); return n; } export { Diff, applyPatch, applyPatches, canonicalize, convertChangesToDMP, convertChangesToXML, createPatch, createTwoFilesPatch, diffArrays, diffChars, diffCss, diffJson, diffLines, diffSentences, diffTrimmedLines, diffWords, diffWordsWithSpace, formatPatch, merge, parsePatch, reversePatch, structuredPatch }; PK ~\žz7!!"diff/lib/util/distance-iterator.jsnu[/*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = _default; /*istanbul ignore end*/ // Iterator that traverses in the range of [min, max], stepping // by distance from a given start position. I.e. for [0, 4], with // start of 2, this will iterate 2, 3, 1, 4, 0. function /*istanbul ignore start*/ _default /*istanbul ignore end*/ (start, minLine, maxLine) { var wantForward = true, backwardExhausted = false, forwardExhausted = false, localOffset = 1; return function iterator() { if (wantForward && !forwardExhausted) { if (backwardExhausted) { localOffset++; } else { wantForward = false; } // Check if trying to fit beyond text length, and if not, check it fits // after offset location (or desired location on first iteration) if (start + localOffset <= maxLine) { return localOffset; } forwardExhausted = true; } if (!backwardExhausted) { if (!forwardExhausted) { wantForward = true; } // Check if trying to fit before text beginning, and if not, check it fits // before offset location if (minLine <= start - localOffset) { return -localOffset++; } backwardExhausted = true; return iterator(); } // We tried to fit hunk before text beginning and beyond text length, then // hunk can't fit on the text. Return undefined }; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy91dGlsL2Rpc3RhbmNlLWl0ZXJhdG9yLmpzIl0sIm5hbWVzIjpbInN0YXJ0IiwibWluTGluZSIsIm1heExpbmUiLCJ3YW50Rm9yd2FyZCIsImJhY2t3YXJkRXhoYXVzdGVkIiwiZm9yd2FyZEV4aGF1c3RlZCIsImxvY2FsT2Zmc2V0IiwiaXRlcmF0b3IiXSwibWFwcGluZ3MiOiI7Oz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RydWU7XG4gICAgfVxuXG4gICAgaWYgKCFiYWNrd2FyZEV4aGF1c3RlZCkge1xuICAgICAgaWYgKCFmb3J3YXJkRXhoYXVzdGVkKSB7XG4gICAgICAgIHdhbnRGb3J3YXJkID0gdHJ1ZTtcbiAgICAgIH1cblxuICAgICAgLy8gQ2hlY2sgaWYgdHJ5aW5nIHRvIGZpdCBiZWZvcmUgdGV4dCBiZWdpbm5pbmcsIGFuZCBpZiBub3QsIGNoZWNrIGl0IGZpdHNcbiAgICAgIC8vIGJlZm9yZSBvZmZzZXQgbG9jYXRpb25cbiAgICAgIGlmIChtaW5MaW5lIDw9IHN0YXJ0IC0gbG9jYWxPZmZzZXQpIHtcbiAgICAgICAgcmV0dXJuIC1sb2NhbE9mZnNldCsrO1xuICAgICAgfVxuXG4gICAgICBiYWNrd2FyZEV4aGF1c3RlZCA9IHRydWU7XG4gICAgICByZXR1cm4gaXRlcmF0b3IoKTtcbiAgICB9XG5cbiAgICAvLyBXZSB0cmllZCB0byBmaXQgaHVuayBiZWZvcmUgdGV4dCBiZWdpbm5pbmcgYW5kIGJleW9uZCB0ZXh0IGxlbmd0aCwgdGhlblxuICAgIC8vIGh1bmsgY2FuJ3QgZml0IG9uIHRoZSB0ZXh0LiBSZXR1cm4gdW5kZWZpbmVkXG4gIH07XG59XG4iXX0= PK ~\@diff/lib/util/array.jsnu[/*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.arrayEqual = arrayEqual; exports.arrayStartsWith = arrayStartsWith; /*istanbul ignore end*/ function arrayEqual(a, b) { if (a.length !== b.length) { return false; } return arrayStartsWith(a, b); } function arrayStartsWith(array, start) { if (start.length > array.length) { return false; } for (var i = 0; i < start.length; i++) { if (start[i] !== array[i]) { return false; } } return true; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy91dGlsL2FycmF5LmpzIl0sIm5hbWVzIjpbImFycmF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XJ0KSB7XG4gIGlmIChzdGFydC5sZW5ndGggPiBhcnJheS5sZW5ndGgpIHtcbiAgICByZXR1cm4gZmFsc2U7XG4gIH1cblxuICBmb3IgKGxldCBpID0gMDsgaSA8IHN0YXJ0Lmxlbmd0aDsgaSsrKSB7XG4gICAgaWYgKHN0YXJ0W2ldICE9PSBhcnJheVtpXSkge1xuICAgICAgcmV0dXJuIGZhbHNlO1xuICAgIH1cbiAgfVxuXG4gIHJldHVybiB0cnVlO1xufVxuIl19 PK ~\kbdiff/lib/util/params.jsnu[/*istanbul ignore start*/ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.generateOptions = generateOptions; /*istanbul ignore end*/ function generateOptions(options, defaults) { if (typeof options === 'function') { defaults.callback = options; } else if (options) { for (var name in options) { /* istanbul ignore else */ if (options.hasOwnProperty(name)) { defaults[name] = options[name]; } } } return defaults; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy91dGlsL3BhcmFtcy5qcyJdLCJuYW1lcyI6WyJnZW5lcmF0ZU9wdGlvbnMiLCJvcHRpb25zIiwiZGVmYXVsdHMiLCJjYWxsYmFjayIsIm5hbWUiLCJoYXNPd25Qcm9wZXJ0eSJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7O0FBQU8sU0FBU0EsZUFBVCxDQUF5QkMsT0FBekIsRUFBa0NDLFFBQWxDLEVBQTRDO0FBQ2pELE1BQUksT0FBT0QsT0FBUCxLQUFtQixVQUF2QixFQUFtQztBQUNqQ0MsSUFBQUEsUUFBUSxDQUFDQyxRQUFULEdBQW9CRixPQUFwQjtBQUNELEdBRkQsTUFFTyxJQUFJQSxPQUFKLEVBQWE7QUFDbEIsU0FBSyxJQUFJRyxJQUFULElBQWlCSCxPQUFqQixFQUEwQjtBQUN4QjtBQUNBLFVBQUlBLE9BQU8sQ0FBQ0ksY0FBUixDQUF1QkQsSUFBdkIsQ0FBSixFQUFrQztBQUNoQ0YsUUFBQUEsUUFBUSxDQUFDRSxJQUFELENBQVIsR0FBaUJILE9BQU8sQ0FBQ0csSUFBRCxDQUF4QjtBQUNEO0FBQ0Y7QUFDRjs7QUFDRCxTQUFPRixRQUFQO0FBQ0QiLCJzb3VyY2VzQ29udGVudCI6WyJleHBvcnQgZnVuY3Rpb24gZ2VuZXJhdGVPcHRpb25zKG9wdGlvbnMsIGRlZmF1bHRzKSB7XG4gIGlmICh0eXBlb2Ygb3B0aW9ucyA9PT0gJ2Z1bmN0aW9uJykge1xuICAgIGRlZmF1bHRzLmNhbGxiYWNrID0gb3B0aW9ucztcbiAgfSBlbHNlIGlmIChvcHRpb25zKSB7XG4gICAgZm9yIChsZXQgbmFtZSBpbiBvcHRpb25zKSB7XG4gICAgICAvKiBpc3RhbmJ1bCBpZ25vcmUgZWxzZSAqL1xuICAgICAgaWYgKG9wdGlvbnMuaGFzT3duUHJvcGVydHkobmFtZSkpIHtcbiAgICAgICAgZGVmYXVsdHNbbmFtZV0gPSBvcHRpb25zW25hbWVdO1xuICAgICAgfVxuICAgIH1cbiAgfVxuICByZXR1cm4gZGVmYXVsdHM7XG59XG4iXX0= PK ~\+   diff/LICENSEnu[BSD 3-Clause License Copyright (c) 2009-2015, Kevin Decker All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. PK ~\jGDGDdiff/dist/diff.min.jsnu[!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((e=e||self).Diff={})}(this,function(e){"use strict";function t(){}t.prototype={diff:function(s,a,e){var n,t=2=c&&f<=v+1)return d([{value:this.join(a),count:a.length}]);var m=-1/0,g=1/0;function w(){for(var e=Math.max(m,-p);e<=Math.min(g,p);e+=2){var n=void 0,t=h[e-1],r=h[e+1];t&&(h[e-1]=void 0);var i,o=!1;r&&(i=r.oldPos-e,o=r&&0<=i&&i=c&&f<=v+1)return d(function(e,n,t,r,i){var o,l=[];for(;n;)l.push(n),o=n.previousComponent,delete n.previousComponent,n=o;l.reverse();for(var s=0,a=l.length,u=0,d=0;se.length?t:e}),p.value=e.join(c)):p.value=e.join(t.slice(u,u+p.count)),u+=p.count,p.added||(d+=p.count))}var h=l[a-1];1=c&&(g=Math.min(g,e-1)),f<=v+1&&(m=Math.max(m,e+1))}else h[e]=void 0}p++}if(r)!function e(){setTimeout(function(){return il?r():void(w()||e())},0)}();else for(;p<=i&&Date.now()<=l;){var y=w();if(y)return y}},addToPath:function(e,n,t,r){var i=e.lastComponent;return i&&i.added===n&&i.removed===t?{oldPos:e.oldPos+r,lastComponent:{count:i.count+1,added:n,removed:t,previousComponent:i.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:n,removed:t,previousComponent:i}}},extractCommon:function(e,n,t,r){for(var i=n.length,o=t.length,l=e.oldPos,s=l-r,a=0;s+1e.length)&&(n=e.length);for(var t=0,r=new Array(n);t=c.length-2&&a.length<=f.context&&(i=/\n$/.test(u),o=/\n$/.test(d),l=0==a.length&&m.length>r.oldLines,!i&&l&&0e.length)return!1;for(var t=0;t"):i.removed&&t.push(""),t.push((n=i.value,n.replace(/&/g,"&").replace(//g,">").replace(/"/g,"""))),i.added?t.push(""):i.removed&&t.push("")}return t.join("")},e.createPatch=function(e,n,t,r,i,o){return b(e,e,n,t,r,i,o)},e.createTwoFilesPatch=b,e.diffArrays=function(e,n,t){return g.diff(e,n,t)},e.diffChars=function(e,n,t){return r.diff(e,n,t)},e.diffCss=function(e,n,t){return d.diff(e,n,t)},e.diffJson=function(e,n,t){return v.diff(e,n,t)},e.diffLines=L,e.diffSentences=function(e,n,t){return u.diff(e,n,t)},e.diffTrimmedLines=function(e,n,t){var r=i(t,{ignoreWhitespace:!0});return a.diff(e,n,r)},e.diffWords=function(e,n,t){return t=i(t,{ignoreWhitespace:!0}),s.diff(e,n,t)},e.diffWordsWithSpace=function(e,n,t){return s.diff(e,n,t)},e.formatPatch=S,e.merge=function(e,n,t){e=N(e,t),n=N(n,t);var r={};(e.index||n.index)&&(r.index=e.index||n.index),(e.newFileName||n.newFileName)&&(P(e)?P(n)?(r.oldFileName=j(r,e.oldFileName,n.oldFileName),r.newFileName=j(r,e.newFileName,n.newFileName),r.oldHeader=j(r,e.oldHeader,n.oldHeader),r.newHeader=j(r,e.newHeader,n.newHeader)):(r.oldFileName=e.oldFileName,r.newFileName=e.newFileName,r.oldHeader=e.oldHeader,r.newHeader=e.newHeader):(r.oldFileName=n.oldFileName||e.oldFileName,r.newFileName=n.newFileName||e.newFileName,r.oldHeader=n.oldHeader||e.oldHeader,r.newHeader=n.newHeader||e.newHeader)),r.hunks=[];for(var i=0,o=0,l=0,s=0;i 2 && arguments[2] !== undefined ? arguments[2] : {}; var callback = options.callback; if (typeof options === 'function') { callback = options; options = {}; } this.options = options; var self = this; function done(value) { if (callback) { setTimeout(function () { callback(undefined, value); }, 0); return true; } else { return value; } } // Allow subclasses to massage the input prior to running oldString = this.castInput(oldString); newString = this.castInput(newString); oldString = this.removeEmpty(this.tokenize(oldString)); newString = this.removeEmpty(this.tokenize(newString)); var newLen = newString.length, oldLen = oldString.length; var editLength = 1; var maxEditLength = newLen + oldLen; if (options.maxEditLength) { maxEditLength = Math.min(maxEditLength, options.maxEditLength); } var maxExecutionTime = (_options$timeout = options.timeout) !== null && _options$timeout !== void 0 ? _options$timeout : Infinity; var abortAfterTimestamp = Date.now() + maxExecutionTime; var bestPath = [{ oldPos: -1, lastComponent: undefined }]; // Seed editLength = 0, i.e. the content starts with the same values var newPos = this.extractCommon(bestPath[0], newString, oldString, 0); if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) { // Identity per the equality and tokenizer return done([{ value: this.join(newString), count: newString.length }]); } // Once we hit the right edge of the edit graph on some diagonal k, we can // definitely reach the end of the edit graph in no more than k edits, so // there's no point in considering any moves to diagonal k+1 any more (from // which we're guaranteed to need at least k+1 more edits). // Similarly, once we've reached the bottom of the edit graph, there's no // point considering moves to lower diagonals. // We record this fact by setting minDiagonalToConsider and // maxDiagonalToConsider to some finite value once we've hit the edge of // the edit graph. // This optimization is not faithful to the original algorithm presented in // Myers's paper, which instead pointlessly extends D-paths off the end of // the edit graph - see page 7 of Myers's paper which notes this point // explicitly and illustrates it with a diagram. This has major performance // implications for some common scenarios. For instance, to compute a diff // where the new text simply appends d characters on the end of the // original text of length n, the true Myers algorithm will take O(n+d^2) // time while this optimization needs only O(n+d) time. var minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity; // Main worker method. checks all permutations of a given edit length for acceptance. function execEditLength() { for (var diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) { var basePath = void 0; var removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1]; if (removePath) { // No one else is going to attempt to use this value, clear it bestPath[diagonalPath - 1] = undefined; } var canAdd = false; if (addPath) { // what newPos will be after we do an insertion: var addPathNewPos = addPath.oldPos - diagonalPath; canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen; } var canRemove = removePath && removePath.oldPos + 1 < oldLen; if (!canAdd && !canRemove) { // If this path is a terminal then prune bestPath[diagonalPath] = undefined; continue; } // Select the diagonal that we want to branch from. We select the prior // path whose position in the old string is the farthest from the origin // and does not pass the bounds of the diff graph // TODO: Remove the `+ 1` here to make behavior match Myers algorithm // and prefer to order removals before insertions. if (!canRemove || canAdd && removePath.oldPos + 1 < addPath.oldPos) { basePath = self.addToPath(addPath, true, undefined, 0); } else { basePath = self.addToPath(removePath, undefined, true, 1); } newPos = self.extractCommon(basePath, newString, oldString, diagonalPath); if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) { // If we have hit the end of both strings, then we are done return done(buildValues(self, basePath.lastComponent, newString, oldString, self.useLongestToken)); } else { bestPath[diagonalPath] = basePath; if (basePath.oldPos + 1 >= oldLen) { maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1); } if (newPos + 1 >= newLen) { minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1); } } } editLength++; } // Performs the length of edit iteration. Is a bit fugly as this has to support the // sync and async mode which is never fun. Loops over execEditLength until a value // is produced, or until the edit length exceeds options.maxEditLength (if given), // in which case it will return undefined. if (callback) { (function exec() { setTimeout(function () { if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) { return callback(); } if (!execEditLength()) { exec(); } }, 0); })(); } else { while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) { var ret = execEditLength(); if (ret) { return ret; } } } }, addToPath: function addToPath(path, added, removed, oldPosInc) { var last = path.lastComponent; if (last && last.added === added && last.removed === removed) { return { oldPos: path.oldPos + oldPosInc, lastComponent: { count: last.count + 1, added: added, removed: removed, previousComponent: last.previousComponent } }; } else { return { oldPos: path.oldPos + oldPosInc, lastComponent: { count: 1, added: added, removed: removed, previousComponent: last } }; } }, extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) { var newLen = newString.length, oldLen = oldString.length, oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0; while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { newPos++; oldPos++; commonCount++; } if (commonCount) { basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent }; } basePath.oldPos = oldPos; return newPos; }, equals: function equals(left, right) { if (this.options.comparator) { return this.options.comparator(left, right); } else { return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase(); } }, removeEmpty: function removeEmpty(array) { var ret = []; for (var i = 0; i < array.length; i++) { if (array[i]) { ret.push(array[i]); } } return ret; }, castInput: function castInput(value) { return value; }, tokenize: function tokenize(value) { return value.split(''); }, join: function join(chars) { return chars.join(''); } }; function buildValues(diff, lastComponent, newString, oldString, useLongestToken) { // First we convert our linked list of components in reverse order to an // array in the right order: var components = []; var nextComponent; while (lastComponent) { components.push(lastComponent); nextComponent = lastComponent.previousComponent; delete lastComponent.previousComponent; lastComponent = nextComponent; } components.reverse(); var componentPos = 0, componentLen = components.length, newPos = 0, oldPos = 0; for (; componentPos < componentLen; componentPos++) { var component = components[componentPos]; if (!component.removed) { if (!component.added && useLongestToken) { var value = newString.slice(newPos, newPos + component.count); value = value.map(function (value, i) { var oldValue = oldString[oldPos + i]; return oldValue.length > value.length ? oldValue : value; }); component.value = diff.join(value); } else { component.value = diff.join(newString.slice(newPos, newPos + component.count)); } newPos += component.count; // Common case if (!component.added) { oldPos += component.count; } } else { component.value = diff.join(oldString.slice(oldPos, oldPos + component.count)); oldPos += component.count; // Reverse add and remove so removes are output first to match common convention // The diffing algorithm is tied to add then remove output and this is the simplest // route to get the desired output with minimal overhead. if (componentPos && components[componentPos - 1].added) { var tmp = components[componentPos - 1]; components[componentPos - 1] = components[componentPos]; components[componentPos] = tmp; } } } // Special case handle for when one terminal is ignored (i.e. whitespace). // For this case we merge the terminal into the prior string and drop the change. // This is only available for string mode. var finalComponent = components[componentLen - 1]; if (componentLen > 1 && typeof finalComponent.value === 'string' && (finalComponent.added || finalComponent.removed) && diff.equals('', finalComponent.value)) { components[componentLen - 2].value += finalComponent.value; components.pop(); } return components; } var characterDiff = new Diff(); function diffChars(oldStr, newStr, options) { return characterDiff.diff(oldStr, newStr, options); } function generateOptions(options, defaults) { if (typeof options === 'function') { defaults.callback = options; } else if (options) { for (var name in options) { /* istanbul ignore else */ if (options.hasOwnProperty(name)) { defaults[name] = options[name]; } } } return defaults; } // // Ranges and exceptions: // Latin-1 Supplement, 0080–00FF // - U+00D7 × Multiplication sign // - U+00F7 ÷ Division sign // Latin Extended-A, 0100–017F // Latin Extended-B, 0180–024F // IPA Extensions, 0250–02AF // Spacing Modifier Letters, 02B0–02FF // - U+02C7 ˇ ˇ Caron // - U+02D8 ˘ ˘ Breve // - U+02D9 ˙ ˙ Dot Above // - U+02DA ˚ ˚ Ring Above // - U+02DB ˛ ˛ Ogonek // - U+02DC ˜ ˜ Small Tilde // - U+02DD ˝ ˝ Double Acute Accent // Latin Extended Additional, 1E00–1EFF var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/; var reWhitespace = /\S/; var wordDiff = new Diff(); wordDiff.equals = function (left, right) { if (this.options.ignoreCase) { left = left.toLowerCase(); right = right.toLowerCase(); } return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right); }; wordDiff.tokenize = function (value) { // All whitespace symbols except newline group into one token, each newline - in separate token var tokens = value.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set. for (var i = 0; i < tokens.length - 1; i++) { // If we have an empty string in the next field and we have only word chars before and after, merge if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) { tokens[i] += tokens[i + 2]; tokens.splice(i + 1, 2); i--; } } return tokens; }; function diffWords(oldStr, newStr, options) { options = generateOptions(options, { ignoreWhitespace: true }); return wordDiff.diff(oldStr, newStr, options); } function diffWordsWithSpace(oldStr, newStr, options) { return wordDiff.diff(oldStr, newStr, options); } var lineDiff = new Diff(); lineDiff.tokenize = function (value) { if (this.options.stripTrailingCr) { // remove one \r before \n to match GNU diff's --strip-trailing-cr behavior value = value.replace(/\r\n/g, '\n'); } var retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line if (!linesAndNewlines[linesAndNewlines.length - 1]) { linesAndNewlines.pop(); } // Merge the content and line separators into single tokens for (var i = 0; i < linesAndNewlines.length; i++) { var line = linesAndNewlines[i]; if (i % 2 && !this.options.newlineIsToken) { retLines[retLines.length - 1] += line; } else { if (this.options.ignoreWhitespace) { line = line.trim(); } retLines.push(line); } } return retLines; }; function diffLines(oldStr, newStr, callback) { return lineDiff.diff(oldStr, newStr, callback); } function diffTrimmedLines(oldStr, newStr, callback) { var options = generateOptions(callback, { ignoreWhitespace: true }); return lineDiff.diff(oldStr, newStr, options); } var sentenceDiff = new Diff(); sentenceDiff.tokenize = function (value) { return value.split(/(\S.+?[.!?])(?=\s+|$)/); }; function diffSentences(oldStr, newStr, callback) { return sentenceDiff.diff(oldStr, newStr, callback); } var cssDiff = new Diff(); cssDiff.tokenize = function (value) { return value.split(/([{}:;,]|\s+)/); }; function diffCss(oldStr, newStr, callback) { return cssDiff.diff(oldStr, newStr, callback); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function (obj) { return typeof obj; }; } else { _typeof = function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var objectPrototypeToString = Object.prototype.toString; var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: jsonDiff.useLongestToken = true; jsonDiff.tokenize = lineDiff.tokenize; jsonDiff.castInput = function (value) { var _this$options = this.options, undefinedReplacement = _this$options.undefinedReplacement, _this$options$stringi = _this$options.stringifyReplacer, stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) { return typeof v === 'undefined' ? undefinedReplacement : v; } : _this$options$stringi; return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' '); }; jsonDiff.equals = function (left, right) { return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1')); }; function diffJson(oldObj, newObj, options) { return jsonDiff.diff(oldObj, newObj, options); } // This function handles the presence of circular references by bailing out when encountering an // object that is already on the "stack" of items being processed. Accepts an optional replacer function canonicalize(obj, stack, replacementStack, replacer, key) { stack = stack || []; replacementStack = replacementStack || []; if (replacer) { obj = replacer(key, obj); } var i; for (i = 0; i < stack.length; i += 1) { if (stack[i] === obj) { return replacementStack[i]; } } var canonicalizedObj; if ('[object Array]' === objectPrototypeToString.call(obj)) { stack.push(obj); canonicalizedObj = new Array(obj.length); replacementStack.push(canonicalizedObj); for (i = 0; i < obj.length; i += 1) { canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key); } stack.pop(); replacementStack.pop(); return canonicalizedObj; } if (obj && obj.toJSON) { obj = obj.toJSON(); } if (_typeof(obj) === 'object' && obj !== null) { stack.push(obj); canonicalizedObj = {}; replacementStack.push(canonicalizedObj); var sortedKeys = [], _key; for (_key in obj) { /* istanbul ignore else */ if (obj.hasOwnProperty(_key)) { sortedKeys.push(_key); } } sortedKeys.sort(); for (i = 0; i < sortedKeys.length; i += 1) { _key = sortedKeys[i]; canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key); } stack.pop(); replacementStack.pop(); } else { canonicalizedObj = obj; } return canonicalizedObj; } var arrayDiff = new Diff(); arrayDiff.tokenize = function (value) { return value.slice(); }; arrayDiff.join = arrayDiff.removeEmpty = function (value) { return value; }; function diffArrays(oldArr, newArr, callback) { return arrayDiff.diff(oldArr, newArr, callback); } function parsePatch(uniDiff) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/), delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [], list = [], i = 0; function parseIndex() { var index = {}; list.push(index); // Parse diff metadata while (i < diffstr.length) { var line = diffstr[i]; // File header found, end parsing diff metadata if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) { break; } // Diff index var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line); if (header) { index.index = header[1]; } i++; } // Parse file headers if they are defined. Unified diff requires them, but // there's no technical issues to have an isolated hunk without file header parseFileHeader(index); parseFileHeader(index); // Parse hunks index.hunks = []; while (i < diffstr.length) { var _line = diffstr[i]; if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) { break; } else if (/^@@/.test(_line)) { index.hunks.push(parseHunk()); } else if (_line && options.strict) { // Ignore unexpected content unless in strict mode throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line)); } else { i++; } } } // Parses the --- and +++ headers, if none are found, no lines // are consumed. function parseFileHeader(index) { var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]); if (fileHeader) { var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new'; var data = fileHeader[2].split('\t', 2); var fileName = data[0].replace(/\\\\/g, '\\'); if (/^".*"$/.test(fileName)) { fileName = fileName.substr(1, fileName.length - 2); } index[keyPrefix + 'FileName'] = fileName; index[keyPrefix + 'Header'] = (data[1] || '').trim(); i++; } } // Parses a hunk // This assumes that we are at the start of a hunk. function parseHunk() { var chunkHeaderIndex = i, chunkHeaderLine = diffstr[i++], chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); var hunk = { oldStart: +chunkHeader[1], oldLines: typeof chunkHeader[2] === 'undefined' ? 1 : +chunkHeader[2], newStart: +chunkHeader[3], newLines: typeof chunkHeader[4] === 'undefined' ? 1 : +chunkHeader[4], lines: [], linedelimiters: [] }; // Unified Diff Format quirk: If the chunk size is 0, // the first number is one lower than one would expect. // https://www.artima.com/weblogs/viewpost.jsp?thread=164293 if (hunk.oldLines === 0) { hunk.oldStart += 1; } if (hunk.newLines === 0) { hunk.newStart += 1; } var addCount = 0, removeCount = 0; for (; i < diffstr.length; i++) { // Lines starting with '---' could be mistaken for the "remove line" operation // But they could be the header for the next file. Therefore prune such cases out. if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) { break; } var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0]; if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { hunk.lines.push(diffstr[i]); hunk.linedelimiters.push(delimiters[i] || '\n'); if (operation === '+') { addCount++; } else if (operation === '-') { removeCount++; } else if (operation === ' ') { addCount++; removeCount++; } } else { break; } } // Handle the empty block count case if (!addCount && hunk.newLines === 1) { hunk.newLines = 0; } if (!removeCount && hunk.oldLines === 1) { hunk.oldLines = 0; } // Perform optional sanity checking if (options.strict) { if (addCount !== hunk.newLines) { throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); } if (removeCount !== hunk.oldLines) { throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); } } return hunk; } while (i < diffstr.length) { parseIndex(); } return list; } // Iterator that traverses in the range of [min, max], stepping // by distance from a given start position. I.e. for [0, 4], with // start of 2, this will iterate 2, 3, 1, 4, 0. function distanceIterator (start, minLine, maxLine) { var wantForward = true, backwardExhausted = false, forwardExhausted = false, localOffset = 1; return function iterator() { if (wantForward && !forwardExhausted) { if (backwardExhausted) { localOffset++; } else { wantForward = false; } // Check if trying to fit beyond text length, and if not, check it fits // after offset location (or desired location on first iteration) if (start + localOffset <= maxLine) { return localOffset; } forwardExhausted = true; } if (!backwardExhausted) { if (!forwardExhausted) { wantForward = true; } // Check if trying to fit before text beginning, and if not, check it fits // before offset location if (minLine <= start - localOffset) { return -localOffset++; } backwardExhausted = true; return iterator(); } // We tried to fit hunk before text beginning and beyond text length, then // hunk can't fit on the text. Return undefined }; } function applyPatch(source, uniDiff) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; if (typeof uniDiff === 'string') { uniDiff = parsePatch(uniDiff); } if (Array.isArray(uniDiff)) { if (uniDiff.length > 1) { throw new Error('applyPatch only works with a single input.'); } uniDiff = uniDiff[0]; } // Apply the diff to the input var lines = source.split(/\r\n|[\n\v\f\r\x85]/), delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [], hunks = uniDiff.hunks, compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) { return line === patchContent; }, errorCount = 0, fuzzFactor = options.fuzzFactor || 0, minLine = 0, offset = 0, removeEOFNL, addEOFNL; /** * Checks if the hunk exactly fits on the provided location */ function hunkFits(hunk, toPos) { for (var j = 0; j < hunk.lines.length; j++) { var line = hunk.lines[j], operation = line.length > 0 ? line[0] : ' ', content = line.length > 0 ? line.substr(1) : line; if (operation === ' ' || operation === '-') { // Context sanity check if (!compareLine(toPos + 1, lines[toPos], operation, content)) { errorCount++; if (errorCount > fuzzFactor) { return false; } } toPos++; } } return true; } // Search best fit offsets for each hunk based on the previous ones for (var i = 0; i < hunks.length; i++) { var hunk = hunks[i], maxLine = lines.length - hunk.oldLines, localOffset = 0, toPos = offset + hunk.oldStart - 1; var iterator = distanceIterator(toPos, minLine, maxLine); for (; localOffset !== undefined; localOffset = iterator()) { if (hunkFits(hunk, toPos + localOffset)) { hunk.offset = offset += localOffset; break; } } if (localOffset === undefined) { return false; } // Set lower text limit to end of the current hunk, so next ones don't try // to fit over already patched text minLine = hunk.offset + hunk.oldStart + hunk.oldLines; } // Apply patch hunks var diffOffset = 0; for (var _i = 0; _i < hunks.length; _i++) { var _hunk = hunks[_i], _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1; diffOffset += _hunk.newLines - _hunk.oldLines; for (var j = 0; j < _hunk.lines.length; j++) { var line = _hunk.lines[j], operation = line.length > 0 ? line[0] : ' ', content = line.length > 0 ? line.substr(1) : line, delimiter = _hunk.linedelimiters && _hunk.linedelimiters[j] || '\n'; if (operation === ' ') { _toPos++; } else if (operation === '-') { lines.splice(_toPos, 1); delimiters.splice(_toPos, 1); /* istanbul ignore else */ } else if (operation === '+') { lines.splice(_toPos, 0, content); delimiters.splice(_toPos, 0, delimiter); _toPos++; } else if (operation === '\\') { var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null; if (previousOperation === '+') { removeEOFNL = true; } else if (previousOperation === '-') { addEOFNL = true; } } } } // Handle EOFNL insertion/removal if (removeEOFNL) { while (!lines[lines.length - 1]) { lines.pop(); delimiters.pop(); } } else if (addEOFNL) { lines.push(''); delimiters.push('\n'); } for (var _k = 0; _k < lines.length - 1; _k++) { lines[_k] = lines[_k] + delimiters[_k]; } return lines.join(''); } // Wrapper that supports multiple file patches via callbacks. function applyPatches(uniDiff, options) { if (typeof uniDiff === 'string') { uniDiff = parsePatch(uniDiff); } var currentIndex = 0; function processIndex() { var index = uniDiff[currentIndex++]; if (!index) { return options.complete(); } options.loadFile(index, function (err, data) { if (err) { return options.complete(err); } var updatedContent = applyPatch(data, index, options); options.patched(index, updatedContent, function (err) { if (err) { return options.complete(err); } processIndex(); }); }); } processIndex(); } function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { if (!options) { options = {}; } if (typeof options.context === 'undefined') { options.context = 4; } var diff = diffLines(oldStr, newStr, options); if (!diff) { return; } diff.push({ value: '', lines: [] }); // Append an empty value to make cleanup easier function contextLines(lines) { return lines.map(function (entry) { return ' ' + entry; }); } var hunks = []; var oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; var _loop = function _loop(i) { var current = diff[i], lines = current.lines || current.value.replace(/\n$/, '').split('\n'); current.lines = lines; if (current.added || current.removed) { var _curRange; // If we have previous context, start with that if (!oldRangeStart) { var prev = diff[i - 1]; oldRangeStart = oldLine; newRangeStart = newLine; if (prev) { curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : []; oldRangeStart -= curRange.length; newRangeStart -= curRange.length; } } // Output our changes (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) { return (current.added ? '+' : '-') + entry; }))); // Track the updated file position if (current.added) { newLine += lines.length; } else { oldLine += lines.length; } } else { // Identical context lines. Track line changes if (oldRangeStart) { // Close out any changes that have been output (or join overlapping) if (lines.length <= options.context * 2 && i < diff.length - 2) { var _curRange2; // Overlapping (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines))); } else { var _curRange3; // end the range and output var contextSize = Math.min(lines.length, options.context); (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize)))); var hunk = { oldStart: oldRangeStart, oldLines: oldLine - oldRangeStart + contextSize, newStart: newRangeStart, newLines: newLine - newRangeStart + contextSize, lines: curRange }; if (i >= diff.length - 2 && lines.length <= options.context) { // EOF is inside this hunk var oldEOFNewline = /\n$/.test(oldStr); var newEOFNewline = /\n$/.test(newStr); var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines; if (!oldEOFNewline && noNlBeforeAdds && oldStr.length > 0) { // special case: old has no eol and no trailing context; no-nl can end up before adds // however, if the old file is empty, do not output the no-nl line curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file'); } if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) { curRange.push('\\ No newline at end of file'); } } hunks.push(hunk); oldRangeStart = 0; newRangeStart = 0; curRange = []; } } oldLine += lines.length; newLine += lines.length; } }; for (var i = 0; i < diff.length; i++) { _loop(i); } return { oldFileName: oldFileName, newFileName: newFileName, oldHeader: oldHeader, newHeader: newHeader, hunks: hunks }; } function formatPatch(diff) { if (Array.isArray(diff)) { return diff.map(formatPatch).join('\n'); } var ret = []; if (diff.oldFileName == diff.newFileName) { ret.push('Index: ' + diff.oldFileName); } ret.push('==================================================================='); ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader)); ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader)); for (var i = 0; i < diff.hunks.length; i++) { var hunk = diff.hunks[i]; // Unified Diff Format quirk: If the chunk size is 0, // the first number is one lower than one would expect. // https://www.artima.com/weblogs/viewpost.jsp?thread=164293 if (hunk.oldLines === 0) { hunk.oldStart -= 1; } if (hunk.newLines === 0) { hunk.newStart -= 1; } ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@'); ret.push.apply(ret, hunk.lines); } return ret.join('\n') + '\n'; } function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { return formatPatch(structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options)); } function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); } function arrayEqual(a, b) { if (a.length !== b.length) { return false; } return arrayStartsWith(a, b); } function arrayStartsWith(array, start) { if (start.length > array.length) { return false; } for (var i = 0; i < start.length; i++) { if (start[i] !== array[i]) { return false; } } return true; } function calcLineCount(hunk) { var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines), oldLines = _calcOldNewLineCount.oldLines, newLines = _calcOldNewLineCount.newLines; if (oldLines !== undefined) { hunk.oldLines = oldLines; } else { delete hunk.oldLines; } if (newLines !== undefined) { hunk.newLines = newLines; } else { delete hunk.newLines; } } function merge(mine, theirs, base) { mine = loadPatch(mine, base); theirs = loadPatch(theirs, base); var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning. // Leaving sanity checks on this to the API consumer that may know more about the // meaning in their own context. if (mine.index || theirs.index) { ret.index = mine.index || theirs.index; } if (mine.newFileName || theirs.newFileName) { if (!fileNameChanged(mine)) { // No header or no change in ours, use theirs (and ours if theirs does not exist) ret.oldFileName = theirs.oldFileName || mine.oldFileName; ret.newFileName = theirs.newFileName || mine.newFileName; ret.oldHeader = theirs.oldHeader || mine.oldHeader; ret.newHeader = theirs.newHeader || mine.newHeader; } else if (!fileNameChanged(theirs)) { // No header or no change in theirs, use ours ret.oldFileName = mine.oldFileName; ret.newFileName = mine.newFileName; ret.oldHeader = mine.oldHeader; ret.newHeader = mine.newHeader; } else { // Both changed... figure it out ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName); ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName); ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader); ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader); } } ret.hunks = []; var mineIndex = 0, theirsIndex = 0, mineOffset = 0, theirsOffset = 0; while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) { var mineCurrent = mine.hunks[mineIndex] || { oldStart: Infinity }, theirsCurrent = theirs.hunks[theirsIndex] || { oldStart: Infinity }; if (hunkBefore(mineCurrent, theirsCurrent)) { // This patch does not overlap with any of the others, yay. ret.hunks.push(cloneHunk(mineCurrent, mineOffset)); mineIndex++; theirsOffset += mineCurrent.newLines - mineCurrent.oldLines; } else if (hunkBefore(theirsCurrent, mineCurrent)) { // This patch does not overlap with any of the others, yay. ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset)); theirsIndex++; mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines; } else { // Overlap, merge as best we can var mergedHunk = { oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart), oldLines: 0, newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset), newLines: 0, lines: [] }; mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines); theirsIndex++; mineIndex++; ret.hunks.push(mergedHunk); } } return ret; } function loadPatch(param, base) { if (typeof param === 'string') { if (/^@@/m.test(param) || /^Index:/m.test(param)) { return parsePatch(param)[0]; } if (!base) { throw new Error('Must provide a base reference or pass in a patch'); } return structuredPatch(undefined, undefined, base, param); } return param; } function fileNameChanged(patch) { return patch.newFileName && patch.newFileName !== patch.oldFileName; } function selectField(index, mine, theirs) { if (mine === theirs) { return mine; } else { index.conflict = true; return { mine: mine, theirs: theirs }; } } function hunkBefore(test, check) { return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart; } function cloneHunk(hunk, offset) { return { oldStart: hunk.oldStart, oldLines: hunk.oldLines, newStart: hunk.newStart + offset, newLines: hunk.newLines, lines: hunk.lines }; } function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) { // This will generally result in a conflicted hunk, but there are cases where the context // is the only overlap where we can successfully merge the content here. var mine = { offset: mineOffset, lines: mineLines, index: 0 }, their = { offset: theirOffset, lines: theirLines, index: 0 }; // Handle any leading content insertLeading(hunk, mine, their); insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each. while (mine.index < mine.lines.length && their.index < their.lines.length) { var mineCurrent = mine.lines[mine.index], theirCurrent = their.lines[their.index]; if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) { // Both modified ... mutualChange(hunk, mine, their); } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') { var _hunk$lines; // Mine inserted (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine))); } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') { var _hunk$lines2; // Theirs inserted (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their))); } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') { // Mine removed or edited removal(hunk, mine, their); } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') { // Their removed or edited removal(hunk, their, mine, true); } else if (mineCurrent === theirCurrent) { // Context identity hunk.lines.push(mineCurrent); mine.index++; their.index++; } else { // Context mismatch conflict(hunk, collectChange(mine), collectChange(their)); } } // Now push anything that may be remaining insertTrailing(hunk, mine); insertTrailing(hunk, their); calcLineCount(hunk); } function mutualChange(hunk, mine, their) { var myChanges = collectChange(mine), theirChanges = collectChange(their); if (allRemoves(myChanges) && allRemoves(theirChanges)) { // Special case for remove changes that are supersets of one another if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) { var _hunk$lines3; (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges)); return; } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) { var _hunk$lines4; (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges)); return; } } else if (arrayEqual(myChanges, theirChanges)) { var _hunk$lines5; (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges)); return; } conflict(hunk, myChanges, theirChanges); } function removal(hunk, mine, their, swap) { var myChanges = collectChange(mine), theirChanges = collectContext(their, myChanges); if (theirChanges.merged) { var _hunk$lines6; (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged)); } else { conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges); } } function conflict(hunk, mine, their) { hunk.conflict = true; hunk.lines.push({ conflict: true, mine: mine, theirs: their }); } function insertLeading(hunk, insert, their) { while (insert.offset < their.offset && insert.index < insert.lines.length) { var line = insert.lines[insert.index++]; hunk.lines.push(line); insert.offset++; } } function insertTrailing(hunk, insert) { while (insert.index < insert.lines.length) { var line = insert.lines[insert.index++]; hunk.lines.push(line); } } function collectChange(state) { var ret = [], operation = state.lines[state.index][0]; while (state.index < state.lines.length) { var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change. if (operation === '-' && line[0] === '+') { operation = '+'; } if (operation === line[0]) { ret.push(line); state.index++; } else { break; } } return ret; } function collectContext(state, matchChanges) { var changes = [], merged = [], matchIndex = 0, contextChanges = false, conflicted = false; while (matchIndex < matchChanges.length && state.index < state.lines.length) { var change = state.lines[state.index], match = matchChanges[matchIndex]; // Once we've hit our add, then we are done if (match[0] === '+') { break; } contextChanges = contextChanges || change[0] !== ' '; merged.push(match); matchIndex++; // Consume any additions in the other block as a conflict to attempt // to pull in the remaining context after this if (change[0] === '+') { conflicted = true; while (change[0] === '+') { changes.push(change); change = state.lines[++state.index]; } } if (match.substr(1) === change.substr(1)) { changes.push(change); state.index++; } else { conflicted = true; } } if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) { conflicted = true; } if (conflicted) { return changes; } while (matchIndex < matchChanges.length) { merged.push(matchChanges[matchIndex++]); } return { merged: merged, changes: changes }; } function allRemoves(changes) { return changes.reduce(function (prev, change) { return prev && change[0] === '-'; }, true); } function skipRemoveSuperset(state, removeChanges, delta) { for (var i = 0; i < delta; i++) { var changeContent = removeChanges[removeChanges.length - delta + i].substr(1); if (state.lines[state.index + i] !== ' ' + changeContent) { return false; } } state.index += delta; return true; } function calcOldNewLineCount(lines) { var oldLines = 0; var newLines = 0; lines.forEach(function (line) { if (typeof line !== 'string') { var myCount = calcOldNewLineCount(line.mine); var theirCount = calcOldNewLineCount(line.theirs); if (oldLines !== undefined) { if (myCount.oldLines === theirCount.oldLines) { oldLines += myCount.oldLines; } else { oldLines = undefined; } } if (newLines !== undefined) { if (myCount.newLines === theirCount.newLines) { newLines += myCount.newLines; } else { newLines = undefined; } } } else { if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) { newLines++; } if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) { oldLines++; } } }); return { oldLines: oldLines, newLines: newLines }; } function reversePatch(structuredPatch) { if (Array.isArray(structuredPatch)) { return structuredPatch.map(reversePatch).reverse(); } return _objectSpread2(_objectSpread2({}, structuredPatch), {}, { oldFileName: structuredPatch.newFileName, oldHeader: structuredPatch.newHeader, newFileName: structuredPatch.oldFileName, newHeader: structuredPatch.oldHeader, hunks: structuredPatch.hunks.map(function (hunk) { return { oldLines: hunk.newLines, oldStart: hunk.newStart, newLines: hunk.oldLines, newStart: hunk.oldStart, linedelimiters: hunk.linedelimiters, lines: hunk.lines.map(function (l) { if (l.startsWith('-')) { return "+".concat(l.slice(1)); } if (l.startsWith('+')) { return "-".concat(l.slice(1)); } return l; }) }; }) }); } // See: http://code.google.com/p/google-diff-match-patch/wiki/API function convertChangesToDMP(changes) { var ret = [], change, operation; for (var i = 0; i < changes.length; i++) { change = changes[i]; if (change.added) { operation = 1; } else if (change.removed) { operation = -1; } else { operation = 0; } ret.push([operation, change.value]); } return ret; } function convertChangesToXML(changes) { var ret = []; for (var i = 0; i < changes.length; i++) { var change = changes[i]; if (change.added) { ret.push(''); } else if (change.removed) { ret.push(''); } ret.push(escapeHTML(change.value)); if (change.added) { ret.push(''); } else if (change.removed) { ret.push(''); } } return ret.join(''); } function escapeHTML(s) { var n = s; n = n.replace(/&/g, '&'); n = n.replace(//g, '>'); n = n.replace(/"/g, '"'); return n; } exports.Diff = Diff; exports.applyPatch = applyPatch; exports.applyPatches = applyPatches; exports.canonicalize = canonicalize; exports.convertChangesToDMP = convertChangesToDMP; exports.convertChangesToXML = convertChangesToXML; exports.createPatch = createPatch; exports.createTwoFilesPatch = createTwoFilesPatch; exports.diffArrays = diffArrays; exports.diffChars = diffChars; exports.diffCss = diffCss; exports.diffJson = diffJson; exports.diffLines = diffLines; exports.diffSentences = diffSentences; exports.diffTrimmedLines = diffTrimmedLines; exports.diffWords = diffWords; exports.diffWordsWithSpace = diffWordsWithSpace; exports.formatPatch = formatPatch; exports.merge = merge; exports.parsePatch = parsePatch; exports.reversePatch = reversePatch; exports.structuredPatch = structuredPatch; Object.defineProperty(exports, '__esModule', { value: true }); }))); PK ~\"bCCdiff/runtime.jsnu[require('@babel/register')({ ignore: ['lib', 'node_modules'] }); PK ~\IIdiff/release-notes.mdnu[# Release Notes ## v5.2.0 [Commits](https://github.com/kpdecker/jsdiff/compare/v5.1.0...master) - [#411](https://github.com/kpdecker/jsdiff/pull/411) Big performance improvement. Previously an O(n) array-copying operation inside the innermost loop of jsdiff's base diffing code increased the overall worst-case time complexity of computing a diff from O(n²) to O(n³). This is now fixed, bringing the worst-case time complexity down to what it theoretically should be for a Myers diff implementation. - [#448](https://github.com/kpdecker/jsdiff/pull/411) Performance improvement. Diagonals whose furthest-reaching D-path would go off the edge of the edit graph are now skipped, rather than being pointlessly considered as called for by the original Myers diff algorithm. This dramatically speeds up computing diffs where the new text just appends or truncates content at the end of the old text. - [#351](https://github.com/kpdecker/jsdiff/issues/351) Importing from the lib folder - e.g. `require("diff/lib/diff/word.js")` - will work again now. This had been broken for users on the latest version of Node since Node 17.5.0, which changed how Node interprets the `exports` property in jsdiff's `package.json` file. - [#344](https://github.com/kpdecker/jsdiff/issues/344) `diffLines`, `createTwoFilesPatch`, and other patch-creation methods now take an optional `stripTrailingCr: true` option which causes Windows-style `\r\n` line endings to be replaced with Unix-style `\n` line endings before calculating the diff, just like GNU `diff`'s `--strip-trailing-cr` flag. - [#451](https://github.com/kpdecker/jsdiff/pull/451) Added `diff.formatPatch`. - [#450](https://github.com/kpdecker/jsdiff/pull/450) Added `diff.reversePatch`. - [#478](https://github.com/kpdecker/jsdiff/pull/478) Added `timeout` option. ## v5.1.0 - [#365](https://github.com/kpdecker/jsdiff/issues/365) Allow early termination to limit execution time with degenerate cases [Commits](https://github.com/kpdecker/jsdiff/compare/v5.0.0...v5.1.0) ## v5.0.0 - Breaking: UMD export renamed from `JsDiff` to `Diff`. - Breaking: Newlines separated into separate tokens for word diff. - Breaking: Unified diffs now match ["quirks"](https://www.artima.com/weblogs/viewpost.jsp?thread=164293) [Commits](https://github.com/kpdecker/jsdiff/compare/v4.0.1...v5.0.0) ## v4.0.1 - January 6th, 2019 - Fix main reference path - b826104 [Commits](https://github.com/kpdecker/jsdiff/compare/v4.0.0...v4.0.1) ## v4.0.0 - January 5th, 2019 - [#94](https://github.com/kpdecker/jsdiff/issues/94) - Missing "No newline at end of file" when comparing two texts that do not end in newlines ([@federicotdn](https://api.github.com/users/federicotdn)) - [#227](https://github.com/kpdecker/jsdiff/issues/227) - Licence - [#199](https://github.com/kpdecker/jsdiff/issues/199) - Import statement for jsdiff - [#159](https://github.com/kpdecker/jsdiff/issues/159) - applyPatch affecting wrong line number with with new lines - [#8](https://github.com/kpdecker/jsdiff/issues/8) - A new state "replace" - Drop ie9 from karma targets - 79c31bd - Upgrade deps. Convert from webpack to rollup - 2c1a29c - Make ()[]"' as word boundaries between each other - f27b899 - jsdiff: Replaced phantomJS by chrome - ec3114e - Add yarn.lock to .npmignore - 29466d8 Compatibility notes: - Bower and Component packages no longer supported [Commits](https://github.com/kpdecker/jsdiff/compare/v3.5.0...v4.0.0) ## v3.5.0 - March 4th, 2018 - Omit redundant slice in join method of diffArrays - 1023590 - Support patches with empty lines - fb0f208 - Accept a custom JSON replacer function for JSON diffing - 69c7f0a - Optimize parch header parser - 2aec429 - Fix typos - e89c832 [Commits](https://github.com/kpdecker/jsdiff/compare/v3.4.0...v3.5.0) ## v3.4.0 - October 7th, 2017 - [#183](https://github.com/kpdecker/jsdiff/issues/183) - Feature request: ability to specify a custom equality checker for `diffArrays` - [#173](https://github.com/kpdecker/jsdiff/issues/173) - Bug: diffArrays gives wrong result on array of booleans - [#158](https://github.com/kpdecker/jsdiff/issues/158) - diffArrays will not compare the empty string in array? - comparator for custom equality checks - 30e141e - count oldLines and newLines when there are conflicts - 53bf384 - Fix: diffArrays can compare falsey items - 9e24284 - Docs: Replace grunt with npm test - 00e2f94 [Commits](https://github.com/kpdecker/jsdiff/compare/v3.3.1...v3.4.0) ## v3.3.1 - September 3rd, 2017 - [#141](https://github.com/kpdecker/jsdiff/issues/141) - Cannot apply patch because my file delimiter is "/r/n" instead of "/n" - [#192](https://github.com/kpdecker/jsdiff/pull/192) - Fix: Bad merge when adding new files (#189) - correct spelling mistake - 21fa478 [Commits](https://github.com/kpdecker/jsdiff/compare/v3.3.0...v3.3.1) ## v3.3.0 - July 5th, 2017 - [#114](https://github.com/kpdecker/jsdiff/issues/114) - /patch/merge not exported - Gracefully accept invalid newStart in hunks, same as patch(1) does. - d8a3635 - Use regex rather than starts/ends with for parsePatch - 6cab62c - Add browser flag - e64f674 - refactor: simplified code a bit more - 8f8e0f2 - refactor: simplified code a bit - b094a6f - fix: some corrections re ignoreCase option - 3c78fd0 - ignoreCase option - 3cbfbb5 - Sanitize filename while parsing patches - 2fe8129 - Added better installation methods - aced50b - Simple export of functionality - 8690f31 [Commits](https://github.com/kpdecker/jsdiff/compare/v3.2.0...v3.3.0) ## v3.2.0 - December 26th, 2016 - [#156](https://github.com/kpdecker/jsdiff/pull/156) - Add `undefinedReplacement` option to `diffJson` ([@ewnd9](https://api.github.com/users/ewnd9)) - [#154](https://github.com/kpdecker/jsdiff/pull/154) - Add `examples` and `images` to `.npmignore`. ([@wtgtybhertgeghgtwtg](https://api.github.com/users/wtgtybhertgeghgtwtg)) - [#153](https://github.com/kpdecker/jsdiff/pull/153) - feat(structuredPatch): Pass options to diffLines ([@Kiougar](https://api.github.com/users/Kiougar)) [Commits](https://github.com/kpdecker/jsdiff/compare/v3.1.0...v3.2.0) ## v3.1.0 - November 27th, 2016 - [#146](https://github.com/kpdecker/jsdiff/pull/146) - JsDiff.diffArrays to compare arrays ([@wvanderdeijl](https://api.github.com/users/wvanderdeijl)) - [#144](https://github.com/kpdecker/jsdiff/pull/144) - Split file using all possible line delimiter instead of hard-coded "/n" and join lines back using the original delimiters ([@soulbeing](https://api.github.com/users/soulbeing)) [Commits](https://github.com/kpdecker/jsdiff/compare/v3.0.1...v3.1.0) ## v3.0.1 - October 9th, 2016 - [#139](https://github.com/kpdecker/jsdiff/pull/139) - Make README.md look nicer in npmjs.com ([@takenspc](https://api.github.com/users/takenspc)) - [#135](https://github.com/kpdecker/jsdiff/issues/135) - parsePatch combines patches from multiple files into a single IUniDiff when there is no "Index" line ([@ramya-rao-a](https://api.github.com/users/ramya-rao-a)) - [#124](https://github.com/kpdecker/jsdiff/issues/124) - IE7/IE8 failure since 2.0.0 ([@boneskull](https://api.github.com/users/boneskull)) [Commits](https://github.com/kpdecker/jsdiff/compare/v3.0.0...v3.0.1) ## v3.0.0 - August 23rd, 2016 - [#130](https://github.com/kpdecker/jsdiff/pull/130) - Add callback argument to applyPatches `patched` option ([@piranna](https://api.github.com/users/piranna)) - [#120](https://github.com/kpdecker/jsdiff/pull/120) - Correctly handle file names containing spaces ([@adius](https://api.github.com/users/adius)) - [#119](https://github.com/kpdecker/jsdiff/pull/119) - Do single reflow ([@wifiextender](https://api.github.com/users/wifiextender)) - [#117](https://github.com/kpdecker/jsdiff/pull/117) - Make more usable with long strings. ([@abnbgist](https://api.github.com/users/abnbgist)) Compatibility notes: - applyPatches patch callback now is async and requires the callback be called to continue operation [Commits](https://github.com/kpdecker/jsdiff/compare/v2.2.3...v3.0.0) ## v2.2.3 - May 31st, 2016 - [#118](https://github.com/kpdecker/jsdiff/pull/118) - Add a fix for applying 0-length destination patches ([@chaaz](https://api.github.com/users/chaaz)) - [#115](https://github.com/kpdecker/jsdiff/pull/115) - Fixed grammar in README ([@krizalys](https://api.github.com/users/krizalys)) - [#113](https://github.com/kpdecker/jsdiff/pull/113) - fix typo ([@vmazare](https://api.github.com/users/vmazare)) [Commits](https://github.com/kpdecker/jsdiff/compare/v2.2.2...v2.2.3) ## v2.2.2 - March 13th, 2016 - [#102](https://github.com/kpdecker/jsdiff/issues/102) - diffJson with dates, returns empty curly braces ([@dr-dimitru](https://api.github.com/users/dr-dimitru)) - [#97](https://github.com/kpdecker/jsdiff/issues/97) - Whitespaces & diffWords ([@faiwer](https://api.github.com/users/faiwer)) - [#92](https://github.com/kpdecker/jsdiff/pull/92) - Fixes typo in the readme ([@bg451](https://api.github.com/users/bg451)) [Commits](https://github.com/kpdecker/jsdiff/compare/v2.2.1...v2.2.2) ## v2.2.1 - November 12th, 2015 - [#89](https://github.com/kpdecker/jsdiff/pull/89) - add in display selector to readme ([@FranDias](https://api.github.com/users/FranDias)) - [#88](https://github.com/kpdecker/jsdiff/pull/88) - Split diffs based on file headers instead of 'Index:' metadata ([@piranna](https://api.github.com/users/piranna)) [Commits](https://github.com/kpdecker/jsdiff/compare/v2.2.0...v2.2.1) ## v2.2.0 - October 29th, 2015 - [#80](https://github.com/kpdecker/jsdiff/pull/80) - Fix a typo: applyPath -> applyPatch ([@fluxxu](https://api.github.com/users/fluxxu)) - [#83](https://github.com/kpdecker/jsdiff/pull/83) - Add basic fuzzy matching to applyPatch ([@piranna](https://github.com/piranna)) [Commits](https://github.com/kpdecker/jsdiff/compare/v2.2.0...v2.2.0) ## v2.2.0 - October 29th, 2015 - [#80](https://github.com/kpdecker/jsdiff/pull/80) - Fix a typo: applyPath -> applyPatch ([@fluxxu](https://api.github.com/users/fluxxu)) - [#83](https://github.com/kpdecker/jsdiff/pull/83) - Add basic fuzzy matching to applyPatch ([@piranna](https://github.com/piranna)) [Commits](https://github.com/kpdecker/jsdiff/compare/v2.1.3...v2.2.0) ## v2.1.3 - September 30th, 2015 - [#78](https://github.com/kpdecker/jsdiff/pull/78) - fix: error throwing when apply patch to empty string ([@21paradox](https://api.github.com/users/21paradox)) [Commits](https://github.com/kpdecker/jsdiff/compare/v2.1.2...v2.1.3) ## v2.1.2 - September 23rd, 2015 - [#76](https://github.com/kpdecker/jsdiff/issues/76) - diff headers give error ([@piranna](https://api.github.com/users/piranna)) [Commits](https://github.com/kpdecker/jsdiff/compare/v2.1.1...v2.1.2) ## v2.1.1 - September 9th, 2015 - [#73](https://github.com/kpdecker/jsdiff/issues/73) - Is applyPatches() exposed in the API? ([@davidparsson](https://api.github.com/users/davidparsson)) [Commits](https://github.com/kpdecker/jsdiff/compare/v2.1.0...v2.1.1) ## v2.1.0 - August 27th, 2015 - [#72](https://github.com/kpdecker/jsdiff/issues/72) - Consider using options object API for flag permutations ([@kpdecker](https://api.github.com/users/kpdecker)) - [#70](https://github.com/kpdecker/jsdiff/issues/70) - diffWords treats \n at the end as significant whitespace ([@nesQuick](https://api.github.com/users/nesQuick)) - [#69](https://github.com/kpdecker/jsdiff/issues/69) - Missing count ([@wfalkwallace](https://api.github.com/users/wfalkwallace)) - [#68](https://github.com/kpdecker/jsdiff/issues/68) - diffLines seems broken ([@wfalkwallace](https://api.github.com/users/wfalkwallace)) - [#60](https://github.com/kpdecker/jsdiff/issues/60) - Support multiple diff hunks ([@piranna](https://api.github.com/users/piranna)) - [#54](https://github.com/kpdecker/jsdiff/issues/54) - Feature Request: 3-way merge ([@mog422](https://api.github.com/users/mog422)) - [#42](https://github.com/kpdecker/jsdiff/issues/42) - Fuzz factor for applyPatch ([@stuartpb](https://api.github.com/users/stuartpb)) - Move whitespace ignore out of equals method - 542063c - Include source maps in babel output - 7f7ab21 - Merge diff/line and diff/patch implementations - 1597705 - Drop map utility method - 1ddc939 - Documentation for parsePatch and applyPatches - 27c4b77 Compatibility notes: - The undocumented ignoreWhitespace flag has been removed from the Diff equality check directly. This implementation may be copied to diff utilities if dependencies existed on this functionality. [Commits](https://github.com/kpdecker/jsdiff/compare/v2.0.2...v2.1.0) ## v2.0.2 - August 8th, 2015 - [#67](https://github.com/kpdecker/jsdiff/issues/67) - cannot require from npm module in node ([@commenthol](https://api.github.com/users/commenthol)) - Convert to chai since we don’t support IE8 - a96bbad [Commits](https://github.com/kpdecker/jsdiff/compare/v2.0.1...v2.0.2) ## v2.0.1 - August 7th, 2015 - Add release build at proper step - 57542fd [Commits](https://github.com/kpdecker/jsdiff/compare/v2.0.0...v2.0.1) ## v2.0.0 - August 7th, 2015 - [#66](https://github.com/kpdecker/jsdiff/issues/66) - Add karma and sauce tests ([@kpdecker](https://api.github.com/users/kpdecker)) - [#65](https://github.com/kpdecker/jsdiff/issues/65) - Create component repository for bower ([@kpdecker](https://api.github.com/users/kpdecker)) - [#64](https://github.com/kpdecker/jsdiff/issues/64) - Automatically call removeEmpty for all tokenizer calls ([@kpdecker](https://api.github.com/users/kpdecker)) - [#62](https://github.com/kpdecker/jsdiff/pull/62) - Allow access to structured object representation of patch data ([@bittrance](https://api.github.com/users/bittrance)) - [#61](https://github.com/kpdecker/jsdiff/pull/61) - Use svg instead of png to get better image quality ([@PeterDaveHello](https://api.github.com/users/PeterDaveHello)) - [#29](https://github.com/kpdecker/jsdiff/issues/29) - word tokenizer works only for 7 bit ascii ([@plasmagunman](https://api.github.com/users/plasmagunman)) Compatibility notes: - `this.removeEmpty` is now called automatically for all instances. If this is not desired, this may be overridden on a per instance basis. - The library has been refactored to use some ES6 features. The external APIs should remain the same, but bower projects that directly referenced the repository will now have to point to the [components/jsdiff](https://github.com/components/jsdiff) repository. [Commits](https://github.com/kpdecker/jsdiff/compare/v1.4.0...v2.0.0) ## v1.4.0 - May 6th, 2015 - [#57](https://github.com/kpdecker/jsdiff/issues/57) - createPatch -> applyPatch failed. ([@mog422](https://api.github.com/users/mog422)) - [#56](https://github.com/kpdecker/jsdiff/pull/56) - Two files patch ([@rgeissert](https://api.github.com/users/rgeissert)) - [#14](https://github.com/kpdecker/jsdiff/issues/14) - Flip added and removed order? ([@jakesandlund](https://api.github.com/users/jakesandlund)) [Commits](https://github.com/kpdecker/jsdiff/compare/v1.3.2...v1.4.0) ## v1.3.2 - March 30th, 2015 - [#53](https://github.com/kpdecker/jsdiff/pull/53) - Updated README.MD with Bower installation instructions ([@ofbriggs](https://api.github.com/users/ofbriggs)) - [#49](https://github.com/kpdecker/jsdiff/issues/49) - Cannot read property 'oldlines' of undefined ([@nwtn](https://api.github.com/users/nwtn)) - [#44](https://github.com/kpdecker/jsdiff/issues/44) - invalid-meta jsdiff is missing "main" entry in bower.json [Commits](https://github.com/kpdecker/jsdiff/compare/v1.3.1...v1.3.2) ## v1.3.1 - March 13th, 2015 - [#52](https://github.com/kpdecker/jsdiff/pull/52) - Fix for #51 Wrong result of JsDiff.diffLines ([@felicienfrancois](https://api.github.com/users/felicienfrancois)) [Commits](https://github.com/kpdecker/jsdiff/compare/v1.3.0...v1.3.1) ## v1.3.0 - March 2nd, 2015 - [#47](https://github.com/kpdecker/jsdiff/pull/47) - Adding Diff Trimmed Lines ([@JamesGould123](https://api.github.com/users/JamesGould123)) [Commits](https://github.com/kpdecker/jsdiff/compare/v1.2.2...v1.3.0) ## v1.2.2 - January 26th, 2015 - [#45](https://github.com/kpdecker/jsdiff/pull/45) - Fix AMD module loading ([@pedrocarrico](https://api.github.com/users/pedrocarrico)) - [#43](https://github.com/kpdecker/jsdiff/pull/43) - added a bower file ([@nbrustein](https://api.github.com/users/nbrustein)) [Commits](https://github.com/kpdecker/jsdiff/compare/v1.2.1...v1.2.2) ## v1.2.1 - December 26th, 2014 - [#41](https://github.com/kpdecker/jsdiff/pull/41) - change condition of using node export system. ([@ironhee](https://api.github.com/users/ironhee)) [Commits](https://github.com/kpdecker/jsdiff/compare/v1.2.0...v1.2.1) ## v1.2.0 - November 29th, 2014 - [#37](https://github.com/kpdecker/jsdiff/pull/37) - Add support for sentences. ([@vmariano](https://api.github.com/users/vmariano)) - [#28](https://github.com/kpdecker/jsdiff/pull/28) - Implemented diffJson ([@papandreou](https://api.github.com/users/papandreou)) - [#27](https://github.com/kpdecker/jsdiff/issues/27) - Slow to execute over diffs with a large number of changes ([@termi](https://api.github.com/users/termi)) - Allow for optional async diffing - 19385b9 - Fix diffChars implementation - eaa44ed [Commits](https://github.com/kpdecker/jsdiff/compare/v1.1.0...v1.2.0) ## v1.1.0 - November 25th, 2014 - [#33](https://github.com/kpdecker/jsdiff/pull/33) - AMD and global exports ([@ovcharik](https://api.github.com/users/ovcharik)) - [#32](https://github.com/kpdecker/jsdiff/pull/32) - Add support for component ([@vmariano](https://api.github.com/users/vmariano)) - [#31](https://github.com/kpdecker/jsdiff/pull/31) - Don't rely on Array.prototype.map ([@papandreou](https://api.github.com/users/papandreou)) [Commits](https://github.com/kpdecker/jsdiff/compare/v1.0.8...v1.1.0) ## v1.0.8 - December 22nd, 2013 - [#24](https://github.com/kpdecker/jsdiff/pull/24) - Handle windows newlines on non windows machines. ([@benogle](https://api.github.com/users/benogle)) - [#23](https://github.com/kpdecker/jsdiff/pull/23) - Prettied up the API formatting a little, and added basic node and web examples ([@airportyh](https://api.github.com/users/airportyh)) [Commits](https://github.com/kpdecker/jsdiff/compare/v1.0.7...v1.0.8) ## v1.0.7 - September 11th, 2013 - [#22](https://github.com/kpdecker/jsdiff/pull/22) - Added variant of WordDiff that doesn't ignore whitespace differences ([@papandreou](https://api.github.com/users/papandreou) - Add 0.10 to travis tests - 243a526 [Commits](https://github.com/kpdecker/jsdiff/compare/v1.0.6...v1.0.7) ## v1.0.6 - August 30th, 2013 - [#19](https://github.com/kpdecker/jsdiff/pull/19) - Explicitly define contents of npm package ([@sindresorhus](https://api.github.com/users/sindresorhus) [Commits](https://github.com/kpdecker/jsdiff/compare/v1.0.5...v1.0.6) PK ~\W  clean-stack/package.jsonnu[{ "_id": "clean-stack@2.2.0", "_inBundle": true, "_location": "/npm/clean-stack", "_phantomChildren": {}, "_requiredBy": [ "/npm/aggregate-error" ], "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "browser": { "os": false }, "bugs": { "url": "https://github.com/sindresorhus/clean-stack/issues" }, "description": "Clean up error stack traces", "devDependencies": { "ava": "^1.4.1", "tsd": "^0.7.2", "xo": "^0.24.0" }, "engines": { "node": ">=6" }, "files": [ "index.js", "index.d.ts" ], "homepage": "https://github.com/sindresorhus/clean-stack#readme", "keywords": [ "clean", "stack", "trace", "traces", "error", "err", "electron" ], "license": "MIT", "name": "clean-stack", "repository": { "type": "git", "url": "git+https://github.com/sindresorhus/clean-stack.git" }, "scripts": { "test": "xo && ava && tsd" }, "version": "2.2.0" } PK ~\_clean-stack/index.jsnu['use strict'; const os = require('os'); const extractPathRegex = /\s+at.*(?:\(|\s)(.*)\)?/; const pathRegex = /^(?:(?:(?:node|(?:internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)\.js:\d+:\d+)|native)/; const homeDir = typeof os.homedir === 'undefined' ? '' : os.homedir(); module.exports = (stack, options) => { options = Object.assign({pretty: false}, options); return stack.replace(/\\/g, '/') .split('\n') .filter(line => { const pathMatches = line.match(extractPathRegex); if (pathMatches === null || !pathMatches[1]) { return true; } const match = pathMatches[1]; // Electron if ( match.includes('.app/Contents/Resources/electron.asar') || match.includes('.app/Contents/Resources/default_app.asar') ) { return false; } return !pathRegex.test(match); }) .filter(line => line.trim() !== '') .map(line => { if (options.pretty) { return line.replace(extractPathRegex, (m, p1) => m.replace(p1, p1.replace(homeDir, '~'))); } return line; }) .join('\n'); }; PK ~\E}UUclean-stack/licensenu[MIT License Copyright (c) Sindre Sorhus (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\Jagent-base/package.jsonnu[{ "_id": "agent-base@7.1.1", "_inBundle": true, "_location": "/npm/agent-base", "_phantomChildren": {}, "_requiredBy": [ "/npm/@npmcli/agent", "/npm/http-proxy-agent", "/npm/https-proxy-agent", "/npm/socks-proxy-agent" ], "author": { "name": "Nathan Rajlich", "email": "nathan@tootallnate.net", "url": "http://n8.io/" }, "bugs": { "url": "https://github.com/TooTallNate/proxy-agents/issues" }, "dependencies": { "debug": "^4.3.4" }, "description": "Turn a function into an `http.Agent` instance", "devDependencies": { "@types/debug": "^4.1.7", "@types/jest": "^29.5.1", "@types/node": "^14.18.45", "@types/semver": "^7.3.13", "@types/ws": "^6.0.4", "async-listen": "^3.0.0", "jest": "^29.5.0", "ts-jest": "^29.1.0", "tsconfig": "0.0.0", "typescript": "^5.0.4", "ws": "^3.3.3" }, "engines": { "node": ">= 14" }, "files": [ "dist" ], "homepage": "https://github.com/TooTallNate/proxy-agents#readme", "keywords": [ "http", "agent", "base", "barebones", "https" ], "license": "MIT", "main": "./dist/index.js", "name": "agent-base", "repository": { "type": "git", "url": "git+https://github.com/TooTallNate/proxy-agents.git", "directory": "packages/agent-base" }, "scripts": { "build": "tsc", "lint": "eslint . --ext .ts", "pack": "node ../../scripts/pack.mjs", "test": "jest --env node --verbose --bail" }, "types": "./dist/index.d.ts", "version": "7.1.1" } PK ~\sMMagent-base/LICENSEnu[(The MIT License) Copyright (c) 2013 Nathan Rajlich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.PK ~\u Iwwagent-base/dist/index.jsnu["use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Agent = void 0; const net = __importStar(require("net")); const http = __importStar(require("http")); const https_1 = require("https"); __exportStar(require("./helpers"), exports); const INTERNAL = Symbol('AgentBaseInternalState'); class Agent extends http.Agent { constructor(opts) { super(opts); this[INTERNAL] = {}; } /** * Determine whether this is an `http` or `https` request. */ isSecureEndpoint(options) { if (options) { // First check the `secureEndpoint` property explicitly, since this // means that a parent `Agent` is "passing through" to this instance. // eslint-disable-next-line @typescript-eslint/no-explicit-any if (typeof options.secureEndpoint === 'boolean') { return options.secureEndpoint; } // If no explicit `secure` endpoint, check if `protocol` property is // set. This will usually be the case since using a full string URL // or `URL` instance should be the most common usage. if (typeof options.protocol === 'string') { return options.protocol === 'https:'; } } // Finally, if no `protocol` property was set, then fall back to // checking the stack trace of the current call stack, and try to // detect the "https" module. const { stack } = new Error(); if (typeof stack !== 'string') return false; return stack .split('\n') .some((l) => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1); } // In order to support async signatures in `connect()` and Node's native // connection pooling in `http.Agent`, the array of sockets for each origin // has to be updated synchronously. This is so the length of the array is // accurate when `addRequest()` is next called. We achieve this by creating a // fake socket and adding it to `sockets[origin]` and incrementing // `totalSocketCount`. incrementSockets(name) { // If `maxSockets` and `maxTotalSockets` are both Infinity then there is no // need to create a fake socket because Node.js native connection pooling // will never be invoked. if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) { return null; } // All instances of `sockets` are expected TypeScript errors. The // alternative is to add it as a private property of this class but that // will break TypeScript subclassing. if (!this.sockets[name]) { // @ts-expect-error `sockets` is readonly in `@types/node` this.sockets[name] = []; } const fakeSocket = new net.Socket({ writable: false }); this.sockets[name].push(fakeSocket); // @ts-expect-error `totalSocketCount` isn't defined in `@types/node` this.totalSocketCount++; return fakeSocket; } decrementSockets(name, socket) { if (!this.sockets[name] || socket === null) { return; } const sockets = this.sockets[name]; const index = sockets.indexOf(socket); if (index !== -1) { sockets.splice(index, 1); // @ts-expect-error `totalSocketCount` isn't defined in `@types/node` this.totalSocketCount--; if (sockets.length === 0) { // @ts-expect-error `sockets` is readonly in `@types/node` delete this.sockets[name]; } } } // In order to properly update the socket pool, we need to call `getName()` on // the core `https.Agent` if it is a secureEndpoint. getName(options) { const secureEndpoint = typeof options.secureEndpoint === 'boolean' ? options.secureEndpoint : this.isSecureEndpoint(options); if (secureEndpoint) { // @ts-expect-error `getName()` isn't defined in `@types/node` return https_1.Agent.prototype.getName.call(this, options); } // @ts-expect-error `getName()` isn't defined in `@types/node` return super.getName(options); } createSocket(req, options, cb) { const connectOpts = { ...options, secureEndpoint: this.isSecureEndpoint(options), }; const name = this.getName(connectOpts); const fakeSocket = this.incrementSockets(name); Promise.resolve() .then(() => this.connect(req, connectOpts)) .then((socket) => { this.decrementSockets(name, fakeSocket); if (socket instanceof http.Agent) { // @ts-expect-error `addRequest()` isn't defined in `@types/node` return socket.addRequest(req, connectOpts); } this[INTERNAL].currentSocket = socket; // @ts-expect-error `createSocket()` isn't defined in `@types/node` super.createSocket(req, options, cb); }, (err) => { this.decrementSockets(name, fakeSocket); cb(err); }); } createConnection() { const socket = this[INTERNAL].currentSocket; this[INTERNAL].currentSocket = undefined; if (!socket) { throw new Error('No socket was returned in the `connect()` function'); } return socket; } get defaultPort() { return (this[INTERNAL].defaultPort ?? (this.protocol === 'https:' ? 443 : 80)); } set defaultPort(v) { if (this[INTERNAL]) { this[INTERNAL].defaultPort = v; } } get protocol() { return (this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? 'https:' : 'http:')); } set protocol(v) { if (this[INTERNAL]) { this[INTERNAL].protocol = v; } } } exports.Agent = Agent; //# sourceMappingURL=index.js.mapPK ~\^^g agent-base/dist/helpers.jsnu["use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.req = exports.json = exports.toBuffer = void 0; const http = __importStar(require("http")); const https = __importStar(require("https")); async function toBuffer(stream) { let length = 0; const chunks = []; for await (const chunk of stream) { length += chunk.length; chunks.push(chunk); } return Buffer.concat(chunks, length); } exports.toBuffer = toBuffer; // eslint-disable-next-line @typescript-eslint/no-explicit-any async function json(stream) { const buf = await toBuffer(stream); const str = buf.toString('utf8'); try { return JSON.parse(str); } catch (_err) { const err = _err; err.message += ` (input: ${str})`; throw err; } } exports.json = json; function req(url, opts = {}) { const href = typeof url === 'string' ? url : url.href; const req = (href.startsWith('https:') ? https : http).request(url, opts); const promise = new Promise((resolve, reject) => { req .once('response', resolve) .once('error', reject) .end(); }); req.then = promise.then.bind(promise); return req; } exports.req = req; //# sourceMappingURL=helpers.js.mapPK ~\Y socks-proxy-agent/package.jsonnu[{ "_id": "socks-proxy-agent@8.0.3", "_inBundle": true, "_location": "/npm/socks-proxy-agent", "_phantomChildren": {}, "_requiredBy": [ "/npm/@npmcli/agent" ], "author": { "name": "Nathan Rajlich", "email": "nathan@tootallnate.net", "url": "http://n8.io/" }, "bugs": { "url": "https://github.com/TooTallNate/proxy-agents/issues" }, "contributors": [ { "name": "Kiko Beats", "email": "josefrancisco.verdu@gmail.com" }, { "name": "Josh Glazebrook", "email": "josh@joshglazebrook.com" }, { "name": "talmobi", "email": "talmobi@users.noreply.github.com" }, { "name": "Indospace.io", "email": "justin@indospace.io" }, { "name": "Kilian von Pflugk", "email": "github@jumoog.io" }, { "name": "Kyle", "email": "admin@hk1229.cn" }, { "name": "Matheus Fernandes", "email": "matheus.frndes@gmail.com" }, { "name": "Ricky Miller", "email": "richardkazuomiller@gmail.com" }, { "name": "Shantanu Sharma", "email": "shantanu34@outlook.com" }, { "name": "Tim Perry", "email": "pimterry@gmail.com" }, { "name": "Vadim Baryshev", "email": "vadimbaryshev@gmail.com" }, { "name": "jigu", "email": "luo1257857309@gmail.com" }, { "name": "Alba Mendez", "email": "me@jmendeth.com" }, { "name": "Дмитрий Гуденков", "email": "Dimangud@rambler.ru" }, { "name": "Andrei Bitca", "email": "63638922+andrei-bitca-dc@users.noreply.github.com" }, { "name": "Andrew Casey", "email": "amcasey@users.noreply.github.com" }, { "name": "Brandon Ros", "email": "brandonros1@gmail.com" }, { "name": "Dang Duy Thanh", "email": "thanhdd.it@gmail.com" }, { "name": "Dimitar Nestorov", "email": "8790386+dimitarnestorov@users.noreply.github.com" } ], "dependencies": { "agent-base": "^7.1.1", "debug": "^4.3.4", "socks": "^2.7.1" }, "description": "A SOCKS proxy `http.Agent` implementation for HTTP and HTTPS", "devDependencies": { "@types/async-retry": "^1.4.5", "@types/debug": "^4.1.7", "@types/dns2": "^2.0.3", "@types/jest": "^29.5.1", "@types/node": "^14.18.45", "async-listen": "^3.0.0", "async-retry": "^1.3.3", "cacheable-lookup": "^6.1.0", "dns2": "^2.1.0", "jest": "^29.5.0", "proxy": "2.1.1", "socksv5": "github:TooTallNate/socksv5#fix/dstSock-close-event", "ts-jest": "^29.1.0", "tsconfig": "0.0.0", "typescript": "^5.0.4" }, "engines": { "node": ">= 14" }, "files": [ "dist" ], "homepage": "https://github.com/TooTallNate/proxy-agents#readme", "keywords": [ "agent", "http", "https", "proxy", "socks", "socks4", "socks4a", "socks5", "socks5h" ], "license": "MIT", "main": "./dist/index.js", "name": "socks-proxy-agent", "repository": { "type": "git", "url": "git+https://github.com/TooTallNate/proxy-agents.git", "directory": "packages/socks-proxy-agent" }, "scripts": { "build": "tsc", "lint": "eslint . --ext .ts", "pack": "node ../../scripts/pack.mjs", "test": "jest --env node --verbose --bail test/test.ts", "test-e2e": "jest --env node --verbose --bail test/e2e.test.ts" }, "types": "./dist/index.d.ts", "version": "8.0.3" } PK ~\sMMsocks-proxy-agent/LICENSEnu[(The MIT License) Copyright (c) 2013 Nathan Rajlich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.PK ~\o" socks-proxy-agent/dist/index.jsnu["use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SocksProxyAgent = void 0; const socks_1 = require("socks"); const agent_base_1 = require("agent-base"); const debug_1 = __importDefault(require("debug")); const dns = __importStar(require("dns")); const net = __importStar(require("net")); const tls = __importStar(require("tls")); const url_1 = require("url"); const debug = (0, debug_1.default)('socks-proxy-agent'); function parseSocksURL(url) { let lookup = false; let type = 5; const host = url.hostname; // From RFC 1928, Section 3: https://tools.ietf.org/html/rfc1928#section-3 // "The SOCKS service is conventionally located on TCP port 1080" const port = parseInt(url.port, 10) || 1080; // figure out if we want socks v4 or v5, based on the "protocol" used. // Defaults to 5. switch (url.protocol.replace(':', '')) { case 'socks4': lookup = true; type = 4; break; // pass through case 'socks4a': type = 4; break; case 'socks5': lookup = true; type = 5; break; // pass through case 'socks': // no version specified, default to 5h type = 5; break; case 'socks5h': type = 5; break; default: throw new TypeError(`A "socks" protocol must be specified! Got: ${String(url.protocol)}`); } const proxy = { host, port, type, }; if (url.username) { Object.defineProperty(proxy, 'userId', { value: decodeURIComponent(url.username), enumerable: false, }); } if (url.password != null) { Object.defineProperty(proxy, 'password', { value: decodeURIComponent(url.password), enumerable: false, }); } return { lookup, proxy }; } class SocksProxyAgent extends agent_base_1.Agent { constructor(uri, opts) { super(opts); const url = typeof uri === 'string' ? new url_1.URL(uri) : uri; const { proxy, lookup } = parseSocksURL(url); this.shouldLookup = lookup; this.proxy = proxy; this.timeout = opts?.timeout ?? null; this.socketOptions = opts?.socketOptions ?? null; } /** * Initiates a SOCKS connection to the specified SOCKS proxy server, * which in turn connects to the specified remote host and port. */ async connect(req, opts) { const { shouldLookup, proxy, timeout } = this; if (!opts.host) { throw new Error('No `host` defined!'); } let { host } = opts; const { port, lookup: lookupFn = dns.lookup } = opts; if (shouldLookup) { // Client-side DNS resolution for "4" and "5" socks proxy versions. host = await new Promise((resolve, reject) => { // Use the request's custom lookup, if one was configured: lookupFn(host, {}, (err, res) => { if (err) { reject(err); } else { resolve(res); } }); }); } const socksOpts = { proxy, destination: { host, port: typeof port === 'number' ? port : parseInt(port, 10), }, command: 'connect', timeout: timeout ?? undefined, // @ts-expect-error the type supplied by socks for socket_options is wider // than necessary since socks will always override the host and port socket_options: this.socketOptions ?? undefined, }; const cleanup = (tlsSocket) => { req.destroy(); socket.destroy(); if (tlsSocket) tlsSocket.destroy(); }; debug('Creating socks proxy connection: %o', socksOpts); const { socket } = await socks_1.SocksClient.createConnection(socksOpts); debug('Successfully created socks proxy connection'); if (timeout !== null) { socket.setTimeout(timeout); socket.on('timeout', () => cleanup()); } if (opts.secureEndpoint) { // The proxy is connecting to a TLS server, so upgrade // this socket connection to a TLS connection. debug('Upgrading socket connection to TLS'); const servername = opts.servername || opts.host; const tlsSocket = tls.connect({ ...omit(opts, 'host', 'path', 'port'), socket, servername: net.isIP(servername) ? undefined : servername, }); tlsSocket.once('error', (error) => { debug('Socket TLS error', error.message); cleanup(tlsSocket); }); return tlsSocket; } return socket; } } SocksProxyAgent.protocols = [ 'socks', 'socks4', 'socks4a', 'socks5', 'socks5h', ]; exports.SocksProxyAgent = SocksProxyAgent; function omit(obj, ...keys) { const ret = {}; let key; for (key in obj) { if (!keys.includes(key)) { ret[key] = obj[key]; } } return ret; } //# sourceMappingURL=index.js.mapPK ~\Ilibnpmteam/package.jsonnu[{ "_id": "libnpmteam@6.0.5", "_inBundle": true, "_location": "/npm/libnpmteam", "_phantomChildren": {}, "_requiredBy": [ "/npm" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/cli/issues" }, "dependencies": { "aproba": "^2.0.0", "npm-registry-fetch": "^17.0.1" }, "description": "npm Team management APIs", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.22.0", "nock": "^13.3.3", "tap": "^16.3.8" }, "engines": { "node": "^16.14.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://npmjs.com/package/libnpmteam", "license": "ISC", "main": "lib/index.js", "name": "libnpmteam", "repository": { "type": "git", "url": "git+https://github.com/npm/cli.git", "directory": "workspaces/libnpmteam" }, "scripts": { "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.22.0", "content": "../../scripts/template-oss/index.js" }, "version": "6.0.5" } PK ~\;libnpmteam/lib/index.jsnu['use strict' const eu = encodeURIComponent const npmFetch = require('npm-registry-fetch') const validate = require('aproba') const cmd = module.exports cmd.create = (entity, opts = {}) => { return Promise.resolve().then(() => { const { scope, team } = splitEntity(entity) validate('SSO', [scope, team, opts]) const uri = `/-/org/${eu(scope)}/team` return npmFetch.json(uri, { ...opts, method: 'PUT', scope, body: { name: team, description: opts.description }, }) }) } cmd.destroy = async (entity, opts = {}) => { const { scope, team } = splitEntity(entity) validate('SSO', [scope, team, opts]) const uri = `/-/team/${eu(scope)}/${eu(team)}` await npmFetch(uri, { ...opts, method: 'DELETE', scope, ignoreBody: true, }) return true } cmd.add = (user, entity, opts = {}) => { const { scope, team } = splitEntity(entity) validate('SSO', [scope, team, opts]) const uri = `/-/team/${eu(scope)}/${eu(team)}/user` return npmFetch.json(uri, { ...opts, method: 'PUT', scope, body: { user }, }) } cmd.rm = async (user, entity, opts = {}) => { const { scope, team } = splitEntity(entity) validate('SSO', [scope, team, opts]) const uri = `/-/team/${eu(scope)}/${eu(team)}/user` await npmFetch(uri, { ...opts, method: 'DELETE', scope, body: { user }, ignoreBody: true, }) return true } cmd.lsTeams = (...args) => cmd.lsTeams.stream(...args).collect() cmd.lsTeams.stream = (scope, opts = {}) => { validate('SO', [scope, opts]) const uri = `/-/org/${eu(scope)}/team` return npmFetch.json.stream(uri, '.*', { ...opts, query: { format: 'cli' }, }) } cmd.lsUsers = (...args) => cmd.lsUsers.stream(...args).collect() cmd.lsUsers.stream = (entity, opts = {}) => { const { scope, team } = splitEntity(entity) validate('SSO', [scope, team, opts]) const uri = `/-/team/${eu(scope)}/${eu(team)}/user` return npmFetch.json.stream(uri, '.*', { ...opts, query: { format: 'cli' }, }) } cmd.edit = () => { throw new Error('edit is not implemented yet') } function splitEntity (entity = '') { const [, scope, team] = entity.match(/^@?([^:]+):(.*)$/) || [] return { scope, team } } PK ~\gXlibnpmteam/LICENSEnu[Copyright npm, Inc Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\^`  libnpmteam/README.mdnu[# libnpmteam [![npm version](https://img.shields.io/npm/v/libnpmteam.svg)](https://npm.im/libnpmteam) [![license](https://img.shields.io/npm/l/libnpmteam.svg)](https://npm.im/libnpmteam) [![CI - libnpmteam](https://github.com/npm/cli/actions/workflows/ci-libnpmteam.yml/badge.svg)](https://github.com/npm/cli/actions/workflows/ci-libnpmteam.yml) [`libnpmteam`](https://github.com/npm/libnpmteam) is a Node.js library that provides programmatic access to the guts of the npm CLI's `npm team` command and its various subcommands. ## Example ```javascript const team = require('libnpmteam') // List all teams for the @npm org. console.log(await team.lsTeams('npm')) ``` ## Publishing 1. Manually create CHANGELOG.md file 1. Commit changes to CHANGELOG.md ```bash $ git commit -m "chore: updated CHANGELOG.md" ``` 1. Run `npm version {newVersion}` ```bash # Example $ npm version patch # 1. Runs `coverage` and `lint` scripts # 2. Bumps package version; and **create commit/tag** # 3. Runs `npm publish`; publishing directory with **unpushed commit** # 4. Runs `git push origin --follow-tags` ``` ## Table of Contents * [Installing](#install) * [Example](#example) * [API](#api) * [team opts](#opts) * [`create()`](#create) * [`destroy()`](#destroy) * [`add()`](#add) * [`rm()`](#rm) * [`lsTeams()`](#ls-teams) * [`lsTeams.stream()`](#ls-teams-stream) * [`lsUsers()`](#ls-users) * [`lsUsers.stream()`](#ls-users-stream) ### Install `$ npm install libnpmteam` ### API #### `opts` for `libnpmteam` commands `libnpmteam` uses [`npm-registry-fetch`](https://npm.im/npm-registry-fetch). All options are passed through directly to that library, so please refer to [its own `opts` documentation](https://www.npmjs.com/package/npm-registry-fetch#fetch-options) for options that can be passed in. A couple of options of note for those in a hurry: * `opts.token` - can be passed in and will be used as the authentication token for the registry. For other ways to pass in auth details, see the n-r-f docs. * `opts.otp` - certain operations will require an OTP token to be passed in. If a `libnpmteam` command fails with `err.code === EOTP`, please retry the request with `{otp: <2fa token>}` #### `> team.create(team, [opts]) -> Promise` Creates a team named `team`. Team names use the format `@:`, with the `@` being optional. Additionally, `opts.description` may be passed in to include a description. ##### Example ```javascript await team.create('@npm:cli', {token: 'myregistrytoken'}) // The @npm:cli team now exists. ``` #### `> team.destroy(team, [opts]) -> Promise` Destroys a team named `team`. Team names use the format `@:`, with the `@` being optional. ##### Example ```javascript await team.destroy('@npm:cli', {token: 'myregistrytoken'}) // The @npm:cli team has been destroyed. ``` #### `> team.add(user, team, [opts]) -> Promise` Adds `user` to `team`. ##### Example ```javascript await team.add('zkat', '@npm:cli', {token: 'myregistrytoken'}) // @zkat now belongs to the @npm:cli team. ``` #### `> team.rm(user, team, [opts]) -> Promise` Removes `user` from `team`. ##### Example ```javascript await team.rm('zkat', '@npm:cli', {token: 'myregistrytoken'}) // @zkat is no longer part of the @npm:cli team. ``` #### `> team.lsTeams(scope, [opts]) -> Promise` Resolves to an array of team names belonging to `scope`. ##### Example ```javascript await team.lsTeams('@npm', {token: 'myregistrytoken'}) => [ 'npm:cli', 'npm:web', 'npm:registry', 'npm:developers' ] ``` #### `> team.lsTeams.stream(scope, [opts]) -> Stream` Returns a stream of teams belonging to `scope`. For a Promise-based version of these results, see [`team.lsTeams()`](#ls-teams). ##### Example ```javascript for await (let team of team.lsTeams.stream('@npm', {token: 'myregistrytoken'})) { console.log(team) } // outputs // npm:cli // npm:web // npm:registry // npm:developers ``` #### `> team.lsUsers(team, [opts]) -> Promise` Resolves to an array of usernames belonging to `team`. For a streamed version of these results, see [`team.lsUsers.stream()`](#ls-users-stream). ##### Example ```javascript await team.lsUsers('@npm:cli', {token: 'myregistrytoken'}) => [ 'iarna', 'zkat' ] ``` #### `> team.lsUsers.stream(team, [opts]) -> Stream` Returns a stream of usernames belonging to `team`. For a Promise-based version of these results, see [`team.lsUsers()`](#ls-users). ##### Example ```javascript for await (let user of team.lsUsers.stream('@npm:cli', {token: 'myregistrytoken'})) { console.log(user) } // outputs // iarna // zkat ``` PK ~\\Bminipass-flush/package.jsonnu[{ "_id": "minipass-flush@1.0.5", "_inBundle": true, "_location": "/npm/minipass-flush", "_phantomChildren": { "yallist": "4.0.0" }, "_requiredBy": [ "/npm/cacache", "/npm/make-fetch-happen" ], "author": { "name": "Isaac Z. Schlueter", "email": "i@izs.me", "url": "https://izs.me" }, "bugs": { "url": "https://github.com/isaacs/minipass-flush/issues" }, "dependencies": { "minipass": "^3.0.0" }, "description": "A Minipass stream that calls a flush function before emitting 'end'", "devDependencies": { "tap": "^14.6.9" }, "engines": { "node": ">= 8" }, "files": [ "index.js" ], "homepage": "https://github.com/isaacs/minipass-flush#readme", "keywords": [ "minipass", "flush", "stream" ], "license": "ISC", "main": "index.js", "name": "minipass-flush", "repository": { "type": "git", "url": "git+https://github.com/isaacs/minipass-flush.git" }, "scripts": { "postpublish": "git push origin --follow-tags", "postversion": "npm publish", "preversion": "npm test", "snap": "tap", "test": "tap" }, "tap": { "check-coverage": true }, "version": "1.0.5" } PK ~\1minipass-flush/node_modules/minipass/package.jsonnu[{ "_id": "minipass@3.3.6", "_inBundle": true, "_location": "/npm/minipass-flush/minipass", "_phantomChildren": {}, "_requiredBy": [ "/npm/minipass-flush" ], "author": { "name": "Isaac Z. Schlueter", "email": "i@izs.me", "url": "http://blog.izs.me/" }, "bugs": { "url": "https://github.com/isaacs/minipass/issues" }, "dependencies": { "yallist": "^4.0.0" }, "description": "minimal implementation of a PassThrough stream", "devDependencies": { "@types/node": "^17.0.41", "end-of-stream": "^1.4.0", "prettier": "^2.6.2", "tap": "^16.2.0", "through2": "^2.0.3", "ts-node": "^10.8.1", "typescript": "^4.7.3" }, "engines": { "node": ">=8" }, "files": [ "index.d.ts", "index.js" ], "homepage": "https://github.com/isaacs/minipass#readme", "keywords": [ "passthrough", "stream" ], "license": "ISC", "main": "index.js", "name": "minipass", "prettier": { "semi": false, "printWidth": 80, "tabWidth": 2, "useTabs": false, "singleQuote": true, "jsxSingleQuote": false, "bracketSameLine": true, "arrowParens": "avoid", "endOfLine": "lf" }, "repository": { "type": "git", "url": "git+https://github.com/isaacs/minipass.git" }, "scripts": { "postpublish": "git push origin --follow-tags", "postversion": "npm publish", "preversion": "npm test", "test": "tap" }, "tap": { "check-coverage": true }, "types": "index.d.ts", "version": "3.3.6" } PK ~\,minipass-flush/node_modules/minipass/LICENSEnu[The ISC License Copyright (c) 2017-2022 npm, Inc., Isaac Z. Schlueter, and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\-@@-minipass-flush/node_modules/minipass/index.jsnu['use strict' const proc = typeof process === 'object' && process ? process : { stdout: null, stderr: null, } const EE = require('events') const Stream = require('stream') const SD = require('string_decoder').StringDecoder const EOF = Symbol('EOF') const MAYBE_EMIT_END = Symbol('maybeEmitEnd') const EMITTED_END = Symbol('emittedEnd') const EMITTING_END = Symbol('emittingEnd') const EMITTED_ERROR = Symbol('emittedError') const CLOSED = Symbol('closed') const READ = Symbol('read') const FLUSH = Symbol('flush') const FLUSHCHUNK = Symbol('flushChunk') const ENCODING = Symbol('encoding') const DECODER = Symbol('decoder') const FLOWING = Symbol('flowing') const PAUSED = Symbol('paused') const RESUME = Symbol('resume') const BUFFERLENGTH = Symbol('bufferLength') const BUFFERPUSH = Symbol('bufferPush') const BUFFERSHIFT = Symbol('bufferShift') const OBJECTMODE = Symbol('objectMode') const DESTROYED = Symbol('destroyed') const EMITDATA = Symbol('emitData') const EMITEND = Symbol('emitEnd') const EMITEND2 = Symbol('emitEnd2') const ASYNC = Symbol('async') const defer = fn => Promise.resolve().then(fn) // TODO remove when Node v8 support drops const doIter = global._MP_NO_ITERATOR_SYMBOLS_ !== '1' const ASYNCITERATOR = doIter && Symbol.asyncIterator || Symbol('asyncIterator not implemented') const ITERATOR = doIter && Symbol.iterator || Symbol('iterator not implemented') // events that mean 'the stream is over' // these are treated specially, and re-emitted // if they are listened for after emitting. const isEndish = ev => ev === 'end' || ev === 'finish' || ev === 'prefinish' const isArrayBuffer = b => b instanceof ArrayBuffer || typeof b === 'object' && b.constructor && b.constructor.name === 'ArrayBuffer' && b.byteLength >= 0 const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b) class Pipe { constructor (src, dest, opts) { this.src = src this.dest = dest this.opts = opts this.ondrain = () => src[RESUME]() dest.on('drain', this.ondrain) } unpipe () { this.dest.removeListener('drain', this.ondrain) } // istanbul ignore next - only here for the prototype proxyErrors () {} end () { this.unpipe() if (this.opts.end) this.dest.end() } } class PipeProxyErrors extends Pipe { unpipe () { this.src.removeListener('error', this.proxyErrors) super.unpipe() } constructor (src, dest, opts) { super(src, dest, opts) this.proxyErrors = er => dest.emit('error', er) src.on('error', this.proxyErrors) } } module.exports = class Minipass extends Stream { constructor (options) { super() this[FLOWING] = false // whether we're explicitly paused this[PAUSED] = false this.pipes = [] this.buffer = [] this[OBJECTMODE] = options && options.objectMode || false if (this[OBJECTMODE]) this[ENCODING] = null else this[ENCODING] = options && options.encoding || null if (this[ENCODING] === 'buffer') this[ENCODING] = null this[ASYNC] = options && !!options.async || false this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null this[EOF] = false this[EMITTED_END] = false this[EMITTING_END] = false this[CLOSED] = false this[EMITTED_ERROR] = null this.writable = true this.readable = true this[BUFFERLENGTH] = 0 this[DESTROYED] = false } get bufferLength () { return this[BUFFERLENGTH] } get encoding () { return this[ENCODING] } set encoding (enc) { if (this[OBJECTMODE]) throw new Error('cannot set encoding in objectMode') if (this[ENCODING] && enc !== this[ENCODING] && (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH])) throw new Error('cannot change encoding') if (this[ENCODING] !== enc) { this[DECODER] = enc ? new SD(enc) : null if (this.buffer.length) this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk)) } this[ENCODING] = enc } setEncoding (enc) { this.encoding = enc } get objectMode () { return this[OBJECTMODE] } set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om } get ['async'] () { return this[ASYNC] } set ['async'] (a) { this[ASYNC] = this[ASYNC] || !!a } write (chunk, encoding, cb) { if (this[EOF]) throw new Error('write after end') if (this[DESTROYED]) { this.emit('error', Object.assign( new Error('Cannot call write after a stream was destroyed'), { code: 'ERR_STREAM_DESTROYED' } )) return true } if (typeof encoding === 'function') cb = encoding, encoding = 'utf8' if (!encoding) encoding = 'utf8' const fn = this[ASYNC] ? defer : f => f() // convert array buffers and typed array views into buffers // at some point in the future, we may want to do the opposite! // leave strings and buffers as-is // anything else switches us into object mode if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { if (isArrayBufferView(chunk)) chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) else if (isArrayBuffer(chunk)) chunk = Buffer.from(chunk) else if (typeof chunk !== 'string') // use the setter so we throw if we have encoding set this.objectMode = true } // handle object mode up front, since it's simpler // this yields better performance, fewer checks later. if (this[OBJECTMODE]) { /* istanbul ignore if - maybe impossible? */ if (this.flowing && this[BUFFERLENGTH] !== 0) this[FLUSH](true) if (this.flowing) this.emit('data', chunk) else this[BUFFERPUSH](chunk) if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } // at this point the chunk is a buffer or string // don't buffer it up or send it to the decoder if (!chunk.length) { if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } // fast-path writing strings of same encoding to a stream with // an empty buffer, skipping the buffer/decoder dance if (typeof chunk === 'string' && // unless it is a string already ready for us to use !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) { chunk = Buffer.from(chunk, encoding) } if (Buffer.isBuffer(chunk) && this[ENCODING]) chunk = this[DECODER].write(chunk) // Note: flushing CAN potentially switch us into not-flowing mode if (this.flowing && this[BUFFERLENGTH] !== 0) this[FLUSH](true) if (this.flowing) this.emit('data', chunk) else this[BUFFERPUSH](chunk) if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } read (n) { if (this[DESTROYED]) return null if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) { this[MAYBE_EMIT_END]() return null } if (this[OBJECTMODE]) n = null if (this.buffer.length > 1 && !this[OBJECTMODE]) { if (this.encoding) this.buffer = [this.buffer.join('')] else this.buffer = [Buffer.concat(this.buffer, this[BUFFERLENGTH])] } const ret = this[READ](n || null, this.buffer[0]) this[MAYBE_EMIT_END]() return ret } [READ] (n, chunk) { if (n === chunk.length || n === null) this[BUFFERSHIFT]() else { this.buffer[0] = chunk.slice(n) chunk = chunk.slice(0, n) this[BUFFERLENGTH] -= n } this.emit('data', chunk) if (!this.buffer.length && !this[EOF]) this.emit('drain') return chunk } end (chunk, encoding, cb) { if (typeof chunk === 'function') cb = chunk, chunk = null if (typeof encoding === 'function') cb = encoding, encoding = 'utf8' if (chunk) this.write(chunk, encoding) if (cb) this.once('end', cb) this[EOF] = true this.writable = false // if we haven't written anything, then go ahead and emit, // even if we're not reading. // we'll re-emit if a new 'end' listener is added anyway. // This makes MP more suitable to write-only use cases. if (this.flowing || !this[PAUSED]) this[MAYBE_EMIT_END]() return this } // don't let the internal resume be overwritten [RESUME] () { if (this[DESTROYED]) return this[PAUSED] = false this[FLOWING] = true this.emit('resume') if (this.buffer.length) this[FLUSH]() else if (this[EOF]) this[MAYBE_EMIT_END]() else this.emit('drain') } resume () { return this[RESUME]() } pause () { this[FLOWING] = false this[PAUSED] = true } get destroyed () { return this[DESTROYED] } get flowing () { return this[FLOWING] } get paused () { return this[PAUSED] } [BUFFERPUSH] (chunk) { if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1 else this[BUFFERLENGTH] += chunk.length this.buffer.push(chunk) } [BUFFERSHIFT] () { if (this.buffer.length) { if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1 else this[BUFFERLENGTH] -= this.buffer[0].length } return this.buffer.shift() } [FLUSH] (noDrain) { do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]())) if (!noDrain && !this.buffer.length && !this[EOF]) this.emit('drain') } [FLUSHCHUNK] (chunk) { return chunk ? (this.emit('data', chunk), this.flowing) : false } pipe (dest, opts) { if (this[DESTROYED]) return const ended = this[EMITTED_END] opts = opts || {} if (dest === proc.stdout || dest === proc.stderr) opts.end = false else opts.end = opts.end !== false opts.proxyErrors = !!opts.proxyErrors // piping an ended stream ends immediately if (ended) { if (opts.end) dest.end() } else { this.pipes.push(!opts.proxyErrors ? new Pipe(this, dest, opts) : new PipeProxyErrors(this, dest, opts)) if (this[ASYNC]) defer(() => this[RESUME]()) else this[RESUME]() } return dest } unpipe (dest) { const p = this.pipes.find(p => p.dest === dest) if (p) { this.pipes.splice(this.pipes.indexOf(p), 1) p.unpipe() } } addListener (ev, fn) { return this.on(ev, fn) } on (ev, fn) { const ret = super.on(ev, fn) if (ev === 'data' && !this.pipes.length && !this.flowing) this[RESUME]() else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) super.emit('readable') else if (isEndish(ev) && this[EMITTED_END]) { super.emit(ev) this.removeAllListeners(ev) } else if (ev === 'error' && this[EMITTED_ERROR]) { if (this[ASYNC]) defer(() => fn.call(this, this[EMITTED_ERROR])) else fn.call(this, this[EMITTED_ERROR]) } return ret } get emittedEnd () { return this[EMITTED_END] } [MAYBE_EMIT_END] () { if (!this[EMITTING_END] && !this[EMITTED_END] && !this[DESTROYED] && this.buffer.length === 0 && this[EOF]) { this[EMITTING_END] = true this.emit('end') this.emit('prefinish') this.emit('finish') if (this[CLOSED]) this.emit('close') this[EMITTING_END] = false } } emit (ev, data, ...extra) { // error and close are only events allowed after calling destroy() if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED]) return else if (ev === 'data') { return !data ? false : this[ASYNC] ? defer(() => this[EMITDATA](data)) : this[EMITDATA](data) } else if (ev === 'end') { return this[EMITEND]() } else if (ev === 'close') { this[CLOSED] = true // don't emit close before 'end' and 'finish' if (!this[EMITTED_END] && !this[DESTROYED]) return const ret = super.emit('close') this.removeAllListeners('close') return ret } else if (ev === 'error') { this[EMITTED_ERROR] = data const ret = super.emit('error', data) this[MAYBE_EMIT_END]() return ret } else if (ev === 'resume') { const ret = super.emit('resume') this[MAYBE_EMIT_END]() return ret } else if (ev === 'finish' || ev === 'prefinish') { const ret = super.emit(ev) this.removeAllListeners(ev) return ret } // Some other unknown event const ret = super.emit(ev, data, ...extra) this[MAYBE_EMIT_END]() return ret } [EMITDATA] (data) { for (const p of this.pipes) { if (p.dest.write(data) === false) this.pause() } const ret = super.emit('data', data) this[MAYBE_EMIT_END]() return ret } [EMITEND] () { if (this[EMITTED_END]) return this[EMITTED_END] = true this.readable = false if (this[ASYNC]) defer(() => this[EMITEND2]()) else this[EMITEND2]() } [EMITEND2] () { if (this[DECODER]) { const data = this[DECODER].end() if (data) { for (const p of this.pipes) { p.dest.write(data) } super.emit('data', data) } } for (const p of this.pipes) { p.end() } const ret = super.emit('end') this.removeAllListeners('end') return ret } // const all = await stream.collect() collect () { const buf = [] if (!this[OBJECTMODE]) buf.dataLength = 0 // set the promise first, in case an error is raised // by triggering the flow here. const p = this.promise() this.on('data', c => { buf.push(c) if (!this[OBJECTMODE]) buf.dataLength += c.length }) return p.then(() => buf) } // const data = await stream.concat() concat () { return this[OBJECTMODE] ? Promise.reject(new Error('cannot concat in objectMode')) : this.collect().then(buf => this[OBJECTMODE] ? Promise.reject(new Error('cannot concat in objectMode')) : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength)) } // stream.promise().then(() => done, er => emitted error) promise () { return new Promise((resolve, reject) => { this.on(DESTROYED, () => reject(new Error('stream destroyed'))) this.on('error', er => reject(er)) this.on('end', () => resolve()) }) } // for await (let chunk of stream) [ASYNCITERATOR] () { const next = () => { const res = this.read() if (res !== null) return Promise.resolve({ done: false, value: res }) if (this[EOF]) return Promise.resolve({ done: true }) let resolve = null let reject = null const onerr = er => { this.removeListener('data', ondata) this.removeListener('end', onend) reject(er) } const ondata = value => { this.removeListener('error', onerr) this.removeListener('end', onend) this.pause() resolve({ value: value, done: !!this[EOF] }) } const onend = () => { this.removeListener('error', onerr) this.removeListener('data', ondata) resolve({ done: true }) } const ondestroy = () => onerr(new Error('stream destroyed')) return new Promise((res, rej) => { reject = rej resolve = res this.once(DESTROYED, ondestroy) this.once('error', onerr) this.once('end', onend) this.once('data', ondata) }) } return { next } } // for (let chunk of stream) [ITERATOR] () { const next = () => { const value = this.read() const done = value === null return { value, done } } return { next } } destroy (er) { if (this[DESTROYED]) { if (er) this.emit('error', er) else this.emit(DESTROYED) return this } this[DESTROYED] = true // throw away all buffered data, it's never coming out this.buffer.length = 0 this[BUFFERLENGTH] = 0 if (typeof this.close === 'function' && !this[CLOSED]) this.close() if (er) this.emit('error', er) else // if no error to emit, still reject pending promises this.emit(DESTROYED) return this } static isStream (s) { return !!s && (s instanceof Minipass || s instanceof Stream || s instanceof EE && ( typeof s.pipe === 'function' || // readable (typeof s.write === 'function' && typeof s.end === 'function') // writable )) } } PK ~\aGWminipass-flush/LICENSEnu[The ISC License Copyright (c) Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\'wminipass-flush/index.jsnu[const Minipass = require('minipass') const _flush = Symbol('_flush') const _flushed = Symbol('_flushed') const _flushing = Symbol('_flushing') class Flush extends Minipass { constructor (opt = {}) { if (typeof opt === 'function') opt = { flush: opt } super(opt) // or extend this class and provide a 'flush' method in your subclass if (typeof opt.flush !== 'function' && typeof this.flush !== 'function') throw new TypeError('must provide flush function in options') this[_flush] = opt.flush || this.flush } emit (ev, ...data) { if ((ev !== 'end' && ev !== 'finish') || this[_flushed]) return super.emit(ev, ...data) if (this[_flushing]) return this[_flushing] = true const afterFlush = er => { this[_flushed] = true er ? super.emit('error', er) : super.emit('end') } const ret = this[_flush](afterFlush) if (ret && ret.then) ret.then(() => afterFlush(), er => afterFlush(er)) } } module.exports = Flush PK ~\J<<jsbn/package.jsonnu[{ "_id": "jsbn@1.1.0", "_inBundle": true, "_location": "/npm/jsbn", "_phantomChildren": {}, "_requiredBy": [ "/npm/ip-address" ], "author": { "name": "Tom Wu" }, "bugs": { "url": "https://github.com/andyperlitch/jsbn/issues" }, "description": "The jsbn library is a fast, portable implementation of large-number math in pure JavaScript, enabling public-key crypto and other applications on desktop and mobile browsers.", "homepage": "https://github.com/andyperlitch/jsbn#readme", "keywords": [ "biginteger", "bignumber", "big", "integer" ], "license": "MIT", "main": "index.js", "name": "jsbn", "repository": { "type": "git", "url": "git+https://github.com/andyperlitch/jsbn.git" }, "scripts": { "test": "mocha test.js" }, "version": "1.1.0" } PK ~\/>+jsbn/example.jsnu[(function () { var BigInteger = jsbn.BigInteger; var a = new BigInteger('91823918239182398123'); console.log(a.bitLength()); }()); PK ~\=D@@jsbn/test/es6-import.jsnu[import {BigInteger} from '../'; console.log(typeof BigInteger) PK ~\$ jsbn/LICENSEnu[Licensing --------- This software is covered under the following copyright: /* * Copyright (c) 2003-2005 Tom Wu * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL, * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * In addition, the following condition applies: * * All redistributions must retain an intact copy of this copyright notice * and disclaimer. */ Address all questions regarding this license to: Tom Wu tjw@cs.Stanford.EDU PK ~\Z`DD jsbn/index.jsnu[(function(){ // Copyright (c) 2005 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Basic JavaScript BN library - subset useful for RSA encryption. // Bits per digit var dbits; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = ((canary&0xffffff)==0xefcafe); // (public) Constructor function BigInteger(a,b,c) { if(a != null) if("number" == typeof a) this.fromNumber(a,b,c); else if(b == null && "string" != typeof a) this.fromString(a,256); else this.fromString(a,b); } // return new, unset BigInteger function nbi() { return new BigInteger(null); } // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i,x,w,j,c,n) { while(--n >= 0) { var v = x*this[i++]+w[j]+c; c = Math.floor(v/0x4000000); w[j++] = v&0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i,x,w,j,c,n) { var xl = x&0x7fff, xh = x>>15; while(--n >= 0) { var l = this[i]&0x7fff; var h = this[i++]>>15; var m = xh*l+h*xl; l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w[j++] = l&0x3fffffff; } return c; } // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i,x,w,j,c,n) { var xl = x&0x3fff, xh = x>>14; while(--n >= 0) { var l = this[i]&0x3fff; var h = this[i++]>>14; var m = xh*l+h*xl; l = xl*l+((m&0x3fff)<<14)+w[j]+c; c = (l>>28)+(m>>14)+xh*h; w[j++] = l&0xfffffff; } return c; } var inBrowser = typeof navigator !== "undefined"; if(inBrowser && j_lm && (navigator.appName == "Microsoft Internet Explorer")) { BigInteger.prototype.am = am2; dbits = 30; } else if(inBrowser && j_lm && (navigator.appName != "Netscape")) { BigInteger.prototype.am = am1; dbits = 26; } else { // Mozilla/Netscape seems to prefer am3 BigInteger.prototype.am = am3; dbits = 28; } BigInteger.prototype.DB = dbits; BigInteger.prototype.DM = ((1<= 0; --i) r[i] = this[i]; r.t = this.t; r.s = this.s; } // (protected) set from integer value x, -DV <= x < DV function bnpFromInt(x) { this.t = 1; this.s = (x<0)?-1:0; if(x > 0) this[0] = x; else if(x < -1) this[0] = x+this.DV; else this.t = 0; } // return bigint initialized to value function nbv(i) { var r = nbi(); r.fromInt(i); return r; } // (protected) set from string and radix function bnpFromString(s,b) { var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 256) k = 8; // byte array else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else { this.fromRadix(s,b); return; } this.t = 0; this.s = 0; var i = s.length, mi = false, sh = 0; while(--i >= 0) { var x = (k==8)?s[i]&0xff:intAt(s,i); if(x < 0) { if(s.charAt(i) == "-") mi = true; continue; } mi = false; if(sh == 0) this[this.t++] = x; else if(sh+k > this.DB) { this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<>(this.DB-sh)); } else this[this.t-1] |= x<= this.DB) sh -= this.DB; } if(k == 8 && (s[0]&0x80) != 0) { this.s = -1; if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)< 0 && this[this.t-1] == c) --this.t; } // (public) return string representation in given radix function bnToString(b) { if(this.s < 0) return "-"+this.negate().toString(b); var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else return this.toRadix(b); var km = (1< 0) { if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r = int2char(d); } while(i >= 0) { if(p < k) { d = (this[i]&((1<>(p+=this.DB-k); } else { d = (this[i]>>(p-=k))&km; if(p <= 0) { p += this.DB; --i; } } if(d > 0) m = true; if(m) r += int2char(d); } } return m?r:"0"; } // (public) -this function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } // (public) |this| function bnAbs() { return (this.s<0)?this.negate():this; } // (public) return + if this > a, - if this < a, 0 if equal function bnCompareTo(a) { var r = this.s-a.s; if(r != 0) return r; var i = this.t; r = i-a.t; if(r != 0) return (this.s<0)?-r:r; while(--i >= 0) if((r=this[i]-a[i]) != 0) return r; return 0; } // returns bit length of the integer x function nbits(x) { var r = 1, t; if((t=x>>>16) != 0) { x = t; r += 16; } if((t=x>>8) != 0) { x = t; r += 8; } if((t=x>>4) != 0) { x = t; r += 4; } if((t=x>>2) != 0) { x = t; r += 2; } if((t=x>>1) != 0) { x = t; r += 1; } return r; } // (public) return the number of bits in "this" function bnBitLength() { if(this.t <= 0) return 0; return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM)); } // (protected) r = this << n*DB function bnpDLShiftTo(n,r) { var i; for(i = this.t-1; i >= 0; --i) r[i+n] = this[i]; for(i = n-1; i >= 0; --i) r[i] = 0; r.t = this.t+n; r.s = this.s; } // (protected) r = this >> n*DB function bnpDRShiftTo(n,r) { for(var i = n; i < this.t; ++i) r[i-n] = this[i]; r.t = Math.max(this.t-n,0); r.s = this.s; } // (protected) r = this << n function bnpLShiftTo(n,r) { var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<= 0; --i) { r[i+ds+1] = (this[i]>>cbs)|c; c = (this[i]&bm)<= 0; --i) r[i] = 0; r[ds] = c; r.t = this.t+ds+1; r.s = this.s; r.clamp(); } // (protected) r = this >> n function bnpRShiftTo(n,r) { r.s = this.s; var ds = Math.floor(n/this.DB); if(ds >= this.t) { r.t = 0; return; } var bs = n%this.DB; var cbs = this.DB-bs; var bm = (1<>bs; for(var i = ds+1; i < this.t; ++i) { r[i-ds-1] |= (this[i]&bm)<>bs; } if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<>= this.DB; } if(a.t < this.t) { c -= a.s; while(i < this.t) { c += this[i]; r[i++] = c&this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while(i < a.t) { c -= a[i]; r[i++] = c&this.DM; c >>= this.DB; } c -= a.s; } r.s = (c<0)?-1:0; if(c < -1) r[i++] = this.DV+c; else if(c > 0) r[i++] = c; r.t = i; r.clamp(); } // (protected) r = this * a, r != this,a (HAC 14.12) // "this" should be the larger one if appropriate. function bnpMultiplyTo(a,r) { var x = this.abs(), y = a.abs(); var i = x.t; r.t = i+y.t; while(--i >= 0) r[i] = 0; for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t); r.s = 0; r.clamp(); if(this.s != a.s) BigInteger.ZERO.subTo(r,r); } // (protected) r = this^2, r != this (HAC 14.16) function bnpSquareTo(r) { var x = this.abs(); var i = r.t = 2*x.t; while(--i >= 0) r[i] = 0; for(i = 0; i < x.t-1; ++i) { var c = x.am(i,x[i],r,2*i,0,1); if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) { r[i+x.t] -= x.DV; r[i+x.t+1] = 1; } } if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1); r.s = 0; r.clamp(); } // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) // r != q, this != m. q or r may be null. function bnpDivRemTo(m,q,r) { var pm = m.abs(); if(pm.t <= 0) return; var pt = this.abs(); if(pt.t < pm.t) { if(q != null) q.fromInt(0); if(r != null) this.copyTo(r); return; } if(r == null) r = nbi(); var y = nbi(), ts = this.s, ms = m.s; var nsh = this.DB-nbits(pm[pm.t-1]); // normalize modulus if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); } var ys = y.t; var y0 = y[ys-1]; if(y0 == 0) return; var yt = y0*(1<1)?y[ys-2]>>this.F2:0); var d1 = this.FV/yt, d2 = (1<= 0) { r[r.t++] = 1; r.subTo(t,r); } BigInteger.ONE.dlShiftTo(ys,t); t.subTo(y,y); // "negative" y so we can replace sub with am later while(y.t < ys) y[y.t++] = 0; while(--j >= 0) { // Estimate quotient digit var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2); if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out y.dlShiftTo(j,t); r.subTo(t,r); while(r[i] < --qd) r.subTo(t,r); } } if(q != null) { r.drShiftTo(ys,q); if(ts != ms) BigInteger.ZERO.subTo(q,q); } r.t = ys; r.clamp(); if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder if(ts < 0) BigInteger.ZERO.subTo(r,r); } // (public) this mod a function bnMod(a) { var r = nbi(); this.abs().divRemTo(a,null,r); if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r); return r; } // Modular reduction using "classic" algorithm function Classic(m) { this.m = m; } function cConvert(x) { if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); else return x; } function cRevert(x) { return x; } function cReduce(x) { x.divRemTo(this.m,null,x); } function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); } Classic.prototype.convert = cConvert; Classic.prototype.revert = cRevert; Classic.prototype.reduce = cReduce; Classic.prototype.mulTo = cMulTo; Classic.prototype.sqrTo = cSqrTo; // (protected) return "-1/this % 2^DB"; useful for Mont. reduction // justification: // xy == 1 (mod m) // xy = 1+km // xy(2-xy) = (1+km)(1-km) // x[y(2-xy)] = 1-k^2m^2 // x[y(2-xy)] == 1 (mod m^2) // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. // JS multiply "overflows" differently from C/C++, so care is needed here. function bnpInvDigit() { if(this.t < 1) return 0; var x = this[0]; if((x&1) == 0) return 0; var y = x&3; // y == 1/x mod 2^2 y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4 y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8 y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 // last step - calculate inverse mod DV directly; // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return (y>0)?this.DV-y:-y; } // Montgomery reduction function Montgomery(m) { this.m = m; this.mp = m.invDigit(); this.mpl = this.mp&0x7fff; this.mph = this.mp>>15; this.um = (1<<(m.DB-15))-1; this.mt2 = 2*m.t; } // xR mod m function montConvert(x) { var r = nbi(); x.abs().dlShiftTo(this.m.t,r); r.divRemTo(this.m,null,r); if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r); return r; } // x/R mod m function montRevert(x) { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } // x = x/R mod m (HAC 14.32) function montReduce(x) { while(x.t <= this.mt2) // pad x so am has enough room later x[x.t++] = 0; for(var i = 0; i < this.m.t; ++i) { // faster way of calculating u0 = x[i]*mp mod DV var j = x[i]&0x7fff; var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM; // use am to combine the multiply-shift-add into one call j = i+this.m.t; x[j] += this.m.am(0,u0,x,i,0,this.m.t); // propagate carry while(x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; } } x.clamp(); x.drShiftTo(this.m.t,x); if(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = "x^2/R mod m"; x != r function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); } // r = "xy/R mod m"; x,y != r function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Montgomery.prototype.convert = montConvert; Montgomery.prototype.revert = montRevert; Montgomery.prototype.reduce = montReduce; Montgomery.prototype.mulTo = montMulTo; Montgomery.prototype.sqrTo = montSqrTo; // (protected) true iff this is even function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; } // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) function bnpExp(e,z) { if(e > 0xffffffff || e < 1) return BigInteger.ONE; var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1; g.copyTo(r); while(--i >= 0) { z.sqrTo(r,r2); if((e&(1< 0) z.mulTo(r2,g,r); else { var t = r; r = r2; r2 = t; } } return z.revert(r); } // (public) this^e % m, 0 <= e < 2^32 function bnModPowInt(e,m) { var z; if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m); return this.exp(e,z); } // protected BigInteger.prototype.copyTo = bnpCopyTo; BigInteger.prototype.fromInt = bnpFromInt; BigInteger.prototype.fromString = bnpFromString; BigInteger.prototype.clamp = bnpClamp; BigInteger.prototype.dlShiftTo = bnpDLShiftTo; BigInteger.prototype.drShiftTo = bnpDRShiftTo; BigInteger.prototype.lShiftTo = bnpLShiftTo; BigInteger.prototype.rShiftTo = bnpRShiftTo; BigInteger.prototype.subTo = bnpSubTo; BigInteger.prototype.multiplyTo = bnpMultiplyTo; BigInteger.prototype.squareTo = bnpSquareTo; BigInteger.prototype.divRemTo = bnpDivRemTo; BigInteger.prototype.invDigit = bnpInvDigit; BigInteger.prototype.isEven = bnpIsEven; BigInteger.prototype.exp = bnpExp; // public BigInteger.prototype.toString = bnToString; BigInteger.prototype.negate = bnNegate; BigInteger.prototype.abs = bnAbs; BigInteger.prototype.compareTo = bnCompareTo; BigInteger.prototype.bitLength = bnBitLength; BigInteger.prototype.mod = bnMod; BigInteger.prototype.modPowInt = bnModPowInt; // "constants" BigInteger.ZERO = nbv(0); BigInteger.ONE = nbv(1); // Copyright (c) 2005-2009 Tom Wu // All Rights Reserved. // See "LICENSE" for details. // Extended JavaScript BN functions, required for RSA private ops. // Version 1.1: new BigInteger("0", 10) returns "proper" zero // Version 1.2: square() API, isProbablePrime fix // (public) function bnClone() { var r = nbi(); this.copyTo(r); return r; } // (public) return value as integer function bnIntValue() { if(this.s < 0) { if(this.t == 1) return this[0]-this.DV; else if(this.t == 0) return -1; } else if(this.t == 1) return this[0]; else if(this.t == 0) return 0; // assumes 16 < DB < 32 return ((this[1]&((1<<(32-this.DB))-1))<>24; } // (public) return value as short (assumes DB>=16) function bnShortValue() { return (this.t==0)?this.s:(this[0]<<16)>>16; } // (protected) return x s.t. r^x < DV function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); } // (public) 0 if this == 0, 1 if this > 0 function bnSigNum() { if(this.s < 0) return -1; else if(this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0; else return 1; } // (protected) convert to radix string function bnpToRadix(b) { if(b == null) b = 10; if(this.signum() == 0 || b < 2 || b > 36) return "0"; var cs = this.chunkSize(b); var a = Math.pow(b,cs); var d = nbv(a), y = nbi(), z = nbi(), r = ""; this.divRemTo(d,y,z); while(y.signum() > 0) { r = (a+z.intValue()).toString(b).substr(1) + r; y.divRemTo(d,y,z); } return z.intValue().toString(b) + r; } // (protected) convert from radix string function bnpFromRadix(s,b) { this.fromInt(0); if(b == null) b = 10; var cs = this.chunkSize(b); var d = Math.pow(b,cs), mi = false, j = 0, w = 0; for(var i = 0; i < s.length; ++i) { var x = intAt(s,i); if(x < 0) { if(s.charAt(i) == "-" && this.signum() == 0) mi = true; continue; } w = b*w+x; if(++j >= cs) { this.dMultiply(d); this.dAddOffset(w,0); j = 0; w = 0; } } if(j > 0) { this.dMultiply(Math.pow(b,j)); this.dAddOffset(w,0); } if(mi) BigInteger.ZERO.subTo(this,this); } // (protected) alternate constructor function bnpFromNumber(a,b,c) { if("number" == typeof b) { // new BigInteger(int,int,RNG) if(a < 2) this.fromInt(1); else { this.fromNumber(a,c); if(!this.testBit(a-1)) // force MSB set this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this); if(this.isEven()) this.dAddOffset(1,0); // force odd while(!this.isProbablePrime(b)) { this.dAddOffset(2,0); if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this); } } } else { // new BigInteger(int,RNG) var x = new Array(), t = a&7; x.length = (a>>3)+1; b.nextBytes(x); if(t > 0) x[0] &= ((1< 0) { if(p < this.DB && (d = this[i]>>p) != (this.s&this.DM)>>p) r[k++] = d|(this.s<<(this.DB-p)); while(i >= 0) { if(p < 8) { d = (this[i]&((1<>(p+=this.DB-8); } else { d = (this[i]>>(p-=8))&0xff; if(p <= 0) { p += this.DB; --i; } } if((d&0x80) != 0) d |= -256; if(k == 0 && (this.s&0x80) != (d&0x80)) ++k; if(k > 0 || d != this.s) r[k++] = d; } } return r; } function bnEquals(a) { return(this.compareTo(a)==0); } function bnMin(a) { return(this.compareTo(a)<0)?this:a; } function bnMax(a) { return(this.compareTo(a)>0)?this:a; } // (protected) r = this op a (bitwise) function bnpBitwiseTo(a,op,r) { var i, f, m = Math.min(a.t,this.t); for(i = 0; i < m; ++i) r[i] = op(this[i],a[i]); if(a.t < this.t) { f = a.s&this.DM; for(i = m; i < this.t; ++i) r[i] = op(this[i],f); r.t = this.t; } else { f = this.s&this.DM; for(i = m; i < a.t; ++i) r[i] = op(f,a[i]); r.t = a.t; } r.s = op(this.s,a.s); r.clamp(); } // (public) this & a function op_and(x,y) { return x&y; } function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; } // (public) this | a function op_or(x,y) { return x|y; } function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; } // (public) this ^ a function op_xor(x,y) { return x^y; } function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; } // (public) this & ~a function op_andnot(x,y) { return x&~y; } function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; } // (public) ~this function bnNot() { var r = nbi(); for(var i = 0; i < this.t; ++i) r[i] = this.DM&~this[i]; r.t = this.t; r.s = ~this.s; return r; } // (public) this << n function bnShiftLeft(n) { var r = nbi(); if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r); return r; } // (public) this >> n function bnShiftRight(n) { var r = nbi(); if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r); return r; } // return index of lowest 1-bit in x, x < 2^31 function lbit(x) { if(x == 0) return -1; var r = 0; if((x&0xffff) == 0) { x >>= 16; r += 16; } if((x&0xff) == 0) { x >>= 8; r += 8; } if((x&0xf) == 0) { x >>= 4; r += 4; } if((x&3) == 0) { x >>= 2; r += 2; } if((x&1) == 0) ++r; return r; } // (public) returns index of lowest 1-bit (or -1 if none) function bnGetLowestSetBit() { for(var i = 0; i < this.t; ++i) if(this[i] != 0) return i*this.DB+lbit(this[i]); if(this.s < 0) return this.t*this.DB; return -1; } // return number of 1 bits in x function cbit(x) { var r = 0; while(x != 0) { x &= x-1; ++r; } return r; } // (public) return number of set bits function bnBitCount() { var r = 0, x = this.s&this.DM; for(var i = 0; i < this.t; ++i) r += cbit(this[i]^x); return r; } // (public) true iff nth bit is set function bnTestBit(n) { var j = Math.floor(n/this.DB); if(j >= this.t) return(this.s!=0); return((this[j]&(1<<(n%this.DB)))!=0); } // (protected) this op (1<>= this.DB; } if(a.t < this.t) { c += a.s; while(i < this.t) { c += this[i]; r[i++] = c&this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while(i < a.t) { c += a[i]; r[i++] = c&this.DM; c >>= this.DB; } c += a.s; } r.s = (c<0)?-1:0; if(c > 0) r[i++] = c; else if(c < -1) r[i++] = this.DV+c; r.t = i; r.clamp(); } // (public) this + a function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; } // (public) this - a function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; } // (public) this * a function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; } // (public) this^2 function bnSquare() { var r = nbi(); this.squareTo(r); return r; } // (public) this / a function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; } // (public) this % a function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } // (public) [this/a,this%a] function bnDivideAndRemainder(a) { var q = nbi(), r = nbi(); this.divRemTo(a,q,r); return new Array(q,r); } // (protected) this *= n, this >= 0, 1 < n < DV function bnpDMultiply(n) { this[this.t] = this.am(0,n-1,this,0,0,this.t); ++this.t; this.clamp(); } // (protected) this += n << w words, this >= 0 function bnpDAddOffset(n,w) { if(n == 0) return; while(this.t <= w) this[this.t++] = 0; this[w] += n; while(this[w] >= this.DV) { this[w] -= this.DV; if(++w >= this.t) this[this.t++] = 0; ++this[w]; } } // A "null" reducer function NullExp() {} function nNop(x) { return x; } function nMulTo(x,y,r) { x.multiplyTo(y,r); } function nSqrTo(x,r) { x.squareTo(r); } NullExp.prototype.convert = nNop; NullExp.prototype.revert = nNop; NullExp.prototype.mulTo = nMulTo; NullExp.prototype.sqrTo = nSqrTo; // (public) this^e function bnPow(e) { return this.exp(e,new NullExp()); } // (protected) r = lower n words of "this * a", a.t <= n // "this" should be the larger one if appropriate. function bnpMultiplyLowerTo(a,n,r) { var i = Math.min(this.t+a.t,n); r.s = 0; // assumes a,this >= 0 r.t = i; while(i > 0) r[--i] = 0; var j; for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t); for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i); r.clamp(); } // (protected) r = "this * a" without lower n words, n > 0 // "this" should be the larger one if appropriate. function bnpMultiplyUpperTo(a,n,r) { --n; var i = r.t = this.t+a.t-n; r.s = 0; // assumes a,this >= 0 while(--i >= 0) r[i] = 0; for(i = Math.max(n-this.t,0); i < a.t; ++i) r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n); r.clamp(); r.drShiftTo(1,r); } // Barrett modular reduction function Barrett(m) { // setup Barrett this.r2 = nbi(); this.q3 = nbi(); BigInteger.ONE.dlShiftTo(2*m.t,this.r2); this.mu = this.r2.divide(m); this.m = m; } function barrettConvert(x) { if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); else if(x.compareTo(this.m) < 0) return x; else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } } function barrettRevert(x) { return x; } // x = x mod m (HAC 14.42) function barrettReduce(x) { x.drShiftTo(this.m.t-1,this.r2); if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); x.subTo(this.r2,x); while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } // r = x^2 mod m; x != r function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } // r = x*y mod m; x,y != r function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } Barrett.prototype.convert = barrettConvert; Barrett.prototype.revert = barrettRevert; Barrett.prototype.reduce = barrettReduce; Barrett.prototype.mulTo = barrettMulTo; Barrett.prototype.sqrTo = barrettSqrTo; // (public) this^e % m (HAC 14.85) function bnModPow(e,m) { var i = e.bitLength(), k, r = nbv(1), z; if(i <= 0) return r; else if(i < 18) k = 1; else if(i < 48) k = 3; else if(i < 144) k = 4; else if(i < 768) k = 5; else k = 6; if(i < 8) z = new Classic(m); else if(m.isEven()) z = new Barrett(m); else z = new Montgomery(m); // precomputation var g = new Array(), n = 3, k1 = k-1, km = (1< 1) { var g2 = nbi(); z.sqrTo(g[1],g2); while(n <= km) { g[n] = nbi(); z.mulTo(g2,g[n-2],g[n]); n += 2; } } var j = e.t-1, w, is1 = true, r2 = nbi(), t; i = nbits(e[j])-1; while(j >= 0) { if(i >= k1) w = (e[j]>>(i-k1))&km; else { w = (e[j]&((1<<(i+1))-1))<<(k1-i); if(j > 0) w |= e[j-1]>>(this.DB+i-k1); } n = k; while((w&1) == 0) { w >>= 1; --n; } if((i -= n) < 0) { i += this.DB; --j; } if(is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } z.mulTo(r2,g[w],r); } while(j >= 0 && (e[j]&(1< 0) { x.rShiftTo(g,x); y.rShiftTo(g,y); } while(x.signum() > 0) { if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); if(x.compareTo(y) >= 0) { x.subTo(y,x); x.rShiftTo(1,x); } else { y.subTo(x,y); y.rShiftTo(1,y); } } if(g > 0) y.lShiftTo(g,y); return y; } // (protected) this % n, n < 2^26 function bnpModInt(n) { if(n <= 0) return 0; var d = this.DV%n, r = (this.s<0)?n-1:0; if(this.t > 0) if(d == 0) r = this[0]%n; else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n; return r; } // (public) 1/this % m (HAC 14.61) function bnModInverse(m) { var ac = m.isEven(); if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; var u = m.clone(), v = this.clone(); var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); while(u.signum() != 0) { while(u.isEven()) { u.rShiftTo(1,u); if(ac) { if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } a.rShiftTo(1,a); } else if(!b.isEven()) b.subTo(m,b); b.rShiftTo(1,b); } while(v.isEven()) { v.rShiftTo(1,v); if(ac) { if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } c.rShiftTo(1,c); } else if(!d.isEven()) d.subTo(m,d); d.rShiftTo(1,d); } if(u.compareTo(v) >= 0) { u.subTo(v,u); if(ac) a.subTo(c,a); b.subTo(d,b); } else { v.subTo(u,v); if(ac) c.subTo(a,c); d.subTo(b,d); } } if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; if(d.compareTo(m) >= 0) return d.subtract(m); if(d.signum() < 0) d.addTo(m,d); else return d; if(d.signum() < 0) return d.add(m); else return d; } var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997]; var lplim = (1<<26)/lowprimes[lowprimes.length-1]; // (public) test primality with certainty >= 1-.5^t function bnIsProbablePrime(t) { var i, x = this.abs(); if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) { for(i = 0; i < lowprimes.length; ++i) if(x[0] == lowprimes[i]) return true; return false; } if(x.isEven()) return false; i = 1; while(i < lowprimes.length) { var m = lowprimes[i], j = i+1; while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; m = x.modInt(m); while(i < j) if(m%lowprimes[i++] == 0) return false; } return x.millerRabin(t); } // (protected) true if probably prime (HAC 4.24, Miller-Rabin) function bnpMillerRabin(t) { var n1 = this.subtract(BigInteger.ONE); var k = n1.getLowestSetBit(); if(k <= 0) return false; var r = n1.shiftRight(k); t = (t+1)>>1; if(t > lowprimes.length) t = lowprimes.length; var a = nbi(); for(var i = 0; i < t; ++i) { //Pick bases at random, instead of starting at 2 a.fromInt(lowprimes[Math.floor(Math.random()*lowprimes.length)]); var y = a.modPow(r,this); if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { var j = 1; while(j++ < k && y.compareTo(n1) != 0) { y = y.modPowInt(2,this); if(y.compareTo(BigInteger.ONE) == 0) return false; } if(y.compareTo(n1) != 0) return false; } } return true; } // protected BigInteger.prototype.chunkSize = bnpChunkSize; BigInteger.prototype.toRadix = bnpToRadix; BigInteger.prototype.fromRadix = bnpFromRadix; BigInteger.prototype.fromNumber = bnpFromNumber; BigInteger.prototype.bitwiseTo = bnpBitwiseTo; BigInteger.prototype.changeBit = bnpChangeBit; BigInteger.prototype.addTo = bnpAddTo; BigInteger.prototype.dMultiply = bnpDMultiply; BigInteger.prototype.dAddOffset = bnpDAddOffset; BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; BigInteger.prototype.modInt = bnpModInt; BigInteger.prototype.millerRabin = bnpMillerRabin; // public BigInteger.prototype.clone = bnClone; BigInteger.prototype.intValue = bnIntValue; BigInteger.prototype.byteValue = bnByteValue; BigInteger.prototype.shortValue = bnShortValue; BigInteger.prototype.signum = bnSigNum; BigInteger.prototype.toByteArray = bnToByteArray; BigInteger.prototype.equals = bnEquals; BigInteger.prototype.min = bnMin; BigInteger.prototype.max = bnMax; BigInteger.prototype.and = bnAnd; BigInteger.prototype.or = bnOr; BigInteger.prototype.xor = bnXor; BigInteger.prototype.andNot = bnAndNot; BigInteger.prototype.not = bnNot; BigInteger.prototype.shiftLeft = bnShiftLeft; BigInteger.prototype.shiftRight = bnShiftRight; BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; BigInteger.prototype.bitCount = bnBitCount; BigInteger.prototype.testBit = bnTestBit; BigInteger.prototype.setBit = bnSetBit; BigInteger.prototype.clearBit = bnClearBit; BigInteger.prototype.flipBit = bnFlipBit; BigInteger.prototype.add = bnAdd; BigInteger.prototype.subtract = bnSubtract; BigInteger.prototype.multiply = bnMultiply; BigInteger.prototype.divide = bnDivide; BigInteger.prototype.remainder = bnRemainder; BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; BigInteger.prototype.modPow = bnModPow; BigInteger.prototype.modInverse = bnModInverse; BigInteger.prototype.pow = bnPow; BigInteger.prototype.gcd = bnGCD; BigInteger.prototype.isProbablePrime = bnIsProbablePrime; // JSBN-specific extension BigInteger.prototype.square = bnSquare; // Expose the Barrett function BigInteger.prototype.Barrett = Barrett // BigInteger interfaces not implemented in jsbn: // BigInteger(int signum, byte[] magnitude) // double doubleValue() // float floatValue() // int hashCode() // long longValue() // static BigInteger valueOf(long val) // Random number generator - requires a PRNG backend, e.g. prng4.js // For best results, put code like // // in your main HTML document. var rng_state; var rng_pool; var rng_pptr; // Mix in a 32-bit integer into the pool function rng_seed_int(x) { rng_pool[rng_pptr++] ^= x & 255; rng_pool[rng_pptr++] ^= (x >> 8) & 255; rng_pool[rng_pptr++] ^= (x >> 16) & 255; rng_pool[rng_pptr++] ^= (x >> 24) & 255; if(rng_pptr >= rng_psize) rng_pptr -= rng_psize; } // Mix in the current time (w/milliseconds) into the pool function rng_seed_time() { rng_seed_int(new Date().getTime()); } // Initialize the pool with junk if needed. if(rng_pool == null) { rng_pool = new Array(); rng_pptr = 0; var t; if(typeof window !== "undefined" && window.crypto) { if (window.crypto.getRandomValues) { // Use webcrypto if available var ua = new Uint8Array(32); window.crypto.getRandomValues(ua); for(t = 0; t < 32; ++t) rng_pool[rng_pptr++] = ua[t]; } else if(navigator.appName == "Netscape" && navigator.appVersion < "5") { // Extract entropy (256 bits) from NS4 RNG if available var z = window.crypto.random(32); for(t = 0; t < z.length; ++t) rng_pool[rng_pptr++] = z.charCodeAt(t) & 255; } } while(rng_pptr < rng_psize) { // extract some randomness from Math.random() t = Math.floor(65536 * Math.random()); rng_pool[rng_pptr++] = t >>> 8; rng_pool[rng_pptr++] = t & 255; } rng_pptr = 0; rng_seed_time(); //rng_seed_int(window.screenX); //rng_seed_int(window.screenY); } function rng_get_byte() { if(rng_state == null) { rng_seed_time(); rng_state = prng_newstate(); rng_state.init(rng_pool); for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) rng_pool[rng_pptr] = 0; rng_pptr = 0; //rng_pool = null; } // TODO: allow reseeding after first request return rng_state.next(); } function rng_get_bytes(ba) { var i; for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte(); } function SecureRandom() {} SecureRandom.prototype.nextBytes = rng_get_bytes; // prng4.js - uses Arcfour as a PRNG function Arcfour() { this.i = 0; this.j = 0; this.S = new Array(); } // Initialize arcfour context from key, an array of ints, each from [0..255] function ARC4init(key) { var i, j, t; for(i = 0; i < 256; ++i) this.S[i] = i; j = 0; for(i = 0; i < 256; ++i) { j = (j + this.S[i] + key[i % key.length]) & 255; t = this.S[i]; this.S[i] = this.S[j]; this.S[j] = t; } this.i = 0; this.j = 0; } function ARC4next() { var t; this.i = (this.i + 1) & 255; this.j = (this.j + this.S[this.i]) & 255; t = this.S[this.i]; this.S[this.i] = this.S[this.j]; this.S[this.j] = t; return this.S[(t + this.S[this.i]) & 255]; } Arcfour.prototype.init = ARC4init; Arcfour.prototype.next = ARC4next; // Plug in your RNG constructor here function prng_newstate() { return new Arcfour(); } // Pool size must be a multiple of 4 and greater than 32. // An array of bytes the size of the pool will be passed to init() var rng_psize = 256; if (typeof exports !== 'undefined') { exports = module.exports = { default: BigInteger, BigInteger: BigInteger, SecureRandom: SecureRandom, }; } else { this.jsbn = { BigInteger: BigInteger, SecureRandom: SecureRandom }; } }).call(this); PK ~\Hjsbn/example.htmlnu[ PK ~\R>>brace-expansion/package.jsonnu[{ "_id": "brace-expansion@2.0.1", "_inBundle": true, "_location": "/npm/brace-expansion", "_phantomChildren": {}, "_requiredBy": [ "/npm/minimatch" ], "author": { "name": "Julian Gruber", "email": "mail@juliangruber.com", "url": "http://juliangruber.com" }, "bugs": { "url": "https://github.com/juliangruber/brace-expansion/issues" }, "dependencies": { "balanced-match": "^1.0.0" }, "description": "Brace expansion as known from sh/bash", "devDependencies": { "@c4312/matcha": "^1.3.1", "tape": "^4.6.0" }, "homepage": "https://github.com/juliangruber/brace-expansion", "keywords": [], "license": "MIT", "main": "index.js", "name": "brace-expansion", "repository": { "type": "git", "url": "git://github.com/juliangruber/brace-expansion.git" }, "scripts": { "bench": "matcha test/perf/bench.js", "gentest": "bash test/generate.sh", "test": "tape test/*.js" }, "testling": { "files": "test/*.js", "browsers": [ "ie/8..latest", "firefox/20..latest", "firefox/nightly", "chrome/25..latest", "chrome/canary", "opera/12..latest", "opera/next", "safari/5.1..latest", "ipad/6.0..latest", "iphone/6.0..latest", "android-browser/4.2..latest" ] }, "version": "2.0.1" } PK ~\ϗHHbrace-expansion/LICENSEnu[MIT License Copyright (c) 2013 Julian Gruber Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\:Ebrace-expansion/index.jsnu[var balanced = require('balanced-match'); module.exports = expandTop; var escSlash = '\0SLASH'+Math.random()+'\0'; var escOpen = '\0OPEN'+Math.random()+'\0'; var escClose = '\0CLOSE'+Math.random()+'\0'; var escComma = '\0COMMA'+Math.random()+'\0'; var escPeriod = '\0PERIOD'+Math.random()+'\0'; function numeric(str) { return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0); } function escapeBraces(str) { return str.split('\\\\').join(escSlash) .split('\\{').join(escOpen) .split('\\}').join(escClose) .split('\\,').join(escComma) .split('\\.').join(escPeriod); } function unescapeBraces(str) { return str.split(escSlash).join('\\') .split(escOpen).join('{') .split(escClose).join('}') .split(escComma).join(',') .split(escPeriod).join('.'); } // Basically just str.split(","), but handling cases // where we have nested braced sections, which should be // treated as individual members, like {a,{b,c},d} function parseCommaParts(str) { if (!str) return ['']; var parts = []; var m = balanced('{', '}', str); if (!m) return str.split(','); var pre = m.pre; var body = m.body; var post = m.post; var p = pre.split(','); p[p.length-1] += '{' + body + '}'; var postParts = parseCommaParts(post); if (post.length) { p[p.length-1] += postParts.shift(); p.push.apply(p, postParts); } parts.push.apply(parts, p); return parts; } function expandTop(str) { if (!str) return []; // I don't know why Bash 4.3 does this, but it does. // Anything starting with {} will have the first two bytes preserved // but *only* at the top level, so {},a}b will not expand to anything, // but a{},b}c will be expanded to [a}c,abc]. // One could argue that this is a bug in Bash, but since the goal of // this module is to match Bash's rules, we escape a leading {} if (str.substr(0, 2) === '{}') { str = '\\{\\}' + str.substr(2); } return expand(escapeBraces(str), true).map(unescapeBraces); } function embrace(str) { return '{' + str + '}'; } function isPadded(el) { return /^-?0\d/.test(el); } function lte(i, y) { return i <= y; } function gte(i, y) { return i >= y; } function expand(str, isTop) { var expansions = []; var m = balanced('{', '}', str); if (!m) return [str]; // no need to expand pre, since it is guaranteed to be free of brace-sets var pre = m.pre; var post = m.post.length ? expand(m.post, false) : ['']; if (/\$$/.test(m.pre)) { for (var k = 0; k < post.length; k++) { var expansion = pre+ '{' + m.body + '}' + post[k]; expansions.push(expansion); } } else { var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); var isSequence = isNumericSequence || isAlphaSequence; var isOptions = m.body.indexOf(',') >= 0; if (!isSequence && !isOptions) { // {a},b} if (m.post.match(/,.*\}/)) { str = m.pre + '{' + m.body + escClose + m.post; return expand(str); } return [str]; } var n; if (isSequence) { n = m.body.split(/\.\./); } else { n = parseCommaParts(m.body); if (n.length === 1) { // x{{a,b}}y ==> x{a}y x{b}y n = expand(n[0], false).map(embrace); if (n.length === 1) { return post.map(function(p) { return m.pre + n[0] + p; }); } } } // at this point, n is the parts, and we know it's not a comma set // with a single entry. var N; if (isSequence) { var x = numeric(n[0]); var y = numeric(n[1]); var width = Math.max(n[0].length, n[1].length) var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1; var test = lte; var reverse = y < x; if (reverse) { incr *= -1; test = gte; } var pad = n.some(isPadded); N = []; for (var i = x; test(i, y); i += incr) { var c; if (isAlphaSequence) { c = String.fromCharCode(i); if (c === '\\') c = ''; } else { c = String(i); if (pad) { var need = width - c.length; if (need > 0) { var z = new Array(need + 1).join('0'); if (i < 0) c = '-' + z + c.slice(1); else c = z + c; } } } N.push(c); } } else { N = []; for (var j = 0; j < n.length; j++) { N.push.apply(N, expand(n[j], false)); } } for (var j = 0; j < N.length; j++) { for (var k = 0; k < post.length; k++) { var expansion = pre + N[j] + post[k]; if (!isTop || isSequence || expansion) expansions.push(expansion); } } } return expansions; } PK ~\ string-width/package.jsonnu[{ "_id": "string-width@4.2.3", "_inBundle": true, "_location": "/npm/string-width", "_phantomChildren": {}, "_requiredBy": [ "/npm/cli-columns", "/npm/wrap-ansi-cjs" ], "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "bugs": { "url": "https://github.com/sindresorhus/string-width/issues" }, "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" }, "description": "Get the visual width of a string - the number of columns required to display it", "devDependencies": { "ava": "^1.4.1", "tsd": "^0.7.1", "xo": "^0.24.0" }, "engines": { "node": ">=8" }, "files": [ "index.js", "index.d.ts" ], "homepage": "https://github.com/sindresorhus/string-width#readme", "keywords": [ "string", "character", "unicode", "width", "visual", "column", "columns", "fullwidth", "full-width", "full", "ansi", "escape", "codes", "cli", "command-line", "terminal", "console", "cjk", "chinese", "japanese", "korean", "fixed-width" ], "license": "MIT", "name": "string-width", "repository": { "type": "git", "url": "git+https://github.com/sindresorhus/string-width.git" }, "scripts": { "test": "xo && ava && tsd" }, "version": "4.2.3" } PK ~\Ikstring-width/index.jsnu['use strict'; const stripAnsi = require('strip-ansi'); const isFullwidthCodePoint = require('is-fullwidth-code-point'); const emojiRegex = require('emoji-regex'); const stringWidth = string => { if (typeof string !== 'string' || string.length === 0) { return 0; } string = stripAnsi(string); if (string.length === 0) { return 0; } string = string.replace(emojiRegex(), ' '); let width = 0; for (let i = 0; i < string.length; i++) { const code = string.codePointAt(i); // Ignore control characters if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { continue; } // Ignore combining characters if (code >= 0x300 && code <= 0x36F) { continue; } // Surrogates if (code > 0xFFFF) { i++; } width += isFullwidthCodePoint(code) ? 2 : 1; } return width; }; module.exports = stringWidth; // TODO: remove this in the next major version module.exports.default = stringWidth; PK ~\E}UUstring-width/licensenu[MIT License Copyright (c) Sindre Sorhus (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\Ftnpm-pick-manifest/package.jsonnu[{ "_id": "npm-pick-manifest@9.0.1", "_inBundle": true, "_location": "/npm/npm-pick-manifest", "_phantomChildren": {}, "_requiredBy": [ "/npm", "/npm/@npmcli/arborist", "/npm/@npmcli/git", "/npm/pacote" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/npm-pick-manifest/issues" }, "dependencies": { "npm-install-checks": "^6.0.0", "npm-normalize-package-bin": "^3.0.0", "npm-package-arg": "^11.0.0", "semver": "^7.3.5" }, "description": "Resolves a matching manifest from a package metadata document according to standard npm semver resolution rules.", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.22.0", "tap": "^16.0.1" }, "engines": { "node": "^16.14.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/npm-pick-manifest#readme", "keywords": [ "npm", "semver", "package manager" ], "license": "ISC", "main": "./lib", "name": "npm-pick-manifest", "repository": { "type": "git", "url": "git+https://github.com/npm/npm-pick-manifest.git" }, "scripts": { "coverage": "tap", "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "check-coverage": true, "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.22.0", "publish": true }, "version": "9.0.1" } PK ~\mnpm-pick-manifest/lib/index.jsnu['use strict' const npa = require('npm-package-arg') const semver = require('semver') const { checkEngine } = require('npm-install-checks') const normalizeBin = require('npm-normalize-package-bin') const engineOk = (manifest, npmVersion, nodeVersion) => { try { checkEngine(manifest, npmVersion, nodeVersion) return true } catch (_) { return false } } const isBefore = (verTimes, ver, time) => !verTimes || !verTimes[ver] || Date.parse(verTimes[ver]) <= time const avoidSemverOpt = { includePrerelease: true, loose: true } const shouldAvoid = (ver, avoid) => avoid && semver.satisfies(ver, avoid, avoidSemverOpt) const decorateAvoid = (result, avoid) => result && shouldAvoid(result.version, avoid) ? { ...result, _shouldAvoid: true } : result const pickManifest = (packument, wanted, opts) => { const { defaultTag = 'latest', before = null, nodeVersion = process.version, npmVersion = null, includeStaged = false, avoid = null, avoidStrict = false, } = opts const { name, time: verTimes } = packument const versions = packument.versions || {} if (avoidStrict) { const looseOpts = { ...opts, avoidStrict: false, } const result = pickManifest(packument, wanted, looseOpts) if (!result || !result._shouldAvoid) { return result } const caret = pickManifest(packument, `^${result.version}`, looseOpts) if (!caret || !caret._shouldAvoid) { return { ...caret, _outsideDependencyRange: true, _isSemVerMajor: false, } } const star = pickManifest(packument, '*', looseOpts) if (!star || !star._shouldAvoid) { return { ...star, _outsideDependencyRange: true, _isSemVerMajor: true, } } throw Object.assign(new Error(`No avoidable versions for ${name}`), { code: 'ETARGET', name, wanted, avoid, before, versions: Object.keys(versions), }) } const staged = (includeStaged && packument.stagedVersions && packument.stagedVersions.versions) || {} const restricted = (packument.policyRestrictions && packument.policyRestrictions.versions) || {} const time = before && verTimes ? +(new Date(before)) : Infinity const spec = npa.resolve(name, wanted || defaultTag) const type = spec.type const distTags = packument['dist-tags'] || {} if (type !== 'tag' && type !== 'version' && type !== 'range') { throw new Error('Only tag, version, and range are supported') } // if the type is 'tag', and not just the implicit default, then it must // be that exactly, or nothing else will do. if (wanted && type === 'tag') { const ver = distTags[wanted] // if the version in the dist-tags is before the before date, then // we use that. Otherwise, we get the highest precedence version // prior to the dist-tag. if (isBefore(verTimes, ver, time)) { return decorateAvoid(versions[ver] || staged[ver] || restricted[ver], avoid) } else { return pickManifest(packument, `<=${ver}`, opts) } } // similarly, if a specific version, then only that version will do if (wanted && type === 'version') { const ver = semver.clean(wanted, { loose: true }) const mani = versions[ver] || staged[ver] || restricted[ver] return isBefore(verTimes, ver, time) ? decorateAvoid(mani, avoid) : null } // ok, sort based on our heuristics, and pick the best fit const range = type === 'range' ? wanted : '*' // if the range is *, then we prefer the 'latest' if available // but skip this if it should be avoided, in that case we have // to try a little harder. const defaultVer = distTags[defaultTag] if (defaultVer && (range === '*' || semver.satisfies(defaultVer, range, { loose: true })) && !shouldAvoid(defaultVer, avoid)) { const mani = versions[defaultVer] if (mani && isBefore(verTimes, defaultVer, time)) { return mani } } // ok, actually have to sort the list and take the winner const allEntries = Object.entries(versions) .concat(Object.entries(staged)) .concat(Object.entries(restricted)) .filter(([ver]) => isBefore(verTimes, ver, time)) if (!allEntries.length) { throw Object.assign(new Error(`No versions available for ${name}`), { code: 'ENOVERSIONS', name, type, wanted, before, versions: Object.keys(versions), }) } const sortSemverOpt = { loose: true } const entries = allEntries.filter(([ver]) => semver.satisfies(ver, range, { loose: true })) .sort((a, b) => { const [vera, mania] = a const [verb, manib] = b const notavoida = !shouldAvoid(vera, avoid) const notavoidb = !shouldAvoid(verb, avoid) const notrestra = !restricted[a] const notrestrb = !restricted[b] const notstagea = !staged[a] const notstageb = !staged[b] const notdepra = !mania.deprecated const notdeprb = !manib.deprecated const enginea = engineOk(mania, npmVersion, nodeVersion) const engineb = engineOk(manib, npmVersion, nodeVersion) // sort by: // - not an avoided version // - not restricted // - not staged // - not deprecated and engine ok // - engine ok // - not deprecated // - semver return (notavoidb - notavoida) || (notrestrb - notrestra) || (notstageb - notstagea) || ((notdeprb && engineb) - (notdepra && enginea)) || (engineb - enginea) || (notdeprb - notdepra) || semver.rcompare(vera, verb, sortSemverOpt) }) return decorateAvoid(entries[0] && entries[0][1], avoid) } module.exports = (packument, wanted, opts = {}) => { const mani = pickManifest(packument, wanted, opts) const picked = mani && normalizeBin(mani) const policyRestrictions = packument.policyRestrictions const restricted = (policyRestrictions && policyRestrictions.versions) || {} if (picked && !restricted[picked.version]) { return picked } const { before = null, defaultTag = 'latest' } = opts const bstr = before ? new Date(before).toLocaleString() : '' const { name } = packument const pckg = `${name}@${wanted}` + (before ? ` with a date before ${bstr}` : '') const isForbidden = picked && !!restricted[picked.version] const polMsg = isForbidden ? policyRestrictions.message : '' const msg = !isForbidden ? `No matching version found for ${pckg}.` : `Could not download ${pckg} due to policy violations:\n${polMsg}` const code = isForbidden ? 'E403' : 'ETARGET' throw Object.assign(new Error(msg), { code, type: npa.resolve(packument.name, wanted).type, wanted, versions: Object.keys(packument.versions ?? {}), name, distTags: packument['dist-tags'], defaultTag, }) } PK ~\ gnpm-pick-manifest/LICENSE.mdnu[ISC License Copyright (c) npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE COPYRIGHT HOLDER DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\e(spdx-exceptions/package.jsonnu[{ "_id": "spdx-exceptions@2.5.0", "_inBundle": true, "_location": "/npm/spdx-exceptions", "_phantomChildren": {}, "_requiredBy": [ "/npm/spdx-correct/spdx-expression-parse", "/npm/spdx-expression-parse", "/npm/validate-npm-package-license/spdx-expression-parse" ], "author": { "name": "The Linux Foundation" }, "bugs": { "url": "https://github.com/kemitchell/spdx-exceptions.json/issues" }, "contributors": [ { "name": "Kyle E. Mitchell", "email": "kyle@kemitchell.com", "url": "https://kemitchell.com/" } ], "description": "list of SPDX standard license exceptions", "files": [ "index.json", "deprecated.json" ], "homepage": "https://github.com/kemitchell/spdx-exceptions.json#readme", "license": "CC-BY-3.0", "name": "spdx-exceptions", "repository": { "type": "git", "url": "git+https://github.com/kemitchell/spdx-exceptions.json.git" }, "scripts": { "build": "node build.js", "latest": "node latest.js" }, "version": "2.5.0" } PK ~\o™spdx-exceptions/deprecated.jsonnu[[ "Nokia-Qt-exception-1.1" ] PK ~\X4spdx-exceptions/index.jsonnu[[ "389-exception", "Asterisk-exception", "Autoconf-exception-2.0", "Autoconf-exception-3.0", "Autoconf-exception-generic", "Autoconf-exception-generic-3.0", "Autoconf-exception-macro", "Bison-exception-1.24", "Bison-exception-2.2", "Bootloader-exception", "Classpath-exception-2.0", "CLISP-exception-2.0", "cryptsetup-OpenSSL-exception", "DigiRule-FOSS-exception", "eCos-exception-2.0", "Fawkes-Runtime-exception", "FLTK-exception", "fmt-exception", "Font-exception-2.0", "freertos-exception-2.0", "GCC-exception-2.0", "GCC-exception-2.0-note", "GCC-exception-3.1", "Gmsh-exception", "GNAT-exception", "GNOME-examples-exception", "GNU-compiler-exception", "gnu-javamail-exception", "GPL-3.0-interface-exception", "GPL-3.0-linking-exception", "GPL-3.0-linking-source-exception", "GPL-CC-1.0", "GStreamer-exception-2005", "GStreamer-exception-2008", "i2p-gpl-java-exception", "KiCad-libraries-exception", "LGPL-3.0-linking-exception", "libpri-OpenH323-exception", "Libtool-exception", "Linux-syscall-note", "LLGPL", "LLVM-exception", "LZMA-exception", "mif-exception", "OCaml-LGPL-linking-exception", "OCCT-exception-1.0", "OpenJDK-assembly-exception-1.0", "openvpn-openssl-exception", "PS-or-PDF-font-exception-20170817", "QPL-1.0-INRIA-2004-exception", "Qt-GPL-exception-1.0", "Qt-LGPL-exception-1.1", "Qwt-exception-1.0", "SANE-exception", "SHL-2.0", "SHL-2.1", "stunnel-exception", "SWI-exception", "Swift-exception", "Texinfo-exception", "u-boot-exception-2.0", "UBDL-exception", "Universal-FOSS-exception-1.0", "vsftpd-openssl-exception", "WxWindows-exception-3.1", "x11vnc-openssl-exception" ] PK ~\.,npm-install-checks/package.jsonnu[{ "_id": "npm-install-checks@6.3.0", "_inBundle": true, "_location": "/npm/npm-install-checks", "_phantomChildren": {}, "_requiredBy": [ "/npm", "/npm/@npmcli/arborist", "/npm/npm-pick-manifest" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/npm-install-checks/issues" }, "dependencies": { "semver": "^7.1.1" }, "description": "Check the engines and platform fields in package.json", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.19.0", "tap": "^16.0.1" }, "engines": { "node": "^14.17.0 || ^16.13.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/npm-install-checks#readme", "keywords": [ "npm,", "install" ], "license": "BSD-2-Clause", "main": "lib/index.js", "name": "npm-install-checks", "repository": { "type": "git", "url": "git+https://github.com/npm/npm-install-checks.git" }, "scripts": { "lint": "eslint \"**/*.js\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.19.0", "publish": "true" }, "version": "6.3.0" } PK ~\Eʥ3 npm-install-checks/lib/index.jsnu[const semver = require('semver') const checkEngine = (target, npmVer, nodeVer, force = false) => { const nodev = force ? null : nodeVer const eng = target.engines const opt = { includePrerelease: true } if (!eng) { return } const nodeFail = nodev && eng.node && !semver.satisfies(nodev, eng.node, opt) const npmFail = npmVer && eng.npm && !semver.satisfies(npmVer, eng.npm, opt) if (nodeFail || npmFail) { throw Object.assign(new Error('Unsupported engine'), { pkgid: target._id, current: { node: nodeVer, npm: npmVer }, required: eng, code: 'EBADENGINE', }) } } const isMusl = (file) => file.includes('libc.musl-') || file.includes('ld-musl-') const checkPlatform = (target, force = false, environment = {}) => { if (force) { return } const platform = environment.os || process.platform const arch = environment.cpu || process.arch const osOk = target.os ? checkList(platform, target.os) : true const cpuOk = target.cpu ? checkList(arch, target.cpu) : true let libcOk = true let libcFamily = null if (target.libc) { // libc checks only work in linux, any value is a failure if we aren't if (environment.libc) { libcOk = checkList(environment.libc, target.libc) } else if (platform !== 'linux') { libcOk = false } else { const report = process.report.getReport() if (report.header?.glibcVersionRuntime) { libcFamily = 'glibc' } else if (Array.isArray(report.sharedObjects) && report.sharedObjects.some(isMusl)) { libcFamily = 'musl' } libcOk = libcFamily ? checkList(libcFamily, target.libc) : false } } if (!osOk || !cpuOk || !libcOk) { throw Object.assign(new Error('Unsupported platform'), { pkgid: target._id, current: { os: platform, cpu: arch, libc: libcFamily, }, required: { os: target.os, cpu: target.cpu, libc: target.libc, }, code: 'EBADPLATFORM', }) } } const checkList = (value, list) => { if (typeof list === 'string') { list = [list] } if (list.length === 1 && list[0] === 'any') { return true } // match none of the negated values, and at least one of the // non-negated values, if any are present. let negated = 0 let match = false for (const entry of list) { const negate = entry.charAt(0) === '!' const test = negate ? entry.slice(1) : entry if (negate) { negated++ if (value === test) { return false } } else { match = match || value === test } } return match || negated === list.length } module.exports = { checkEngine, checkPlatform, } PK ~\=e55npm-install-checks/LICENSEnu[Copyright (c) Robert Kowalski and Isaac Z. Schlueter ("Authors") All rights reserved. The BSD License Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. PK ~\I@@minipass-collect/package.jsonnu[{ "_id": "minipass-collect@2.0.1", "_inBundle": true, "_location": "/npm/minipass-collect", "_phantomChildren": {}, "_requiredBy": [ "/npm/cacache" ], "author": { "name": "Isaac Z. Schlueter", "email": "i@izs.me", "url": "https://izs.me" }, "bugs": { "url": "https://github.com/isaacs/minipass-collect/issues" }, "dependencies": { "minipass": "^7.0.3" }, "description": "A Minipass stream that collects all the data into a single chunk", "devDependencies": { "tap": "^16.3.8" }, "engines": { "node": ">=16 || 14 >=14.17" }, "files": [ "index.js" ], "homepage": "https://github.com/isaacs/minipass-collect#readme", "license": "ISC", "name": "minipass-collect", "repository": { "type": "git", "url": "git+https://github.com/isaacs/minipass-collect.git" }, "scripts": { "postversion": "npm publish", "prepublishOnly": "git push origin --follow-tags", "preversion": "npm test", "snap": "tap", "test": "tap" }, "tap": { "check-coverage": true }, "version": "2.0.1" } PK ~\minipass-collect/LICENSEnu[The ISC License Copyright (c) 2019-2023 Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\&minipass-collect/index.jsnu[const { Minipass } = require('minipass') const _data = Symbol('_data') const _length = Symbol('_length') class Collect extends Minipass { constructor (options) { super(options) this[_data] = [] this[_length] = 0 } write (chunk, encoding, cb) { if (typeof encoding === 'function') cb = encoding, encoding = 'utf8' if (!encoding) encoding = 'utf8' const c = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding) this[_data].push(c) this[_length] += c.length if (cb) cb() return true } end (chunk, encoding, cb) { if (typeof chunk === 'function') cb = chunk, chunk = null if (typeof encoding === 'function') cb = encoding, encoding = 'utf8' if (chunk) this.write(chunk, encoding) const result = Buffer.concat(this[_data], this[_length]) super.write(result) return super.end(cb) } } module.exports = Collect // it would be possible to DRY this a bit by doing something like // this.collector = new Collect() and listening on its data event, // but it's not much code, and we may as well save the extra obj class CollectPassThrough extends Minipass { constructor (options) { super(options) this[_data] = [] this[_length] = 0 } write (chunk, encoding, cb) { if (typeof encoding === 'function') cb = encoding, encoding = 'utf8' if (!encoding) encoding = 'utf8' const c = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding) this[_data].push(c) this[_length] += c.length return super.write(chunk, encoding, cb) } end (chunk, encoding, cb) { if (typeof chunk === 'function') cb = chunk, chunk = null if (typeof encoding === 'function') cb = encoding, encoding = 'utf8' if (chunk) this.write(chunk, encoding) const result = Buffer.concat(this[_data], this[_length]) this.emit('collect', result) return super.end(cb) } } module.exports.PassThrough = CollectPassThrough PK ~\o#]]sigstore/package.jsonnu[{ "_id": "sigstore@2.3.1", "_inBundle": true, "_location": "/npm/sigstore", "_phantomChildren": {}, "_requiredBy": [ "/npm/libnpmpublish", "/npm/pacote" ], "author": { "name": "bdehamer@github.com" }, "bugs": { "url": "https://github.com/sigstore/sigstore-js/issues" }, "dependencies": { "@sigstore/bundle": "^2.3.2", "@sigstore/core": "^1.0.0", "@sigstore/protobuf-specs": "^0.3.2", "@sigstore/sign": "^2.3.2", "@sigstore/tuf": "^2.3.4", "@sigstore/verify": "^1.2.1" }, "description": "code-signing for npm packages", "devDependencies": { "@sigstore/jest": "^0.0.0", "@sigstore/mock": "^0.7.4", "@sigstore/rekor-types": "^2.0.0", "@tufjs/repo-mock": "^2.0.1", "@types/make-fetch-happen": "^10.0.4" }, "engines": { "node": "^16.14.0 || >=18.0.0" }, "files": [ "dist", "store" ], "homepage": "https://github.com/sigstore/sigstore-js/tree/main/packages/client#readme", "license": "Apache-2.0", "main": "dist/index.js", "name": "sigstore", "publishConfig": { "provenance": true }, "repository": { "type": "git", "url": "git+https://github.com/sigstore/sigstore-js.git" }, "scripts": { "build": "tsc --build", "clean": "shx rm -rf dist *.tsbuildinfo", "test": "jest" }, "types": "dist/index.d.ts", "version": "2.3.1" } PK ~\"KW,W,sigstore/LICENSEnu[ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2023 The Sigstore Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. PK ~\k Osigstore/dist/config.jsnu["use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createVerificationPolicy = exports.createKeyFinder = exports.createBundleBuilder = exports.DEFAULT_TIMEOUT = exports.DEFAULT_RETRY = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ const core_1 = require("@sigstore/core"); const sign_1 = require("@sigstore/sign"); const verify_1 = require("@sigstore/verify"); exports.DEFAULT_RETRY = { retries: 2 }; exports.DEFAULT_TIMEOUT = 5000; function createBundleBuilder(bundleType, options) { const bundlerOptions = { signer: initSigner(options), witnesses: initWitnesses(options), }; switch (bundleType) { case 'messageSignature': return new sign_1.MessageSignatureBundleBuilder(bundlerOptions); case 'dsseEnvelope': return new sign_1.DSSEBundleBuilder(bundlerOptions); } } exports.createBundleBuilder = createBundleBuilder; // Translates the public KeySelector type into the KeyFinderFunc type needed by // the verifier. function createKeyFinder(keySelector) { return (hint) => { const key = keySelector(hint); if (!key) { throw new verify_1.VerificationError({ code: 'PUBLIC_KEY_ERROR', message: `key not found: ${hint}`, }); } return { publicKey: core_1.crypto.createPublicKey(key), validFor: () => true, }; }; } exports.createKeyFinder = createKeyFinder; function createVerificationPolicy(options) { const policy = {}; const san = options.certificateIdentityEmail || options.certificateIdentityURI; if (san) { policy.subjectAlternativeName = san; } if (options.certificateIssuer) { policy.extensions = { issuer: options.certificateIssuer }; } return policy; } exports.createVerificationPolicy = createVerificationPolicy; // Instantiate the FulcioSigner based on the supplied options. function initSigner(options) { return new sign_1.FulcioSigner({ fulcioBaseURL: options.fulcioURL, identityProvider: options.identityProvider || initIdentityProvider(options), retry: options.retry ?? exports.DEFAULT_RETRY, timeout: options.timeout ?? exports.DEFAULT_TIMEOUT, }); } // Instantiate an identity provider based on the supplied options. If an // explicit identity token is provided, use that. Otherwise, use the CI // context provider. function initIdentityProvider(options) { const token = options.identityToken; if (token) { /* istanbul ignore next */ return { getToken: () => Promise.resolve(token) }; } else { return new sign_1.CIContextProvider('sigstore'); } } // Instantiate a collection of witnesses based on the supplied options. function initWitnesses(options) { const witnesses = []; if (isRekorEnabled(options)) { witnesses.push(new sign_1.RekorWitness({ rekorBaseURL: options.rekorURL, fetchOnConflict: false, retry: options.retry ?? exports.DEFAULT_RETRY, timeout: options.timeout ?? exports.DEFAULT_TIMEOUT, })); } if (isTSAEnabled(options)) { witnesses.push(new sign_1.TSAWitness({ tsaBaseURL: options.tsaServerURL, retry: options.retry ?? exports.DEFAULT_RETRY, timeout: options.timeout ?? exports.DEFAULT_TIMEOUT, })); } return witnesses; } // Type assertion to ensure that Rekor is enabled function isRekorEnabled(options) { return options.tlogUpload !== false; } // Type assertion to ensure that TSA is enabled function isTSAEnabled(options) { return options.tsaServerURL !== undefined; } PK ~\I sigstore/dist/index.jsnu["use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.verify = exports.sign = exports.createVerifier = exports.attest = exports.VerificationError = exports.PolicyError = exports.TUFError = exports.InternalError = exports.DEFAULT_REKOR_URL = exports.DEFAULT_FULCIO_URL = exports.ValidationError = void 0; /* Copyright 2022 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ var bundle_1 = require("@sigstore/bundle"); Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return bundle_1.ValidationError; } }); var sign_1 = require("@sigstore/sign"); Object.defineProperty(exports, "DEFAULT_FULCIO_URL", { enumerable: true, get: function () { return sign_1.DEFAULT_FULCIO_URL; } }); Object.defineProperty(exports, "DEFAULT_REKOR_URL", { enumerable: true, get: function () { return sign_1.DEFAULT_REKOR_URL; } }); Object.defineProperty(exports, "InternalError", { enumerable: true, get: function () { return sign_1.InternalError; } }); var tuf_1 = require("@sigstore/tuf"); Object.defineProperty(exports, "TUFError", { enumerable: true, get: function () { return tuf_1.TUFError; } }); var verify_1 = require("@sigstore/verify"); Object.defineProperty(exports, "PolicyError", { enumerable: true, get: function () { return verify_1.PolicyError; } }); Object.defineProperty(exports, "VerificationError", { enumerable: true, get: function () { return verify_1.VerificationError; } }); var sigstore_1 = require("./sigstore"); Object.defineProperty(exports, "attest", { enumerable: true, get: function () { return sigstore_1.attest; } }); Object.defineProperty(exports, "createVerifier", { enumerable: true, get: function () { return sigstore_1.createVerifier; } }); Object.defineProperty(exports, "sign", { enumerable: true, get: function () { return sigstore_1.sign; } }); Object.defineProperty(exports, "verify", { enumerable: true, get: function () { return sigstore_1.verify; } }); PK ~\:9sigstore/dist/sigstore.jsnu["use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.createVerifier = exports.verify = exports.attest = exports.sign = void 0; /* Copyright 2023 The Sigstore Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ const bundle_1 = require("@sigstore/bundle"); const tuf = __importStar(require("@sigstore/tuf")); const verify_1 = require("@sigstore/verify"); const config = __importStar(require("./config")); async function sign(payload, /* istanbul ignore next */ options = {}) { const bundler = config.createBundleBuilder('messageSignature', options); const bundle = await bundler.create({ data: payload }); return (0, bundle_1.bundleToJSON)(bundle); } exports.sign = sign; async function attest(payload, payloadType, /* istanbul ignore next */ options = {}) { const bundler = config.createBundleBuilder('dsseEnvelope', options); const bundle = await bundler.create({ data: payload, type: payloadType }); return (0, bundle_1.bundleToJSON)(bundle); } exports.attest = attest; async function verify(bundle, dataOrOptions, options) { let data; if (Buffer.isBuffer(dataOrOptions)) { data = dataOrOptions; } else { options = dataOrOptions; } return createVerifier(options).then((verifier) => verifier.verify(bundle, data)); } exports.verify = verify; async function createVerifier( /* istanbul ignore next */ options = {}) { const trustedRoot = await tuf.getTrustedRoot({ mirrorURL: options.tufMirrorURL, rootPath: options.tufRootPath, cachePath: options.tufCachePath, forceCache: options.tufForceCache, retry: options.retry ?? config.DEFAULT_RETRY, timeout: options.timeout ?? config.DEFAULT_TIMEOUT, }); const keyFinder = options.keySelector ? config.createKeyFinder(options.keySelector) : undefined; const trustMaterial = (0, verify_1.toTrustMaterial)(trustedRoot, keyFinder); const verifierOptions = { ctlogThreshold: options.ctLogThreshold, tlogThreshold: options.tlogThreshold, }; const verifier = new verify_1.Verifier(trustMaterial, verifierOptions); const policy = config.createVerificationPolicy(options); return { verify: (bundle, payload) => { const deserializedBundle = (0, bundle_1.bundleFromJSON)(bundle); const signedEntity = (0, verify_1.toSignedEntity)(deserializedBundle, payload); verifier.verify(signedEntity, policy); return; }, }; } exports.createVerifier = createVerifier; PK ~\^$$libnpmdiff/package.jsonnu[{ "_id": "libnpmdiff@6.1.3", "_inBundle": true, "_location": "/npm/libnpmdiff", "_phantomChildren": {}, "_requiredBy": [ "/npm" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/cli/issues" }, "contributors": [ { "name": "Ruy Adorno", "url": "https://ruyadorno.com" } ], "dependencies": { "@npmcli/arborist": "^7.5.3", "@npmcli/installed-package-contents": "^2.1.0", "binary-extensions": "^2.3.0", "diff": "^5.1.0", "minimatch": "^9.0.4", "npm-package-arg": "^11.0.2", "pacote": "^18.0.6", "tar": "^6.2.1" }, "description": "The registry diff", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.22.0", "tap": "^16.3.8" }, "engines": { "node": "^16.14.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/cli#readme", "keywords": [ "npm", "npmcli", "libnpm", "cli", "diff" ], "license": "ISC", "main": "lib/index.js", "name": "libnpmdiff", "repository": { "type": "git", "url": "git+https://github.com/npm/cli.git", "directory": "workspaces/libnpmdiff" }, "scripts": { "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.22.0", "content": "../../scripts/template-oss/index.js" }, "version": "6.1.3" } PK ~\libnpmdiff/lib/tarball.jsnu[const { relative } = require('node:path') const Arborist = require('@npmcli/arborist') const npa = require('npm-package-arg') const pkgContents = require('@npmcli/installed-package-contents') const pacote = require('pacote') const { tarCreateOptions } = pacote.DirFetcher const tar = require('tar') // returns a simplified tarball when reading files from node_modules folder, // thus avoiding running the prepare scripts and the extra logic from packlist const nodeModulesTarball = (manifest) => pkgContents({ path: manifest._resolved, depth: 1 }) .then(files => files.map(file => relative(manifest._resolved, file)) ) .then(files => tar.c(tarCreateOptions(manifest), files).concat() ) const tarball = (manifest, opts) => { const resolved = manifest._resolved const where = opts.where || process.cwd() const fromNodeModules = npa(resolved).type === 'directory' && /node_modules[\\/](@[^\\/]+\/)?[^\\/]+[\\/]?$/.test(relative(where, resolved)) if (fromNodeModules) { return nodeModulesTarball(manifest, opts) } return pacote.tarball(manifest._resolved, { ...opts, Arborist, }) } module.exports = tarball PK ~\D!  $libnpmdiff/lib/should-print-patch.jsnu[const { basename, extname } = require('node:path') const binaryExtensions = require('binary-extensions') // we should try to print patches as long as the // extension is not identified as binary files const shouldPrintPatch = (path, opts = {}) => { if (opts.diffText) { return true } const filename = basename(path) const extension = ( filename.startsWith('.') ? filename : extname(filename) ).slice(1) return !binaryExtensions.includes(extension) } module.exports = shouldPrintPatch PK ~\J libnpmdiff/lib/format-diff.jsnu[const jsDiff = require('diff') const shouldPrintPatch = require('./should-print-patch.js') const colors = { // red removed: { open: '\x1B[31m', close: '\x1B[39m' }, // green added: { open: '\x1B[32m', close: '\x1B[39m' }, // blue header: { open: '\x1B[34m', close: '\x1B[39m' }, // cyan section: { open: '\x1B[36m', close: '\x1B[39m' }, } const color = (colorStr, colorId) => { const { open, close } = colors[colorId] // avoid highlighting the "\n" (would highlight till the end of the line) return colorStr.replace(/[^\n\r]+/g, open + '$&' + close) } const formatDiff = ({ files, opts = {}, refs, versions }) => { let res = '' const srcPrefix = opts.diffNoPrefix ? '' : opts.diffSrcPrefix || 'a/' const dstPrefix = opts.diffNoPrefix ? '' : opts.diffDstPrefix || 'b/' for (const filename of files.values()) { const names = { a: `${srcPrefix}${filename}`, b: `${dstPrefix}${filename}`, } let fileMode = '' const filenames = { a: refs.get(`a/${filename}`), b: refs.get(`b/${filename}`), } const contents = { a: filenames.a && filenames.a.content, b: filenames.b && filenames.b.content, } const modes = { a: filenames.a && filenames.a.mode, b: filenames.b && filenames.b.mode, } if (contents.a === contents.b && modes.a === modes.b) { continue } if (opts.diffNameOnly) { res += `${filename}\n` continue } let patch = '' let headerLength = 0 const header = str => { headerLength++ patch += `${str}\n` } // manually build a git diff-compatible header header(`diff --git ${names.a} ${names.b}`) if (modes.a === modes.b) { fileMode = filenames.a.mode } else { if (modes.a && !modes.b) { header(`deleted file mode ${modes.a}`) } else if (!modes.a && modes.b) { header(`new file mode ${modes.b}`) } else { header(`old mode ${modes.a}`) header(`new mode ${modes.b}`) } } /* eslint-disable-next-line max-len */ header(`index ${opts.tagVersionPrefix || 'v'}${versions.a}..${opts.tagVersionPrefix || 'v'}${versions.b} ${fileMode}`) if (shouldPrintPatch(filename)) { patch += jsDiff.createTwoFilesPatch( names.a, names.b, contents.a || '', contents.b || '', '', '', { context: opts.diffUnified === 0 ? 0 : opts.diffUnified || 3, ignoreWhitespace: opts.diffIgnoreAllSpace, } ).replace( '===================================================================\n', '' ).replace(/\t\n/g, '\n') // strip trailing tabs headerLength += 2 } else { header(`--- ${names.a}`) header(`+++ ${names.b}`) } if (opts.color) { // this RegExp will include all the `\n` chars into the lines, easier to join const lines = patch.split(/^/m) res += color(lines.slice(0, headerLength).join(''), 'header') res += lines.slice(headerLength).join('') .replace(/^-.*/gm, color('$&', 'removed')) .replace(/^\+.*/gm, color('$&', 'added')) .replace(/^@@.+@@/gm, color('$&', 'section')) } else { res += patch } } return res.trim() } module.exports = formatDiff PK ~\Z] ^libnpmdiff/lib/index.jsnu[const pacote = require('pacote') const formatDiff = require('./format-diff.js') const getTarball = require('./tarball.js') const untar = require('./untar.js') // TODO: we test this condition in the diff command // so this error probably doesnt need to be here. Or // if it does we should figure out a standard code // so we can catch it in the cli and display it consistently const argsError = () => Object.assign( new TypeError('libnpmdiff needs two arguments to compare'), { code: 'EDIFFARGS' } ) const diff = async (specs, opts = {}) => { if (specs.length !== 2) { throw argsError() } const [ aManifest, bManifest, ] = await Promise.all(specs.map(spec => pacote.manifest(spec, opts))) const versions = { a: aManifest.version, b: bManifest.version, } // fetches tarball using pacote const [a, b] = await Promise.all([ getTarball(aManifest, opts), getTarball(bManifest, opts), ]) // read all files // populates `files` and `refs` const { files, refs, } = await untar([ { prefix: 'a/', item: a, }, { prefix: 'b/', item: b, }, ], opts) return formatDiff({ files, opts, refs, versions, }) } module.exports = diff PK ~\͚V V libnpmdiff/lib/untar.jsnu[const tar = require('tar') const { minimatch } = require('minimatch') const normalizeMatch = str => str .replace(/\\+/g, '/') .replace(/^\.\/|^\./, '') // files and refs are mutating params // filterFiles, item, prefix and opts are read-only options const untar = ({ files, refs }, { filterFiles, item, prefix }) => { tar.list({ filter: (path, entry) => { const fileMatch = () => (!filterFiles.length || filterFiles.some(f => { const pattern = normalizeMatch(f) return minimatch( normalizeMatch(path), `{package/,}${pattern}`, { matchBase: pattern.startsWith('*') } ) })) // expands usage of simple path filters, e.g: lib or src/ const folderMatch = () => filterFiles.some(f => normalizeMatch(path).startsWith(normalizeMatch(f)) || normalizeMatch(path).startsWith(`package/${normalizeMatch(f)}`)) if ( entry.type === 'File' && (fileMatch() || folderMatch()) ) { const key = path.replace(/^[^/]+\/?/, '') files.add(key) // should skip reading file when using --name-only option let content try { entry.setEncoding('utf8') content = entry.concat() } catch (e) { /* istanbul ignore next */ throw Object.assign( new Error('failed to read files'), { code: 'EDIFFUNTAR' } ) } refs.set(`${prefix}${key}`, { content, mode: `100${entry.mode.toString(8)}`, }) return true } }, }) .on('error', /* istanbul ignore next */ e => { throw e }) .end(item) } const readTarballs = async (tarballs, opts = {}) => { const files = new Set() const refs = new Map() const arr = [].concat(tarballs) const filterFiles = opts.diffFiles || [] for (const i of arr) { untar({ files, refs, }, { item: i.item, prefix: i.prefix, filterFiles, }) } // await to read all content from included files const allRefs = [...refs.values()] const contents = await Promise.all(allRefs.map(async ref => ref.content)) contents.forEach((content, index) => { allRefs[index].content = content }) return { files, refs, } } module.exports = readTarballs PK ~\Flibnpmdiff/LICENSEnu[The ISC License Copyright (c) GitHub Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\jm libnpmdiff/README.mdnu[# libnpmdiff [![npm version](https://img.shields.io/npm/v/libnpmdiff.svg)](https://npm.im/libnpmdiff) [![license](https://img.shields.io/npm/l/libnpmdiff.svg)](https://npm.im/libnpmdiff) [![CI - libnpmdiff](https://github.com/npm/cli/actions/workflows/ci-libnpmdiff.yml/badge.svg)](https://github.com/npm/cli/actions/workflows/ci-libnpmdiff.yml) The registry diff lib. ## Table of Contents * [Example](#example) * [Install](#install) * [Contributing](#contributing) * [API](#api) * [LICENSE](#license) ## Example ```js const libdiff = require('libnpmdiff') const patch = await libdiff([ 'abbrev@1.1.0', 'abbrev@1.1.1' ]) console.log( patch ) ``` Returns: ```patch diff --git a/package.json b/package.json index v1.1.0..v1.1.1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "abbrev", - "version": "1.1.0", + "version": "1.1.1", "description": "Like ruby's abbrev module, but in js", "author": "Isaac Z. Schlueter ", "main": "abbrev.js", ``` ## Install `$ npm install libnpmdiff` ### Contributing The npm team enthusiastically welcomes contributions and project participation! There's a bunch of things you can do if you want to contribute! The [Contributor Guide](https://github.com/npm/cli/blob/latest/CONTRIBUTING.md) outlines the process for community interaction and contribution. Please don't hesitate to jump in if you'd like to, or even ask us questions if something isn't clear. All participants and maintainers in this project are expected to follow the [npm Code of Conduct](https://docs.npmjs.com/policies/conduct), and just generally be excellent to each other. Please refer to the [Changelog](CHANGELOG.md) for project history details, too. Happy hacking! ### API #### `> libnpmdif([ a, b ], [opts]) -> Promise` Fetches the registry tarballs and compare files between a spec `a` and spec `b`. **npm** spec types are usually described in `@` form but multiple other types are alsos supported, for more info on valid specs take a look at [`npm-package-arg`](https://github.com/npm/npm-package-arg). **Options**: - `color `: Should add ANSI colors to string output? Defaults to `false`. - `tagVersionPrefix `: What prefix should be used to define version numbers. Defaults to `v` - `diffUnified `: How many lines of code to print before/after each diff. Defaults to `3`. - `diffFiles >`: If set only prints patches for the files listed in this array (also accepts globs). Defaults to `undefined`. - `diffIgnoreAllSpace `: Whether or not should ignore changes in whitespace (very useful to avoid indentation changes extra diff lines). Defaults to `false`. - `diffNameOnly `: Prints only file names and no patch diffs. Defaults to `false`. - `diffNoPrefix `: If true then skips printing any prefixes in filenames. Defaults to `false`. - `diffSrcPrefix `: Prefix to be used in the filenames from `a`. Defaults to `a/`. - `diffDstPrefix `: Prefix to be used in the filenames from `b`. Defaults to `b/`. - `diffText `: Should treat all files as text and try to print diff for binary files. Defaults to `false`. - ...`cache`, `registry`, `where` and other common options accepted by [pacote](https://github.com/npm/pacote#options) Returns a `Promise` that fullfils with a `String` containing the resulting patch diffs. Throws an error if either `a` or `b` are missing or if trying to diff more than two specs. ## LICENSE [ISC](./LICENSE) PK ~\\_ؼmute-stream/package.jsonnu[{ "_id": "mute-stream@1.0.0", "_inBundle": true, "_location": "/npm/mute-stream", "_phantomChildren": {}, "_requiredBy": [ "/npm/read" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/mute-stream/issues" }, "description": "Bytes go in, but they don't come out (when muted).", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.11.0", "tap": "^16.3.0" }, "engines": { "node": "^14.17.0 || ^16.13.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/mute-stream#readme", "keywords": [ "mute", "stream", "pipe" ], "license": "ISC", "main": "lib/index.js", "name": "mute-stream", "repository": { "type": "git", "url": "git+https://github.com/npm/mute-stream.git" }, "scripts": { "lint": "eslint \"**/*.js\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "statements": 70, "branches": 60, "functions": 81, "lines": 70, "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.11.0" }, "version": "1.0.0" } PK ~\  mute-stream/lib/index.jsnu[const Stream = require('stream') class MuteStream extends Stream { #isTTY = null constructor (opts = {}) { super(opts) this.writable = this.readable = true this.muted = false this.on('pipe', this._onpipe) this.replace = opts.replace // For readline-type situations // This much at the start of a line being redrawn after a ctrl char // is seen (such as backspace) won't be redrawn as the replacement this._prompt = opts.prompt || null this._hadControl = false } #destSrc (key, def) { if (this._dest) { return this._dest[key] } if (this._src) { return this._src[key] } return def } #proxy (method, ...args) { if (typeof this._dest?.[method] === 'function') { this._dest[method](...args) } if (typeof this._src?.[method] === 'function') { this._src[method](...args) } } get isTTY () { if (this.#isTTY !== null) { return this.#isTTY } return this.#destSrc('isTTY', false) } // basically just get replace the getter/setter with a regular value set isTTY (val) { this.#isTTY = val } get rows () { return this.#destSrc('rows') } get columns () { return this.#destSrc('columns') } mute () { this.muted = true } unmute () { this.muted = false } _onpipe (src) { this._src = src } pipe (dest, options) { this._dest = dest return super.pipe(dest, options) } pause () { if (this._src) { return this._src.pause() } } resume () { if (this._src) { return this._src.resume() } } write (c) { if (this.muted) { if (!this.replace) { return true } // eslint-disable-next-line no-control-regex if (c.match(/^\u001b/)) { if (c.indexOf(this._prompt) === 0) { c = c.slice(this._prompt.length) c = c.replace(/./g, this.replace) c = this._prompt + c } this._hadControl = true return this.emit('data', c) } else { if (this._prompt && this._hadControl && c.indexOf(this._prompt) === 0) { this._hadControl = false this.emit('data', this._prompt) c = c.slice(this._prompt.length) } c = c.toString().replace(/./g, this.replace) } } this.emit('data', c) } end (c) { if (this.muted) { if (c && this.replace) { c = c.toString().replace(/./g, this.replace) } else { c = null } } if (c) { this.emit('data', c) } this.emit('end') } destroy (...args) { return this.#proxy('destroy', ...args) } destroySoon (...args) { return this.#proxy('destroySoon', ...args) } close (...args) { return this.#proxy('close', ...args) } } module.exports = MuteStream PK ~\aGWmute-stream/LICENSEnu[The ISC License Copyright (c) Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\Yaproba/package.jsonnu[{ "_id": "aproba@2.0.0", "_inBundle": true, "_location": "/npm/aproba", "_phantomChildren": {}, "_requiredBy": [ "/npm/libnpmhook", "/npm/libnpmorg", "/npm/libnpmteam" ], "author": { "name": "Rebecca Turner", "email": "me@re-becca.org" }, "bugs": { "url": "https://github.com/iarna/aproba/issues" }, "dependencies": {}, "description": "A ridiculously light-weight argument validator (now browser friendly)", "devDependencies": { "standard": "^11.0.1", "tap": "^12.0.1" }, "directories": { "test": "test" }, "files": [ "index.js" ], "homepage": "https://github.com/iarna/aproba", "keywords": [ "argument", "validate" ], "license": "ISC", "main": "index.js", "name": "aproba", "repository": { "type": "git", "url": "git+https://github.com/iarna/aproba.git" }, "scripts": { "pretest": "standard", "test": "tap --100 -J test/*.js" }, "version": "2.0.0" } PK ~\vraproba/LICENSEnu[Copyright (c) 2015, Rebecca Turner Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\><<aproba/index.jsnu['use strict' module.exports = validate function isArguments (thingy) { return thingy != null && typeof thingy === 'object' && thingy.hasOwnProperty('callee') } const types = { '*': {label: 'any', check: () => true}, A: {label: 'array', check: _ => Array.isArray(_) || isArguments(_)}, S: {label: 'string', check: _ => typeof _ === 'string'}, N: {label: 'number', check: _ => typeof _ === 'number'}, F: {label: 'function', check: _ => typeof _ === 'function'}, O: {label: 'object', check: _ => typeof _ === 'object' && _ != null && !types.A.check(_) && !types.E.check(_)}, B: {label: 'boolean', check: _ => typeof _ === 'boolean'}, E: {label: 'error', check: _ => _ instanceof Error}, Z: {label: 'null', check: _ => _ == null} } function addSchema (schema, arity) { const group = arity[schema.length] = arity[schema.length] || [] if (group.indexOf(schema) === -1) group.push(schema) } function validate (rawSchemas, args) { if (arguments.length !== 2) throw wrongNumberOfArgs(['SA'], arguments.length) if (!rawSchemas) throw missingRequiredArg(0, 'rawSchemas') if (!args) throw missingRequiredArg(1, 'args') if (!types.S.check(rawSchemas)) throw invalidType(0, ['string'], rawSchemas) if (!types.A.check(args)) throw invalidType(1, ['array'], args) const schemas = rawSchemas.split('|') const arity = {} schemas.forEach(schema => { for (let ii = 0; ii < schema.length; ++ii) { const type = schema[ii] if (!types[type]) throw unknownType(ii, type) } if (/E.*E/.test(schema)) throw moreThanOneError(schema) addSchema(schema, arity) if (/E/.test(schema)) { addSchema(schema.replace(/E.*$/, 'E'), arity) addSchema(schema.replace(/E/, 'Z'), arity) if (schema.length === 1) addSchema('', arity) } }) let matching = arity[args.length] if (!matching) { throw wrongNumberOfArgs(Object.keys(arity), args.length) } for (let ii = 0; ii < args.length; ++ii) { let newMatching = matching.filter(schema => { const type = schema[ii] const typeCheck = types[type].check return typeCheck(args[ii]) }) if (!newMatching.length) { const labels = matching.map(_ => types[_[ii]].label).filter(_ => _ != null) throw invalidType(ii, labels, args[ii]) } matching = newMatching } } function missingRequiredArg (num) { return newException('EMISSINGARG', 'Missing required argument #' + (num + 1)) } function unknownType (num, type) { return newException('EUNKNOWNTYPE', 'Unknown type ' + type + ' in argument #' + (num + 1)) } function invalidType (num, expectedTypes, value) { let valueType Object.keys(types).forEach(typeCode => { if (types[typeCode].check(value)) valueType = types[typeCode].label }) return newException('EINVALIDTYPE', 'Argument #' + (num + 1) + ': Expected ' + englishList(expectedTypes) + ' but got ' + valueType) } function englishList (list) { return list.join(', ').replace(/, ([^,]+)$/, ' or $1') } function wrongNumberOfArgs (expected, got) { const english = englishList(expected) const args = expected.every(ex => ex.length === 1) ? 'argument' : 'arguments' return newException('EWRONGARGCOUNT', 'Expected ' + english + ' ' + args + ' but got ' + got) } function moreThanOneError (schema) { return newException('ETOOMANYERRORTYPES', 'Only one error type per argument signature is allowed, more than one found in "' + schema + '"') } function newException (code, msg) { const err = new Error(msg) err.code = code /* istanbul ignore else */ if (Error.captureStackTrace) Error.captureStackTrace(err, validate) return err } PK ~\3L<::chalk/package.jsonnu[{ "_id": "chalk@5.3.0", "_inBundle": true, "_location": "/npm/chalk", "_phantomChildren": {}, "_requiredBy": [ "/npm" ], "bugs": { "url": "https://github.com/chalk/chalk/issues" }, "c8": { "reporter": [ "text", "lcov" ], "exclude": [ "source/vendor" ] }, "description": "Terminal string styling done right", "devDependencies": { "@types/node": "^16.11.10", "ava": "^3.15.0", "c8": "^7.10.0", "color-convert": "^2.0.1", "execa": "^6.0.0", "log-update": "^5.0.0", "matcha": "^0.7.0", "tsd": "^0.19.0", "xo": "^0.53.0", "yoctodelay": "^2.0.0" }, "engines": { "node": "^12.17.0 || ^14.13 || >=16.0.0" }, "exports": "./source/index.js", "files": [ "source", "!source/index.test-d.ts" ], "funding": "https://github.com/chalk/chalk?sponsor=1", "homepage": "https://github.com/chalk/chalk#readme", "imports": { "#ansi-styles": "./source/vendor/ansi-styles/index.js", "#supports-color": { "node": "./source/vendor/supports-color/index.js", "default": "./source/vendor/supports-color/browser.js" } }, "keywords": [ "color", "colour", "colors", "terminal", "console", "cli", "string", "ansi", "style", "styles", "tty", "formatting", "rgb", "256", "shell", "xterm", "log", "logging", "command-line", "text" ], "license": "MIT", "main": "./source/index.js", "name": "chalk", "repository": { "type": "git", "url": "git+https://github.com/chalk/chalk.git" }, "scripts": { "bench": "matcha benchmark.js", "test": "xo && c8 ava && tsd" }, "sideEffects": false, "type": "module", "types": "./source/index.d.ts", "version": "5.3.0", "xo": { "rules": { "unicorn/prefer-string-slice": "off", "@typescript-eslint/consistent-type-imports": "off", "@typescript-eslint/consistent-type-exports": "off", "@typescript-eslint/consistent-type-definitions": "off", "unicorn/expiring-todo-comments": "off" } } } PK ~\e>%chalk/source/index.jsnu[import ansiStyles from '#ansi-styles'; import supportsColor from '#supports-color'; import { // eslint-disable-line import/order stringReplaceAll, stringEncaseCRLFWithFirstIndex, } from './utilities.js'; const {stdout: stdoutColor, stderr: stderrColor} = supportsColor; const GENERATOR = Symbol('GENERATOR'); const STYLER = Symbol('STYLER'); const IS_EMPTY = Symbol('IS_EMPTY'); // `supportsColor.level` → `ansiStyles.color[name]` mapping const levelMapping = [ 'ansi', 'ansi', 'ansi256', 'ansi16m', ]; const styles = Object.create(null); const applyOptions = (object, options = {}) => { if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { throw new Error('The `level` option should be an integer from 0 to 3'); } // Detect level if not set manually const colorLevel = stdoutColor ? stdoutColor.level : 0; object.level = options.level === undefined ? colorLevel : options.level; }; export class Chalk { constructor(options) { // eslint-disable-next-line no-constructor-return return chalkFactory(options); } } const chalkFactory = options => { const chalk = (...strings) => strings.join(' '); applyOptions(chalk, options); Object.setPrototypeOf(chalk, createChalk.prototype); return chalk; }; function createChalk(options) { return chalkFactory(options); } Object.setPrototypeOf(createChalk.prototype, Function.prototype); for (const [styleName, style] of Object.entries(ansiStyles)) { styles[styleName] = { get() { const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]); Object.defineProperty(this, styleName, {value: builder}); return builder; }, }; } styles.visible = { get() { const builder = createBuilder(this, this[STYLER], true); Object.defineProperty(this, 'visible', {value: builder}); return builder; }, }; const getModelAnsi = (model, level, type, ...arguments_) => { if (model === 'rgb') { if (level === 'ansi16m') { return ansiStyles[type].ansi16m(...arguments_); } if (level === 'ansi256') { return ansiStyles[type].ansi256(ansiStyles.rgbToAnsi256(...arguments_)); } return ansiStyles[type].ansi(ansiStyles.rgbToAnsi(...arguments_)); } if (model === 'hex') { return getModelAnsi('rgb', level, type, ...ansiStyles.hexToRgb(...arguments_)); } return ansiStyles[type][model](...arguments_); }; const usedModels = ['rgb', 'hex', 'ansi256']; for (const model of usedModels) { styles[model] = { get() { const {level} = this; return function (...arguments_) { const styler = createStyler(getModelAnsi(model, levelMapping[level], 'color', ...arguments_), ansiStyles.color.close, this[STYLER]); return createBuilder(this, styler, this[IS_EMPTY]); }; }, }; const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); styles[bgModel] = { get() { const {level} = this; return function (...arguments_) { const styler = createStyler(getModelAnsi(model, levelMapping[level], 'bgColor', ...arguments_), ansiStyles.bgColor.close, this[STYLER]); return createBuilder(this, styler, this[IS_EMPTY]); }; }, }; } const proto = Object.defineProperties(() => {}, { ...styles, level: { enumerable: true, get() { return this[GENERATOR].level; }, set(level) { this[GENERATOR].level = level; }, }, }); const createStyler = (open, close, parent) => { let openAll; let closeAll; if (parent === undefined) { openAll = open; closeAll = close; } else { openAll = parent.openAll + open; closeAll = close + parent.closeAll; } return { open, close, openAll, closeAll, parent, }; }; const createBuilder = (self, _styler, _isEmpty) => { // Single argument is hot path, implicit coercion is faster than anything // eslint-disable-next-line no-implicit-coercion const builder = (...arguments_) => applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' ')); // We alter the prototype because we must return a function, but there is // no way to create a function with a different prototype Object.setPrototypeOf(builder, proto); builder[GENERATOR] = self; builder[STYLER] = _styler; builder[IS_EMPTY] = _isEmpty; return builder; }; const applyStyle = (self, string) => { if (self.level <= 0 || !string) { return self[IS_EMPTY] ? '' : string; } let styler = self[STYLER]; if (styler === undefined) { return string; } const {openAll, closeAll} = styler; if (string.includes('\u001B')) { while (styler !== undefined) { // Replace any instances already present with a re-opening code // otherwise only the part of the string until said closing code // will be colored, and the rest will simply be 'plain'. string = stringReplaceAll(string, styler.close, styler.open); styler = styler.parent; } } // We can move both next actions out of loop, because remaining actions in loop won't have // any/visible effect on parts we add here. Close the styling before a linebreak and reopen // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 const lfIndex = string.indexOf('\n'); if (lfIndex !== -1) { string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex); } return openAll + string + closeAll; }; Object.defineProperties(createChalk.prototype, styles); const chalk = createChalk(); export const chalkStderr = createChalk({level: stderrColor ? stderrColor.level : 0}); export { modifierNames, foregroundColorNames, backgroundColorNames, colorNames, // TODO: Remove these aliases in the next major version modifierNames as modifiers, foregroundColorNames as foregroundColors, backgroundColorNames as backgroundColors, colorNames as colors, } from './vendor/ansi-styles/index.js'; export { stdoutColor as supportsColor, stderrColor as supportsColorStderr, }; export default chalk; PK ~\KcS(chalk/source/vendor/ansi-styles/index.jsnu[const ANSI_BACKGROUND_OFFSET = 10; const wrapAnsi16 = (offset = 0) => code => `\u001B[${code + offset}m`; const wrapAnsi256 = (offset = 0) => code => `\u001B[${38 + offset};5;${code}m`; const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`; const styles = { modifier: { reset: [0, 0], // 21 isn't widely supported and 22 does the same thing bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], overline: [53, 55], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], // Bright color blackBright: [90, 39], gray: [90, 39], // Alias of `blackBright` grey: [90, 39], // Alias of `blackBright` redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], // Bright color bgBlackBright: [100, 49], bgGray: [100, 49], // Alias of `bgBlackBright` bgGrey: [100, 49], // Alias of `bgBlackBright` bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], }, }; export const modifierNames = Object.keys(styles.modifier); export const foregroundColorNames = Object.keys(styles.color); export const backgroundColorNames = Object.keys(styles.bgColor); export const colorNames = [...foregroundColorNames, ...backgroundColorNames]; function assembleStyles() { const codes = new Map(); for (const [groupName, group] of Object.entries(styles)) { for (const [styleName, style] of Object.entries(group)) { styles[styleName] = { open: `\u001B[${style[0]}m`, close: `\u001B[${style[1]}m`, }; group[styleName] = styles[styleName]; codes.set(style[0], style[1]); } Object.defineProperty(styles, groupName, { value: group, enumerable: false, }); } Object.defineProperty(styles, 'codes', { value: codes, enumerable: false, }); styles.color.close = '\u001B[39m'; styles.bgColor.close = '\u001B[49m'; styles.color.ansi = wrapAnsi16(); styles.color.ansi256 = wrapAnsi256(); styles.color.ansi16m = wrapAnsi16m(); styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET); styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); // From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js Object.defineProperties(styles, { rgbToAnsi256: { value(red, green, blue) { // We use the extended greyscale palette here, with the exception of // black and white. normal palette only has 4 greyscale shades. if (red === green && green === blue) { if (red < 8) { return 16; } if (red > 248) { return 231; } return Math.round(((red - 8) / 247) * 24) + 232; } return 16 + (36 * Math.round(red / 255 * 5)) + (6 * Math.round(green / 255 * 5)) + Math.round(blue / 255 * 5); }, enumerable: false, }, hexToRgb: { value(hex) { const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16)); if (!matches) { return [0, 0, 0]; } let [colorString] = matches; if (colorString.length === 3) { colorString = [...colorString].map(character => character + character).join(''); } const integer = Number.parseInt(colorString, 16); return [ /* eslint-disable no-bitwise */ (integer >> 16) & 0xFF, (integer >> 8) & 0xFF, integer & 0xFF, /* eslint-enable no-bitwise */ ]; }, enumerable: false, }, hexToAnsi256: { value: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)), enumerable: false, }, ansi256ToAnsi: { value(code) { if (code < 8) { return 30 + code; } if (code < 16) { return 90 + (code - 8); } let red; let green; let blue; if (code >= 232) { red = (((code - 232) * 10) + 8) / 255; green = red; blue = red; } else { code -= 16; const remainder = code % 36; red = Math.floor(code / 36) / 5; green = Math.floor(remainder / 6) / 5; blue = (remainder % 6) / 5; } const value = Math.max(red, green, blue) * 2; if (value === 0) { return 30; } // eslint-disable-next-line no-bitwise let result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red)); if (value === 2) { result += 60; } return result; }, enumerable: false, }, rgbToAnsi: { value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)), enumerable: false, }, hexToAnsi: { value: hex => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)), enumerable: false, }, }); return styles; } const ansiStyles = assembleStyles(); export default ansiStyles; PK ~\&+chalk/source/vendor/supports-color/index.jsnu[import process from 'node:process'; import os from 'node:os'; import tty from 'node:tty'; // From: https://github.com/sindresorhus/has-flag/blob/main/index.js /// function hasFlag(flag, argv = globalThis.Deno?.args ?? process.argv) { function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process.argv) { const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); const position = argv.indexOf(prefix + flag); const terminatorPosition = argv.indexOf('--'); return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); } const {env} = process; let flagForceColor; if ( hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false') || hasFlag('color=never') ) { flagForceColor = 0; } else if ( hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always') ) { flagForceColor = 1; } function envForceColor() { if ('FORCE_COLOR' in env) { if (env.FORCE_COLOR === 'true') { return 1; } if (env.FORCE_COLOR === 'false') { return 0; } return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3); } } function translateLevel(level) { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3, }; } function _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) { const noFlagForceColor = envForceColor(); if (noFlagForceColor !== undefined) { flagForceColor = noFlagForceColor; } const forceColor = sniffFlags ? flagForceColor : noFlagForceColor; if (forceColor === 0) { return 0; } if (sniffFlags) { if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) { return 3; } if (hasFlag('color=256')) { return 2; } } // Check for Azure DevOps pipelines. // Has to be above the `!streamIsTTY` check. if ('TF_BUILD' in env && 'AGENT_NAME' in env) { return 1; } if (haveStream && !streamIsTTY && forceColor === undefined) { return 0; } const min = forceColor || 0; if (env.TERM === 'dumb') { return min; } if (process.platform === 'win32') { // Windows 10 build 10586 is the first Windows release that supports 256 colors. // Windows 10 build 14931 is the first release that supports 16m/TrueColor. const osRelease = os.release().split('.'); if ( Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10_586 ) { return Number(osRelease[2]) >= 14_931 ? 3 : 2; } return 1; } if ('CI' in env) { if ('GITHUB_ACTIONS' in env || 'GITEA_ACTIONS' in env) { return 3; } if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'BUILDKITE', 'DRONE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { return 1; } return min; } if ('TEAMCITY_VERSION' in env) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; } if (env.COLORTERM === 'truecolor') { return 3; } if (env.TERM === 'xterm-kitty') { return 3; } if ('TERM_PROGRAM' in env) { const version = Number.parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); switch (env.TERM_PROGRAM) { case 'iTerm.app': { return version >= 3 ? 3 : 2; } case 'Apple_Terminal': { return 2; } // No default } } if (/-256(color)?$/i.test(env.TERM)) { return 2; } if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { return 1; } if ('COLORTERM' in env) { return 1; } return min; } export function createSupportsColor(stream, options = {}) { const level = _supportsColor(stream, { streamIsTTY: stream && stream.isTTY, ...options, }); return translateLevel(level); } const supportsColor = { stdout: createSupportsColor({isTTY: tty.isatty(1)}), stderr: createSupportsColor({isTTY: tty.isatty(2)}), }; export default supportsColor; PK ~\ -chalk/source/vendor/supports-color/browser.jsnu[/* eslint-env browser */ const level = (() => { if (navigator.userAgentData) { const brand = navigator.userAgentData.brands.find(({brand}) => brand === 'Chromium'); if (brand && brand.version > 93) { return 3; } } if (/\b(Chrome|Chromium)\//.test(navigator.userAgent)) { return 1; } return 0; })(); const colorSupport = level !== 0 && { level, hasBasic: true, has256: level >= 2, has16m: level >= 3, }; const supportsColor = { stdout: colorSupport, stderr: colorSupport, }; export default supportsColor; PK ~\ cchalk/source/utilities.jsnu[// TODO: When targeting Node.js 16, use `String.prototype.replaceAll`. export function stringReplaceAll(string, substring, replacer) { let index = string.indexOf(substring); if (index === -1) { return string; } const substringLength = substring.length; let endIndex = 0; let returnValue = ''; do { returnValue += string.slice(endIndex, index) + substring + replacer; endIndex = index + substringLength; index = string.indexOf(substring, endIndex); } while (index !== -1); returnValue += string.slice(endIndex); return returnValue; } export function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) { let endIndex = 0; let returnValue = ''; do { const gotCR = string[index - 1] === '\r'; returnValue += string.slice(endIndex, (gotCR ? index - 1 : index)) + prefix + (gotCR ? '\r\n' : '\n') + postfix; endIndex = index + 1; index = string.indexOf('\n', endIndex); } while (index !== -1); returnValue += string.slice(endIndex); return returnValue; } PK ~\i]] chalk/licensenu[MIT License Copyright (c) Sindre Sorhus (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\%  pacote/package.jsonnu[{ "_id": "pacote@18.0.6", "_inBundle": true, "_location": "/npm/pacote", "_phantomChildren": {}, "_requiredBy": [ "/npm", "/npm/@npmcli/arborist", "/npm/@npmcli/metavuln-calculator", "/npm/libnpmdiff", "/npm/libnpmexec", "/npm/libnpmpack" ], "author": { "name": "GitHub Inc." }, "bin": { "pacote": "bin/index.js" }, "bugs": { "url": "https://github.com/npm/pacote/issues" }, "dependencies": { "@npmcli/git": "^5.0.0", "@npmcli/installed-package-contents": "^2.0.1", "@npmcli/package-json": "^5.1.0", "@npmcli/promise-spawn": "^7.0.0", "@npmcli/run-script": "^8.0.0", "cacache": "^18.0.0", "fs-minipass": "^3.0.0", "minipass": "^7.0.2", "npm-package-arg": "^11.0.0", "npm-packlist": "^8.0.0", "npm-pick-manifest": "^9.0.0", "npm-registry-fetch": "^17.0.0", "proc-log": "^4.0.0", "promise-retry": "^2.0.1", "sigstore": "^2.2.0", "ssri": "^10.0.0", "tar": "^6.1.11" }, "description": "JavaScript package downloader", "devDependencies": { "@npmcli/arborist": "^7.1.0", "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.22.0", "hosted-git-info": "^7.0.0", "mutate-fs": "^2.1.1", "nock": "^13.2.4", "npm-registry-mock": "^1.3.2", "tap": "^16.0.1" }, "engines": { "node": "^16.14.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/pacote#readme", "keywords": [ "packages", "npm", "git" ], "license": "ISC", "main": "lib/index.js", "name": "pacote", "repository": { "type": "git", "url": "git+https://github.com/npm/pacote.git" }, "scripts": { "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "timeout": 300, "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.22.0", "windowsCI": false, "publish": "true" }, "version": "18.0.6" } PK ~\QQ++pacote/lib/git.jsnu[const cacache = require('cacache') const git = require('@npmcli/git') const npa = require('npm-package-arg') const pickManifest = require('npm-pick-manifest') const { Minipass } = require('minipass') const { log } = require('proc-log') const DirFetcher = require('./dir.js') const Fetcher = require('./fetcher.js') const FileFetcher = require('./file.js') const RemoteFetcher = require('./remote.js') const _ = require('./util/protected.js') const addGitSha = require('./util/add-git-sha.js') const npm = require('./util/npm.js') const hashre = /^[a-f0-9]{40}$/ // get the repository url. // prefer https if there's auth, since ssh will drop that. // otherwise, prefer ssh if available (more secure). // We have to add the git+ back because npa suppresses it. const repoUrl = (h, opts) => h.sshurl && !(h.https && h.auth) && addGitPlus(h.sshurl(opts)) || h.https && addGitPlus(h.https(opts)) // add git+ to the url, but only one time. const addGitPlus = url => url && `git+${url}`.replace(/^(git\+)+/, 'git+') class GitFetcher extends Fetcher { constructor (spec, opts) { super(spec, opts) // we never want to compare integrity for git dependencies: npm/rfcs#525 if (this.opts.integrity) { delete this.opts.integrity log.warn(`skipping integrity check for git dependency ${this.spec.fetchSpec}`) } this.resolvedRef = null if (this.spec.hosted) { this.from = this.spec.hosted.shortcut({ noCommittish: false }) } // shortcut: avoid full clone when we can go straight to the tgz // if we have the full sha and it's a hosted git platform if (this.spec.gitCommittish && hashre.test(this.spec.gitCommittish)) { this.resolvedSha = this.spec.gitCommittish // use hosted.tarball() when we shell to RemoteFetcher later this.resolved = this.spec.hosted ? repoUrl(this.spec.hosted, { noCommittish: false }) : this.spec.rawSpec } else { this.resolvedSha = '' } this.Arborist = opts.Arborist || null } // just exposed to make it easier to test all the combinations static repoUrl (hosted, opts) { return repoUrl(hosted, opts) } get types () { return ['git'] } resolve () { // likely a hosted git repo with a sha, so get the tarball url // but in general, no reason to resolve() more than necessary! if (this.resolved) { return super.resolve() } // fetch the git repo and then look at the current hash const h = this.spec.hosted // try to use ssh, fall back to git. return h ? this.#resolvedFromHosted(h) : this.#resolvedFromRepo(this.spec.fetchSpec) } // first try https, since that's faster and passphrase-less for // public repos, and supports private repos when auth is provided. // Fall back to SSH to support private repos // NB: we always store the https url in resolved field if auth // is present, otherwise ssh if the hosted type provides it #resolvedFromHosted (hosted) { return this.#resolvedFromRepo(hosted.https && hosted.https()).catch(er => { // Throw early since we know pathspec errors will fail again if retried if (er instanceof git.errors.GitPathspecError) { throw er } const ssh = hosted.sshurl && hosted.sshurl() // no fallthrough if we can't fall through or have https auth if (!ssh || hosted.auth) { throw er } return this.#resolvedFromRepo(ssh) }) } #resolvedFromRepo (gitRemote) { // XXX make this a custom error class if (!gitRemote) { return Promise.reject(new Error(`No git url for ${this.spec}`)) } const gitRange = this.spec.gitRange const name = this.spec.name return git.revs(gitRemote, this.opts).then(remoteRefs => { return gitRange ? pickManifest({ versions: remoteRefs.versions, 'dist-tags': remoteRefs['dist-tags'], name, }, gitRange, this.opts) : this.spec.gitCommittish ? remoteRefs.refs[this.spec.gitCommittish] || remoteRefs.refs[remoteRefs.shas[this.spec.gitCommittish]] : remoteRefs.refs.HEAD // no git committish, get default head }).then(revDoc => { // the committish provided isn't in the rev list // things like HEAD~3 or @yesterday can land here. if (!revDoc || !revDoc.sha) { return this.#resolvedFromClone() } this.resolvedRef = revDoc this.resolvedSha = revDoc.sha this.#addGitSha(revDoc.sha) return this.resolved }) } #setResolvedWithSha (withSha) { // we haven't cloned, so a tgz download is still faster // of course, if it's not a known host, we can't do that. this.resolved = !this.spec.hosted ? withSha : repoUrl(npa(withSha).hosted, { noCommittish: false }) } // when we get the git sha, we affix it to our spec to build up // either a git url with a hash, or a tarball download URL #addGitSha (sha) { this.#setResolvedWithSha(addGitSha(this.spec, sha)) } #resolvedFromClone () { // do a full or shallow clone, then look at the HEAD // kind of wasteful, but no other option, really return this.#clone(() => this.resolved) } #prepareDir (dir) { return this[_.readPackageJson](dir).then(mani => { // no need if we aren't going to do any preparation. const scripts = mani.scripts if (!mani.workspaces && (!scripts || !( scripts.postinstall || scripts.build || scripts.preinstall || scripts.install || scripts.prepack || scripts.prepare))) { return } // to avoid cases where we have an cycle of git deps that depend // on one another, we only ever do preparation for one instance // of a given git dep along the chain of installations. // Note that this does mean that a dependency MAY in theory end up // trying to run its prepare script using a dependency that has not // been properly prepared itself, but that edge case is smaller // and less hazardous than a fork bomb of npm and git commands. const noPrepare = !process.env._PACOTE_NO_PREPARE_ ? [] : process.env._PACOTE_NO_PREPARE_.split('\n') if (noPrepare.includes(this.resolved)) { log.info('prepare', 'skip prepare, already seen', this.resolved) return } noPrepare.push(this.resolved) // the DirFetcher will do its own preparation to run the prepare scripts // All we have to do is put the deps in place so that it can succeed. return npm( this.npmBin, [].concat(this.npmInstallCmd).concat(this.npmCliConfig), dir, { ...process.env, _PACOTE_NO_PREPARE_: noPrepare.join('\n') }, { message: 'git dep preparation failed' } ) }) } [_.tarballFromResolved] () { const stream = new Minipass() stream.resolved = this.resolved stream.from = this.from // check it out and then shell out to the DirFetcher tarball packer this.#clone(dir => this.#prepareDir(dir) .then(() => new Promise((res, rej) => { if (!this.Arborist) { throw new Error('GitFetcher requires an Arborist constructor to pack a tarball') } const df = new DirFetcher(`file:${dir}`, { ...this.opts, Arborist: this.Arborist, resolved: null, integrity: null, }) const dirStream = df[_.tarballFromResolved]() dirStream.on('error', rej) dirStream.on('end', res) dirStream.pipe(stream) }))).catch( /* istanbul ignore next: very unlikely and hard to test */ er => stream.emit('error', er) ) return stream } // clone a git repo into a temp folder (or fetch and unpack if possible) // handler accepts a directory, and returns a promise that resolves // when we're done with it, at which point, cacache deletes it // // TODO: after cloning, create a tarball of the folder, and add to the cache // with cacache.put.stream(), using a key that's deterministic based on the // spec and repo, so that we don't ever clone the same thing multiple times. #clone (handler, tarballOk = true) { const o = { tmpPrefix: 'git-clone' } const ref = this.resolvedSha || this.spec.gitCommittish const h = this.spec.hosted const resolved = this.resolved // can be set manually to false to fall back to actual git clone tarballOk = tarballOk && h && resolved === repoUrl(h, { noCommittish: false }) && h.tarball return cacache.tmp.withTmp(this.cache, o, async tmp => { // if we're resolved, and have a tarball url, shell out to RemoteFetcher if (tarballOk) { const nameat = this.spec.name ? `${this.spec.name}@` : '' return new RemoteFetcher(h.tarball({ noCommittish: false }), { ...this.opts, allowGitIgnore: true, pkgid: `git:${nameat}${this.resolved}`, resolved: this.resolved, integrity: null, // it'll always be different, if we have one }).extract(tmp).then(() => handler(tmp), er => { // fall back to ssh download if tarball fails if (er.constructor.name.match(/^Http/)) { return this.#clone(handler, false) } else { throw er } }) } const sha = await ( h ? this.#cloneHosted(ref, tmp) : this.#cloneRepo(this.spec.fetchSpec, ref, tmp) ) this.resolvedSha = sha if (!this.resolved) { await this.#addGitSha(sha) } return handler(tmp) }) } // first try https, since that's faster and passphrase-less for // public repos, and supports private repos when auth is provided. // Fall back to SSH to support private repos // NB: we always store the https url in resolved field if auth // is present, otherwise ssh if the hosted type provides it #cloneHosted (ref, tmp) { const hosted = this.spec.hosted return this.#cloneRepo(hosted.https({ noCommittish: true }), ref, tmp) .catch(er => { // Throw early since we know pathspec errors will fail again if retried if (er instanceof git.errors.GitPathspecError) { throw er } const ssh = hosted.sshurl && hosted.sshurl({ noCommittish: true }) // no fallthrough if we can't fall through or have https auth if (!ssh || hosted.auth) { throw er } return this.#cloneRepo(ssh, ref, tmp) }) } #cloneRepo (repo, ref, tmp) { const { opts, spec } = this return git.clone(repo, ref, tmp, { ...opts, spec }) } manifest () { if (this.package) { return Promise.resolve(this.package) } return this.spec.hosted && this.resolved ? FileFetcher.prototype.manifest.apply(this) : this.#clone(dir => this[_.readPackageJson](dir) .then(mani => this.package = { ...mani, _resolved: this.resolved, _from: this.from, })) } packument () { return FileFetcher.prototype.packument.apply(this) } } module.exports = GitFetcher PK ~\E"8"8pacote/lib/registry.jsnu[const crypto = require('node:crypto') const PackageJson = require('@npmcli/package-json') const pickManifest = require('npm-pick-manifest') const ssri = require('ssri') const npa = require('npm-package-arg') const sigstore = require('sigstore') const fetch = require('npm-registry-fetch') const Fetcher = require('./fetcher.js') const RemoteFetcher = require('./remote.js') const pacoteVersion = require('../package.json').version const removeTrailingSlashes = require('./util/trailing-slashes.js') const _ = require('./util/protected.js') // Corgis are cute. 🐕🐶 const corgiDoc = 'application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*' const fullDoc = 'application/json' // Some really old packages have no time field in their packument so we need a // cutoff date. const MISSING_TIME_CUTOFF = '2015-01-01T00:00:00.000Z' class RegistryFetcher extends Fetcher { #cacheKey constructor (spec, opts) { super(spec, opts) // you usually don't want to fetch the same packument multiple times in // the span of a given script or command, no matter how many pacote calls // are made, so this lets us avoid doing that. It's only relevant for // registry fetchers, because other types simulate their packument from // the manifest, which they memoize on this.package, so it's very cheap // already. this.packumentCache = this.opts.packumentCache || null this.registry = fetch.pickRegistry(spec, opts) this.packumentUrl = `${removeTrailingSlashes(this.registry)}/${this.spec.escapedName}` this.#cacheKey = `${this.fullMetadata ? 'full' : 'corgi'}:${this.packumentUrl}` const parsed = new URL(this.registry) const regKey = `//${parsed.host}${parsed.pathname}` // unlike the nerf-darted auth keys, this one does *not* allow a mismatch // of trailing slashes. It must match exactly. if (this.opts[`${regKey}:_keys`]) { this.registryKeys = this.opts[`${regKey}:_keys`] } // XXX pacote <=9 has some logic to ignore opts.resolved if // the resolved URL doesn't go to the same registry. // Consider reproducing that here, to throw away this.resolved // in that case. } async resolve () { // fetching the manifest sets resolved and (if present) integrity await this.manifest() if (!this.resolved) { throw Object.assign( new Error('Invalid package manifest: no `dist.tarball` field'), { package: this.spec.toString() } ) } return this.resolved } #headers () { return { // npm will override UA, but ensure that we always send *something* 'user-agent': this.opts.userAgent || `pacote/${pacoteVersion} node/${process.version}`, ...(this.opts.headers || {}), 'pacote-version': pacoteVersion, 'pacote-req-type': 'packument', 'pacote-pkg-id': `registry:${this.spec.name}`, accept: this.fullMetadata ? fullDoc : corgiDoc, } } async packument () { // note this might be either an in-flight promise for a request, // or the actual packument, but we never want to make more than // one request at a time for the same thing regardless. if (this.packumentCache?.has(this.#cacheKey)) { return this.packumentCache.get(this.#cacheKey) } // npm-registry-fetch the packument // set the appropriate header for corgis if fullMetadata isn't set // return the res.json() promise try { const res = await fetch(this.packumentUrl, { ...this.opts, headers: this.#headers(), spec: this.spec, // never check integrity for packuments themselves integrity: null, }) const packument = await res.json() const contentLength = res.headers.get('content-length') if (contentLength) { packument._contentLength = Number(contentLength) } this.packumentCache?.set(this.#cacheKey, packument) return packument } catch (err) { this.packumentCache?.delete(this.#cacheKey) if (err.code !== 'E404' || this.fullMetadata) { throw err } // possible that corgis are not supported by this registry this.fullMetadata = true return this.packument() } } async manifest () { if (this.package) { return this.package } // When verifying signatures, we need to fetch the full/uncompressed // packument to get publish time as this is not included in the // corgi/compressed packument. if (this.opts.verifySignatures) { this.fullMetadata = true } const packument = await this.packument() const steps = PackageJson.normalizeSteps.filter(s => s !== '_attributes') const mani = await new PackageJson().fromContent(pickManifest(packument, this.spec.fetchSpec, { ...this.opts, defaultTag: this.defaultTag, before: this.before, })).normalize({ steps }).then(p => p.content) /* XXX add ETARGET and E403 revalidation of cached packuments here */ // add _time from packument if fetched with fullMetadata const time = packument.time?.[mani.version] if (time) { mani._time = time } // add _resolved and _integrity from dist object const { dist } = mani if (dist) { this.resolved = mani._resolved = dist.tarball mani._from = this.from const distIntegrity = dist.integrity ? ssri.parse(dist.integrity) : dist.shasum ? ssri.fromHex(dist.shasum, 'sha1', { ...this.opts }) : null if (distIntegrity) { if (this.integrity && !this.integrity.match(distIntegrity)) { // only bork if they have algos in common. // otherwise we end up breaking if we have saved a sha512 // previously for the tarball, but the manifest only // provides a sha1, which is possible for older publishes. // Otherwise, this is almost certainly a case of holding it // wrong, and will result in weird or insecure behavior // later on when building package tree. for (const algo of Object.keys(this.integrity)) { if (distIntegrity[algo]) { throw Object.assign(new Error( `Integrity checksum failed when using ${algo}: ` + `wanted ${this.integrity} but got ${distIntegrity}.` ), { code: 'EINTEGRITY' }) } } } // made it this far, the integrity is worthwhile. accept it. // the setter here will take care of merging it into what we already // had. this.integrity = distIntegrity } } if (this.integrity) { mani._integrity = String(this.integrity) if (dist.signatures) { if (this.opts.verifySignatures) { // validate and throw on error, then set _signatures const message = `${mani._id}:${mani._integrity}` for (const signature of dist.signatures) { const publicKey = this.registryKeys && this.registryKeys.filter(key => (key.keyid === signature.keyid))[0] if (!publicKey) { throw Object.assign(new Error( `${mani._id} has a registry signature with keyid: ${signature.keyid} ` + 'but no corresponding public key can be found' ), { code: 'EMISSINGSIGNATUREKEY' }) } const publishedTime = Date.parse(mani._time || MISSING_TIME_CUTOFF) const validPublicKey = !publicKey.expires || publishedTime < Date.parse(publicKey.expires) if (!validPublicKey) { throw Object.assign(new Error( `${mani._id} has a registry signature with keyid: ${signature.keyid} ` + `but the corresponding public key has expired ${publicKey.expires}` ), { code: 'EEXPIREDSIGNATUREKEY' }) } const verifier = crypto.createVerify('SHA256') verifier.write(message) verifier.end() const valid = verifier.verify( publicKey.pemkey, signature.sig, 'base64' ) if (!valid) { throw Object.assign(new Error( `${mani._id} has an invalid registry signature with ` + `keyid: ${publicKey.keyid} and signature: ${signature.sig}` ), { code: 'EINTEGRITYSIGNATURE', keyid: publicKey.keyid, signature: signature.sig, resolved: mani._resolved, integrity: mani._integrity, }) } } mani._signatures = dist.signatures } else { mani._signatures = dist.signatures } } if (dist.attestations) { if (this.opts.verifyAttestations) { // Always fetch attestations from the current registry host const attestationsPath = new URL(dist.attestations.url).pathname const attestationsUrl = removeTrailingSlashes(this.registry) + attestationsPath const res = await fetch(attestationsUrl, { ...this.opts, // disable integrity check for attestations json payload, we check the // integrity in the verification steps below integrity: null, }) const { attestations } = await res.json() const bundles = attestations.map(({ predicateType, bundle }) => { const statement = JSON.parse( Buffer.from(bundle.dsseEnvelope.payload, 'base64').toString('utf8') ) const keyid = bundle.dsseEnvelope.signatures[0].keyid const signature = bundle.dsseEnvelope.signatures[0].sig return { predicateType, bundle, statement, keyid, signature, } }) const attestationKeyIds = bundles.map((b) => b.keyid).filter((k) => !!k) const attestationRegistryKeys = (this.registryKeys || []) .filter(key => attestationKeyIds.includes(key.keyid)) if (!attestationRegistryKeys.length) { throw Object.assign(new Error( `${mani._id} has attestations but no corresponding public key(s) can be found` ), { code: 'EMISSINGSIGNATUREKEY' }) } for (const { predicateType, bundle, keyid, signature, statement } of bundles) { const publicKey = attestationRegistryKeys.find(key => key.keyid === keyid) // Publish attestations have a keyid set and a valid public key must be found if (keyid) { if (!publicKey) { throw Object.assign(new Error( `${mani._id} has attestations with keyid: ${keyid} ` + 'but no corresponding public key can be found' ), { code: 'EMISSINGSIGNATUREKEY' }) } const integratedTime = new Date( Number( bundle.verificationMaterial.tlogEntries[0].integratedTime ) * 1000 ) const validPublicKey = !publicKey.expires || (integratedTime < Date.parse(publicKey.expires)) if (!validPublicKey) { throw Object.assign(new Error( `${mani._id} has attestations with keyid: ${keyid} ` + `but the corresponding public key has expired ${publicKey.expires}` ), { code: 'EEXPIREDSIGNATUREKEY' }) } } const subject = { name: statement.subject[0].name, sha512: statement.subject[0].digest.sha512, } // Only type 'version' can be turned into a PURL const purl = this.spec.type === 'version' ? npa.toPurl(this.spec) : this.spec // Verify the statement subject matches the package, version if (subject.name !== purl) { throw Object.assign(new Error( `${mani._id} package name and version (PURL): ${purl} ` + `doesn't match what was signed: ${subject.name}` ), { code: 'EATTESTATIONSUBJECT' }) } // Verify the statement subject matches the tarball integrity const integrityHexDigest = ssri.parse(this.integrity).hexDigest() if (subject.sha512 !== integrityHexDigest) { throw Object.assign(new Error( `${mani._id} package integrity (hex digest): ` + `${integrityHexDigest} ` + `doesn't match what was signed: ${subject.sha512}` ), { code: 'EATTESTATIONSUBJECT' }) } try { // Provenance attestations are signed with a signing certificate // (including the key) so we don't need to return a public key. // // Publish attestations are signed with a keyid so we need to // specify a public key from the keys endpoint: `registry-host.tld/-/npm/v1/keys` const options = { tufCachePath: this.tufCache, tufForceCache: true, keySelector: publicKey ? () => publicKey.pemkey : undefined, } await sigstore.verify(bundle, options) } catch (e) { throw Object.assign(new Error( `${mani._id} failed to verify attestation: ${e.message}` ), { code: 'EATTESTATIONVERIFY', predicateType, keyid, signature, resolved: mani._resolved, integrity: mani._integrity, }) } } mani._attestations = dist.attestations } else { mani._attestations = dist.attestations } } } this.package = mani return this.package } [_.tarballFromResolved] () { // we use a RemoteFetcher to get the actual tarball stream return new RemoteFetcher(this.resolved, { ...this.opts, resolved: this.resolved, pkgid: `registry:${this.spec.name}@${this.resolved}`, })[_.tarballFromResolved]() } get types () { return [ 'tag', 'version', 'range', ] } } module.exports = RegistryFetcher PK ~\6((pacote/lib/index.jsnu[const { get } = require('./fetcher.js') const GitFetcher = require('./git.js') const RegistryFetcher = require('./registry.js') const FileFetcher = require('./file.js') const DirFetcher = require('./dir.js') const RemoteFetcher = require('./remote.js') const tarball = (spec, opts) => get(spec, opts).tarball() tarball.stream = (spec, handler, opts) => get(spec, opts).tarballStream(handler) tarball.file = (spec, dest, opts) => get(spec, opts).tarballFile(dest) module.exports = { GitFetcher, RegistryFetcher, FileFetcher, DirFetcher, RemoteFetcher, resolve: (spec, opts) => get(spec, opts).resolve(), extract: (spec, dest, opts) => get(spec, opts).extract(dest), manifest: (spec, opts) => get(spec, opts).manifest(), packument: (spec, opts) => get(spec, opts).packument(), tarball, } PK ~\@@pacote/lib/fetcher.jsnu[// This is the base class that the other fetcher types in lib // all descend from. // It handles the unpacking and retry logic that is shared among // all of the other Fetcher types. const { basename, dirname } = require('node:path') const { rm, mkdir } = require('node:fs/promises') const PackageJson = require('@npmcli/package-json') const cacache = require('cacache') const fsm = require('fs-minipass') const getContents = require('@npmcli/installed-package-contents') const npa = require('npm-package-arg') const retry = require('promise-retry') const ssri = require('ssri') const tar = require('tar') const { Minipass } = require('minipass') const { log } = require('proc-log') const _ = require('./util/protected.js') const cacheDir = require('./util/cache-dir.js') const isPackageBin = require('./util/is-package-bin.js') const removeTrailingSlashes = require('./util/trailing-slashes.js') // Pacote is only concerned with the package.json contents const packageJsonPrepare = (p) => PackageJson.prepare(p).then(pkg => pkg.content) const packageJsonNormalize = (p) => PackageJson.normalize(p).then(pkg => pkg.content) class FetcherBase { constructor (spec, opts) { if (!opts || typeof opts !== 'object') { throw new TypeError('options object is required') } this.spec = npa(spec, opts.where) this.allowGitIgnore = !!opts.allowGitIgnore // a bit redundant because presumably the caller already knows this, // but it makes it easier to not have to keep track of the requested // spec when we're dispatching thousands of these at once, and normalizing // is nice. saveSpec is preferred if set, because it turns stuff like // x/y#committish into github:x/y#committish. use name@rawSpec for // registry deps so that we turn xyz and xyz@ -> xyz@ this.from = this.spec.registry ? `${this.spec.name}@${this.spec.rawSpec}` : this.spec.saveSpec this.#assertType() // clone the opts object so that others aren't upset when we mutate it // by adding/modifying the integrity value. this.opts = { ...opts } this.cache = opts.cache || cacheDir().cacache this.tufCache = opts.tufCache || cacheDir().tufcache this.resolved = opts.resolved || null // default to caching/verifying with sha512, that's what we usually have // need to change this default, or start overriding it, when sha512 // is no longer strong enough. this.defaultIntegrityAlgorithm = opts.defaultIntegrityAlgorithm || 'sha512' if (typeof opts.integrity === 'string') { this.opts.integrity = ssri.parse(opts.integrity) } this.package = null this.type = this.constructor.name this.fmode = opts.fmode || 0o666 this.dmode = opts.dmode || 0o777 // we don't need a default umask, because we don't chmod files coming // out of package tarballs. they're forced to have a mode that is // valid, regardless of what's in the tarball entry, and then we let // the process's umask setting do its job. but if configured, we do // respect it. this.umask = opts.umask || 0 this.preferOnline = !!opts.preferOnline this.preferOffline = !!opts.preferOffline this.offline = !!opts.offline this.before = opts.before this.fullMetadata = this.before ? true : !!opts.fullMetadata this.fullReadJson = !!opts.fullReadJson this[_.readPackageJson] = this.fullReadJson ? packageJsonPrepare : packageJsonNormalize // rrh is a registry hostname or 'never' or 'always' // defaults to registry.npmjs.org this.replaceRegistryHost = (!opts.replaceRegistryHost || opts.replaceRegistryHost === 'npmjs') ? 'registry.npmjs.org' : opts.replaceRegistryHost this.defaultTag = opts.defaultTag || 'latest' this.registry = removeTrailingSlashes(opts.registry || 'https://registry.npmjs.org') // command to run 'prepare' scripts on directories and git dirs // To use pacote with yarn, for example, set npmBin to 'yarn' // and npmCliConfig with yarn's equivalents. this.npmBin = opts.npmBin || 'npm' // command to install deps for preparing this.npmInstallCmd = opts.npmInstallCmd || ['install', '--force'] // XXX fill more of this in based on what we know from this.opts // we explicitly DO NOT fill in --tag, though, since we are often // going to be packing in the context of a publish, which may set // a dist-tag, but certainly wants to keep defaulting to latest. this.npmCliConfig = opts.npmCliConfig || [ `--cache=${dirname(this.cache)}`, `--prefer-offline=${!!this.preferOffline}`, `--prefer-online=${!!this.preferOnline}`, `--offline=${!!this.offline}`, ...(this.before ? [`--before=${this.before.toISOString()}`] : []), '--no-progress', '--no-save', '--no-audit', // override any omit settings from the environment '--include=dev', '--include=peer', '--include=optional', // we need the actual things, not just the lockfile '--no-package-lock-only', '--no-dry-run', ] } get integrity () { return this.opts.integrity || null } set integrity (i) { if (!i) { return } i = ssri.parse(i) const current = this.opts.integrity // do not ever update an existing hash value, but do // merge in NEW algos and hashes that we don't already have. if (current) { current.merge(i) } else { this.opts.integrity = i } } get notImplementedError () { return new Error('not implemented in this fetcher type: ' + this.type) } // override in child classes // Returns a Promise that resolves to this.resolved string value resolve () { return this.resolved ? Promise.resolve(this.resolved) : Promise.reject(this.notImplementedError) } packument () { return Promise.reject(this.notImplementedError) } // override in child class // returns a manifest containing: // - name // - version // - _resolved // - _integrity // - plus whatever else was in there (corgi, full metadata, or pj file) manifest () { return Promise.reject(this.notImplementedError) } // private, should be overridden. // Note that they should *not* calculate or check integrity or cache, // but *just* return the raw tarball data stream. [_.tarballFromResolved] () { throw this.notImplementedError } // public, should not be overridden tarball () { return this.tarballStream(stream => stream.concat().then(data => { data.integrity = this.integrity && String(this.integrity) data.resolved = this.resolved data.from = this.from return data })) } // private // Note: cacache will raise a EINTEGRITY error if the integrity doesn't match #tarballFromCache () { return cacache.get.stream.byDigest(this.cache, this.integrity, this.opts) } get [_.cacheFetches] () { return true } #istream (stream) { // if not caching this, just return it if (!this.opts.cache || !this[_.cacheFetches]) { // instead of creating a new integrity stream, we only piggyback on the // provided stream's events if (stream.hasIntegrityEmitter) { stream.on('integrity', i => this.integrity = i) return stream } const istream = ssri.integrityStream(this.opts) istream.on('integrity', i => this.integrity = i) stream.on('error', err => istream.emit('error', err)) return stream.pipe(istream) } // we have to return a stream that gets ALL the data, and proxies errors, // but then pipe from the original tarball stream into the cache as well. // To do this without losing any data, and since the cacache put stream // is not a passthrough, we have to pipe from the original stream into // the cache AFTER we pipe into the middleStream. Since the cache stream // has an asynchronous flush to write its contents to disk, we need to // defer the middleStream end until the cache stream ends. const middleStream = new Minipass() stream.on('error', err => middleStream.emit('error', err)) stream.pipe(middleStream, { end: false }) const cstream = cacache.put.stream( this.opts.cache, `pacote:tarball:${this.from}`, this.opts ) cstream.on('integrity', i => this.integrity = i) cstream.on('error', err => stream.emit('error', err)) stream.pipe(cstream) // eslint-disable-next-line promise/catch-or-return cstream.promise().catch(() => {}).then(() => middleStream.end()) return middleStream } pickIntegrityAlgorithm () { return this.integrity ? this.integrity.pickAlgorithm(this.opts) : this.defaultIntegrityAlgorithm } // TODO: check error class, once those are rolled out to our deps isDataCorruptionError (er) { return er.code === 'EINTEGRITY' || er.code === 'Z_DATA_ERROR' } // override the types getter get types () { return false } #assertType () { if (this.types && !this.types.includes(this.spec.type)) { throw new TypeError(`Wrong spec type (${ this.spec.type }) for ${ this.constructor.name }. Supported types: ${this.types.join(', ')}`) } } // We allow ENOENTs from cacache, but not anywhere else. // An ENOENT trying to read a tgz file, for example, is Right Out. isRetriableError (er) { // TODO: check error class, once those are rolled out to our deps return this.isDataCorruptionError(er) || er.code === 'ENOENT' || er.code === 'EISDIR' } // Mostly internal, but has some uses // Pass in a function which returns a promise // Function will be called 1 or more times with streams that may fail. // Retries: // Function MUST handle errors on the stream by rejecting the promise, // so that retry logic can pick it up and either retry or fail whatever // promise it was making (ie, failing extraction, etc.) // // The return value of this method is a Promise that resolves the same // as whatever the streamHandler resolves to. // // This should never be overridden by child classes, but it is public. tarballStream (streamHandler) { // Only short-circuit via cache if we have everything else we'll need, // and the user has not expressed a preference for checking online. const fromCache = ( !this.preferOnline && this.integrity && this.resolved ) ? streamHandler(this.#tarballFromCache()).catch(er => { if (this.isDataCorruptionError(er)) { log.warn('tarball', `cached data for ${ this.spec } (${this.integrity}) seems to be corrupted. Refreshing cache.`) return this.cleanupCached().then(() => { throw er }) } else { throw er } }) : null const fromResolved = er => { if (er) { if (!this.isRetriableError(er)) { throw er } log.silly('tarball', `no local data for ${ this.spec }. Extracting by manifest.`) } return this.resolve().then(() => retry(tryAgain => streamHandler(this.#istream(this[_.tarballFromResolved]())) .catch(streamErr => { // Most likely data integrity. A cache ENOENT error is unlikely // here, since we're definitely not reading from the cache, but it // IS possible that the fetch subsystem accessed the cache, and the // entry got blown away or something. Try one more time to be sure. if (this.isRetriableError(streamErr)) { log.warn('tarball', `tarball data for ${ this.spec } (${this.integrity}) seems to be corrupted. Trying again.`) return this.cleanupCached().then(() => tryAgain(streamErr)) } throw streamErr }), { retries: 1, minTimeout: 0, maxTimeout: 0 })) } return fromCache ? fromCache.catch(fromResolved) : fromResolved() } cleanupCached () { return cacache.rm.content(this.cache, this.integrity, this.opts) } #empty (path) { return getContents({ path, depth: 1 }).then(contents => Promise.all( contents.map(entry => rm(entry, { recursive: true, force: true })))) } async #mkdir (dest) { await this.#empty(dest) return await mkdir(dest, { recursive: true }) } // extraction is always the same. the only difference is where // the tarball comes from. async extract (dest) { await this.#mkdir(dest) return this.tarballStream((tarball) => this.#extract(dest, tarball)) } #toFile (dest) { return this.tarballStream(str => new Promise((res, rej) => { const writer = new fsm.WriteStream(dest) str.on('error', er => writer.emit('error', er)) writer.on('error', er => rej(er)) writer.on('close', () => res({ integrity: this.integrity && String(this.integrity), resolved: this.resolved, from: this.from, })) str.pipe(writer) })) } // don't use this.#mkdir because we don't want to rimraf anything async tarballFile (dest) { const dir = dirname(dest) await mkdir(dir, { recursive: true }) return this.#toFile(dest) } #extract (dest, tarball) { const extractor = tar.x(this.#tarxOptions({ cwd: dest })) const p = new Promise((resolve, reject) => { extractor.on('end', () => { resolve({ resolved: this.resolved, integrity: this.integrity && String(this.integrity), from: this.from, }) }) extractor.on('error', er => { log.warn('tar', er.message) log.silly('tar', er) reject(er) }) tarball.on('error', er => reject(er)) }) tarball.pipe(extractor) return p } // always ensure that entries are at least as permissive as our configured // dmode/fmode, but never more permissive than the umask allows. #entryMode (path, mode, type) { const m = /Directory|GNUDumpDir/.test(type) ? this.dmode : /File$/.test(type) ? this.fmode : /* istanbul ignore next - should never happen in a pkg */ 0 // make sure package bins are executable const exe = isPackageBin(this.package, path) ? 0o111 : 0 // always ensure that files are read/writable by the owner return ((mode | m) & ~this.umask) | exe | 0o600 } #tarxOptions ({ cwd }) { const sawIgnores = new Set() return { cwd, noChmod: true, noMtime: true, filter: (name, entry) => { if (/Link$/.test(entry.type)) { return false } entry.mode = this.#entryMode(entry.path, entry.mode, entry.type) // this replicates the npm pack behavior where .gitignore files // are treated like .npmignore files, but only if a .npmignore // file is not present. if (/File$/.test(entry.type)) { const base = basename(entry.path) if (base === '.npmignore') { sawIgnores.add(entry.path) } else if (base === '.gitignore' && !this.allowGitIgnore) { // rename, but only if there's not already a .npmignore const ni = entry.path.replace(/\.gitignore$/, '.npmignore') if (sawIgnores.has(ni)) { return false } entry.path = ni } return true } }, strip: 1, onwarn: /* istanbul ignore next - we can trust that tar logs */ (code, msg, data) => { log.warn('tar', code, msg) log.silly('tar', code, msg, data) }, umask: this.umask, // always ignore ownership info from tarball metadata preserveOwner: false, } } } module.exports = FetcherBase // Child classes const GitFetcher = require('./git.js') const RegistryFetcher = require('./registry.js') const FileFetcher = require('./file.js') const DirFetcher = require('./dir.js') const RemoteFetcher = require('./remote.js') // Get an appropriate fetcher object from a spec and options FetcherBase.get = (rawSpec, opts = {}) => { const spec = npa(rawSpec, opts.where) switch (spec.type) { case 'git': return new GitFetcher(spec, opts) case 'remote': return new RemoteFetcher(spec, opts) case 'version': case 'range': case 'tag': case 'alias': return new RegistryFetcher(spec.subSpec || spec, opts) case 'file': return new FileFetcher(spec, opts) case 'directory': return new DirFetcher(spec, opts) default: throw new TypeError('Unknown spec type: ' + spec.type) } } PK ~\"; ; pacote/lib/dir.jsnu[const { resolve } = require('node:path') const packlist = require('npm-packlist') const runScript = require('@npmcli/run-script') const tar = require('tar') const { Minipass } = require('minipass') const Fetcher = require('./fetcher.js') const FileFetcher = require('./file.js') const _ = require('./util/protected.js') const tarCreateOptions = require('./util/tar-create-options.js') class DirFetcher extends Fetcher { constructor (spec, opts) { super(spec, opts) // just the fully resolved filename this.resolved = this.spec.fetchSpec this.tree = opts.tree || null this.Arborist = opts.Arborist || null } // exposes tarCreateOptions as public API static tarCreateOptions (manifest) { return tarCreateOptions(manifest) } get types () { return ['directory'] } #prepareDir () { return this.manifest().then(mani => { if (!mani.scripts || !mani.scripts.prepare) { return } // we *only* run prepare. // pre/post-pack is run by the npm CLI for publish and pack, // but this function is *also* run when installing git deps const stdio = this.opts.foregroundScripts ? 'inherit' : 'pipe' return runScript({ pkg: mani, event: 'prepare', path: this.resolved, stdio, env: { npm_package_resolved: this.resolved, npm_package_integrity: this.integrity, npm_package_json: resolve(this.resolved, 'package.json'), }, }) }) } [_.tarballFromResolved] () { if (!this.tree && !this.Arborist) { throw new Error('DirFetcher requires either a tree or an Arborist constructor to pack') } const stream = new Minipass() stream.resolved = this.resolved stream.integrity = this.integrity const { prefix, workspaces } = this.opts // run the prepare script, get the list of files, and tar it up // pipe to the stream, and proxy errors the chain. this.#prepareDir() .then(async () => { if (!this.tree) { const arb = new this.Arborist({ path: this.resolved }) this.tree = await arb.loadActual() } return packlist(this.tree, { path: this.resolved, prefix, workspaces }) }) .then(files => tar.c(tarCreateOptions(this.package), files) .on('error', er => stream.emit('error', er)).pipe(stream)) .catch(er => stream.emit('error', er)) return stream } manifest () { if (this.package) { return Promise.resolve(this.package) } return this[_.readPackageJson](this.resolved) .then(mani => this.package = { ...mani, _integrity: this.integrity && String(this.integrity), _resolved: this.resolved, _from: this.from, }) } packument () { return FileFetcher.prototype.packument.apply(this) } } module.exports = DirFetcher PK ~\(88!pacote/lib/util/is-package-bin.jsnu[// Function to determine whether a path is in the package.bin set. // Used to prevent issues when people publish a package from a // windows machine, and then install with --no-bin-links. // // Note: this is not possible in remote or file fetchers, since // we don't have the manifest until AFTER we've unpacked. But the // main use case is registry fetching with git a distant second, // so that's an acceptable edge case to not handle. const binObj = (name, bin) => typeof bin === 'string' ? { [name]: bin } : bin const hasBin = (pkg, path) => { const bin = binObj(pkg.name, pkg.bin) const p = path.replace(/^[^\\/]*\//, '') for (const kv of Object.entries(bin)) { if (kv[1] === p) { return true } } return false } module.exports = (pkg, path) => pkg && pkg.bin ? hasBin(pkg, path) : false PK ~\ Ilbbpacote/lib/util/cache-dir.jsnu[const { resolve } = require('node:path') const { tmpdir, homedir } = require('node:os') module.exports = (fakePlatform = false) => { const temp = tmpdir() const uidOrPid = process.getuid ? process.getuid() : process.pid const home = homedir() || resolve(temp, 'npm-' + uidOrPid) const platform = fakePlatform || process.platform const cacheExtra = platform === 'win32' ? 'npm-cache' : '.npm' const cacheRoot = (platform === 'win32' && process.env.LOCALAPPDATA) || home return { cacache: resolve(cacheRoot, cacheExtra, '_cacache'), tufcache: resolve(cacheRoot, cacheExtra, '_tuf'), } } PK ~\ϒ%pacote/lib/util/tar-create-options.jsnu[const isPackageBin = require('./is-package-bin.js') const tarCreateOptions = manifest => ({ cwd: manifest._resolved, prefix: 'package/', portable: true, gzip: { // forcing the level to 9 seems to avoid some // platform specific optimizations that cause // integrity mismatch errors due to differing // end results after compression level: 9, }, // ensure that package bins are always executable // Note that npm-packlist is already filtering out // anything that is not a regular file, ignored by // .npmignore or package.json "files", etc. filter: (path, stat) => { if (isPackageBin(manifest, path)) { stat.mode |= 0o111 } return true }, // Provide a specific date in the 1980s for the benefit of zip, // which is confounded by files dated at the Unix epoch 0. mtime: new Date('1985-10-26T08:15:00.000Z'), }) module.exports = tarCreateOptions PK ~\#j#pacote/lib/util/trailing-slashes.jsnu[const removeTrailingSlashes = (input) => { // in order to avoid regexp redos detection let output = input while (output.endsWith('/')) { output = output.slice(0, -1) } return output } module.exports = removeTrailingSlashes PK ~\4,8pacote/lib/util/protected.jsnu[module.exports = { cacheFetches: Symbol.for('pacote.Fetcher._cacheFetches'), readPackageJson: Symbol.for('package.Fetcher._readPackageJson'), tarballFromResolved: Symbol.for('pacote.Fetcher._tarballFromResolved'), } PK ~\bpacote/lib/util/add-git-sha.jsnu[// add a sha to a git remote url spec const addGitSha = (spec, sha) => { if (spec.hosted) { const h = spec.hosted const opt = { noCommittish: true } const base = h.https && h.auth ? h.https(opt) : h.shortcut(opt) return `${base}#${sha}` } else { // don't use new URL for this, because it doesn't handle scp urls return spec.rawSpec.replace(/#.*$/, '') + `#${sha}` } } module.exports = addGitSha PK ~\&rp@77pacote/lib/util/npm.jsnu[// run an npm command const spawn = require('@npmcli/promise-spawn') module.exports = (npmBin, npmCommand, cwd, env, extra) => { const isJS = npmBin.endsWith('.js') const cmd = isJS ? process.execPath : npmBin const args = (isJS ? [npmBin] : []).concat(npmCommand) // when installing to run the `prepare` script for a git dep, we need // to ensure that we don't run into a cycle of checking out packages // in temp directories. this lets us link previously-seen repos that // are also being prepared. return spawn(cmd, args, { cwd, env }, extra) } PK ~\;'~ pacote/lib/file.jsnu[const { resolve } = require('node:path') const { stat, chmod } = require('node:fs/promises') const cacache = require('cacache') const fsm = require('fs-minipass') const Fetcher = require('./fetcher.js') const _ = require('./util/protected.js') class FileFetcher extends Fetcher { constructor (spec, opts) { super(spec, opts) // just the fully resolved filename this.resolved = this.spec.fetchSpec } get types () { return ['file'] } manifest () { if (this.package) { return Promise.resolve(this.package) } // have to unpack the tarball for this. return cacache.tmp.withTmp(this.cache, this.opts, dir => this.extract(dir) .then(() => this[_.readPackageJson](dir)) .then(mani => this.package = { ...mani, _integrity: this.integrity && String(this.integrity), _resolved: this.resolved, _from: this.from, })) } #exeBins (pkg, dest) { if (!pkg.bin) { return Promise.resolve() } return Promise.all(Object.keys(pkg.bin).map(async k => { const script = resolve(dest, pkg.bin[k]) // Best effort. Ignore errors here, the only result is that // a bin script is not executable. But if it's missing or // something, we just leave it for a later stage to trip over // when we can provide a more useful contextual error. try { const st = await stat(script) const mode = st.mode | 0o111 if (mode === st.mode) { return } await chmod(script, mode) } catch { // Ignore errors here } })) } extract (dest) { // if we've already loaded the manifest, then the super got it. // but if not, read the unpacked manifest and chmod properly. return super.extract(dest) .then(result => this.package ? result : this[_.readPackageJson](dest).then(pkg => this.#exeBins(pkg, dest)).then(() => result)) } [_.tarballFromResolved] () { // create a read stream and return it return new fsm.ReadStream(this.resolved) } packument () { // simulate based on manifest return this.manifest().then(mani => ({ name: mani.name, 'dist-tags': { [this.defaultTag]: mani.version, }, versions: { [mani.version]: { ...mani, dist: { tarball: `file:${this.resolved}`, integrity: this.integrity && String(this.integrity), }, }, }, })) } } module.exports = FileFetcher PK ~\ ve e pacote/lib/remote.jsnu[const fetch = require('npm-registry-fetch') const { Minipass } = require('minipass') const Fetcher = require('./fetcher.js') const FileFetcher = require('./file.js') const _ = require('./util/protected.js') const pacoteVersion = require('../package.json').version class RemoteFetcher extends Fetcher { constructor (spec, opts) { super(spec, opts) this.resolved = this.spec.fetchSpec const resolvedURL = new URL(this.resolved) if (this.replaceRegistryHost !== 'never' && (this.replaceRegistryHost === 'always' || this.replaceRegistryHost === resolvedURL.host)) { this.resolved = new URL(resolvedURL.pathname, this.registry).href } // nam is a fermented pork sausage that is good to eat const nameat = this.spec.name ? `${this.spec.name}@` : '' this.pkgid = opts.pkgid ? opts.pkgid : `remote:${nameat}${this.resolved}` } // Don't need to cache tarball fetches in pacote, because make-fetch-happen // will write into cacache anyway. get [_.cacheFetches] () { return false } [_.tarballFromResolved] () { const stream = new Minipass() stream.hasIntegrityEmitter = true const fetchOpts = { ...this.opts, headers: this.#headers(), spec: this.spec, integrity: this.integrity, algorithms: [this.pickIntegrityAlgorithm()], } // eslint-disable-next-line promise/always-return fetch(this.resolved, fetchOpts).then(res => { res.body.on('error', /* istanbul ignore next - exceedingly rare and hard to simulate */ er => stream.emit('error', er) ) res.body.on('integrity', i => { this.integrity = i stream.emit('integrity', i) }) res.body.pipe(stream) }).catch(er => stream.emit('error', er)) return stream } #headers () { return { // npm will override this, but ensure that we always send *something* 'user-agent': this.opts.userAgent || `pacote/${pacoteVersion} node/${process.version}`, ...(this.opts.headers || {}), 'pacote-version': pacoteVersion, 'pacote-req-type': 'tarball', 'pacote-pkg-id': this.pkgid, ...(this.integrity ? { 'pacote-integrity': String(this.integrity) } : {}), ...(this.opts.headers || {}), } } get types () { return ['remote'] } // getting a packument and/or manifest is the same as with a file: spec. // unpack the tarball stream, and then read from the package.json file. packument () { return FileFetcher.prototype.packument.apply(this) } manifest () { return FileFetcher.prototype.manifest.apply(this) } } module.exports = RemoteFetcher PK ~\opacote/LICENSEnu[The ISC License Copyright (c) Isaac Z. Schlueter, Kat Marchán, npm, Inc., and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\+ppacote/bin/index.jsnu[#!/usr/bin/env node const run = conf => { const pacote = require('../') switch (conf._[0]) { case 'resolve': case 'manifest': case 'packument': if (conf._[0] === 'resolve' && conf.long) { return pacote.manifest(conf._[1], conf).then(mani => ({ resolved: mani._resolved, integrity: mani._integrity, from: mani._from, })) } return pacote[conf._[0]](conf._[1], conf) case 'tarball': if (!conf._[2] || conf._[2] === '-') { return pacote.tarball.stream(conf._[1], stream => { stream.pipe( conf.testStdout || /* istanbul ignore next */ process.stdout ) // make sure it resolves something falsey return stream.promise().then(() => { return false }) }, conf) } else { return pacote.tarball.file(conf._[1], conf._[2], conf) } case 'extract': return pacote.extract(conf._[1], conf._[2], conf) default: /* istanbul ignore next */ { throw new Error(`bad command: ${conf._[0]}`) } } } const version = require('../package.json').version const usage = () => `Pacote - The JavaScript Package Handler, v${version} Usage: pacote resolve Resolve a specifier and output the fully resolved target Returns integrity and from if '--long' flag is set. pacote manifest Fetch a manifest and print to stdout pacote packument Fetch a full packument and print to stdout pacote tarball [] Fetch a package tarball and save to If is missing or '-', the tarball will be streamed to stdout. pacote extract Extract a package to the destination folder. Configuration values all match the names of configs passed to npm, or options passed to Pacote. Additional flags for this executable: --long Print an object from 'resolve', including integrity and spec. --json Print result objects as JSON rather than node's default. (This is the default if stdout is not a TTY.) --help -h Print this helpful text. For example '--cache=/path/to/folder' will use that folder as the cache. ` const shouldJSON = (conf, result) => conf.json || !process.stdout.isTTY && conf.json === undefined && result && typeof result === 'object' const pretty = (conf, result) => shouldJSON(conf, result) ? JSON.stringify(result, 0, 2) : result let addedLogListener = false const main = args => { const conf = parse(args) if (conf.help || conf.h) { return console.log(usage()) } if (!addedLogListener) { process.on('log', console.error) addedLogListener = true } try { return run(conf) .then(result => result && console.log(pretty(conf, result))) .catch(er => { console.error(er) process.exit(1) }) } catch (er) { console.error(er.message) console.error(usage()) } } const parseArg = arg => { const split = arg.slice(2).split('=') const k = split.shift() const v = split.join('=') const no = /^no-/.test(k) && !v const key = (no ? k.slice(3) : k) .replace(/^tag$/, 'defaultTag') .replace(/-([a-z])/g, (_, c) => c.toUpperCase()) const value = v ? v.replace(/^~/, process.env.HOME) : !no return { key, value } } const parse = args => { const conf = { _: [], cache: process.env.HOME + '/.npm/_cacache', } let dashdash = false args.forEach(arg => { if (dashdash) { conf._.push(arg) } else if (arg === '--') { dashdash = true } else if (arg === '-h') { conf.help = true } else if (/^--/.test(arg)) { const { key, value } = parseArg(arg) conf[key] = value } else { conf._.push(arg) } }) return conf } if (module === require.main) { main(process.argv.slice(2)) } else { module.exports = { main, run, usage, parseArg, parse, } } PK ~\--pacote/README.mdnu[# pacote Fetches package manifests and tarballs from the npm registry. ## USAGE ```js const pacote = require('pacote') // get a package manifest pacote.manifest('foo@1.x').then(manifest => console.log('got it', manifest)) // extract a package into a folder pacote.extract('github:npm/cli', 'some/path', options) .then(({from, resolved, integrity}) => { console.log('extracted!', from, resolved, integrity) }) pacote.tarball('https://server.com/package.tgz').then(data => { console.log('got ' + data.length + ' bytes of tarball data') }) ``` `pacote` works with any kind of package specifier that npm can install. If you can pass it to the npm CLI, you can pass it to pacote. (In fact, that's exactly what the npm CLI does.) Anything that you can do with one kind of package, you can do with another. Data that isn't relevant (like a packument for a tarball) will be simulated. `prepare` scripts will be run when generating tarballs from `git` and `directory` locations, to simulate what _would_ be published to the registry, so that you get a working package instead of just raw source code that might need to be transpiled. ## CLI This module exports a command line interface that can do most of what is described below. Run `pacote -h` to learn more. ``` Pacote - The JavaScript Package Handler, v10.1.1 Usage: pacote resolve Resolve a specifier and output the fully resolved target Returns integrity and from if '--long' flag is set. pacote manifest Fetch a manifest and print to stdout pacote packument Fetch a full packument and print to stdout pacote tarball [] Fetch a package tarball and save to If is missing or '-', the tarball will be streamed to stdout. pacote extract Extract a package to the destination folder. Configuration values all match the names of configs passed to npm, or options passed to Pacote. Additional flags for this executable: --long Print an object from 'resolve', including integrity and spec. --json Print result objects as JSON rather than node's default. (This is the default if stdout is not a TTY.) --help -h Print this helpful text. For example '--cache=/path/to/folder' will use that folder as the cache. ``` ## API The `spec` refers to any kind of package specifier that npm can install. If you can pass it to the npm CLI, you can pass it to pacote. (In fact, that's exactly what the npm CLI does.) See below for valid `opts` values. * `pacote.resolve(spec, opts)` Resolve a specifier like `foo@latest` or `github:user/project` all the way to a tarball url, tarball file, or git repo with commit hash. * `pacote.extract(spec, dest, opts)` Extract a package's tarball into a destination folder. Returns a promise that resolves to the `{from,resolved,integrity}` of the extracted package. * `pacote.manifest(spec, opts)` Fetch (or simulate) a package's manifest (basically, the `package.json` file, plus a bit of metadata). See below for more on manifests and packuments. Returns a Promise that resolves to the manifest object. * `pacote.packument(spec, opts)` Fetch (or simulate) a package's packument (basically, the top-level package document listing all the manifests that the registry returns). See below for more on manifests and packuments. Returns a Promise that resolves to the packument object. * `pacote.tarball(spec, opts)` Get a package tarball data as a buffer in memory. Returns a Promise that resolves to the tarball data Buffer, with `from`, `resolved`, and `integrity` fields attached. * `pacote.tarball.file(spec, dest, opts)` Save a package tarball data to a file on disk. Returns a Promise that resolves to `{from,integrity,resolved}` of the fetched tarball. * `pacote.tarball.stream(spec, streamHandler, opts)` Fetch a tarball and make the stream available to the `streamHandler` function. This is mostly an internal function, but it is exposed because it does provide some functionality that may be difficult to achieve otherwise. The `streamHandler` function MUST return a Promise that resolves when the stream (and all associated work) is ended, or rejects if the stream has an error. The `streamHandler` function MAY be called multiple times, as Pacote retries requests in some scenarios, such as cache corruption or retriable network failures. ### Options Options are passed to [`npm-registry-fetch`](http://npm.im/npm-registry-fetch) and [`cacache`](http://npm.im/cacache), so in addition to these, anything for those modules can be given to pacote as well. Options object is cloned, and mutated along the way to add integrity, resolved, and other properties, as they are determined. * `cache` Where to store cache entries and temp files. Passed to [`cacache`](http://npm.im/cacache). Defaults to the same cache directory that npm will use by default, based on platform and environment. * `where` Base folder for resolving relative `file:` dependencies. * `resolved` Shortcut for looking up resolved values. Should be specified if known. * `integrity` Expected integrity of fetched package tarball. If specified, tarballs with mismatched integrity values will raise an `EINTEGRITY` error. * `umask` Permission mode mask for extracted files and directories. Defaults to `0o22`. See "Extracted File Modes" below. * `fmode` Minimum permission mode for extracted files. Defaults to `0o666`. See "Extracted File Modes" below. * `dmode` Minimum permission mode for extracted directories. Defaults to `0o777`. See "Extracted File Modes" below. * `preferOnline` Prefer to revalidate cache entries, even when it would not be strictly necessary. Default `false`. * `before` When picking a manifest from a packument, only consider packages published before the specified date. Default `null`. * `defaultTag` The default `dist-tag` to use when choosing a manifest from a packument. Defaults to `latest`. * `registry` The npm registry to use by default. Defaults to `https://registry.npmjs.org/`. * `fullMetadata` Fetch the full metadata from the registry for packuments, including information not strictly required for installation (author, description, etc.) Defaults to `true` when `before` is set, since the version publish time is part of the extended packument metadata. * `fullReadJson` Use the slower `read-package-json` package insted of `read-package-json-fast` in order to include extra fields like "readme" in the manifest. Defaults to `false`. * `packumentCache` For registry packuments only, you may provide a `Map` object which will be used to cache packument requests between pacote calls. This allows you to easily avoid hitting the registry multiple times (even just to validate the cache) for a given packument, since it is unlikely to change in the span of a single command. * `verifySignatures` A boolean that will make pacote verify the integrity signature of a manifest, if present. There must be a configured `_keys` entry in the config that is scoped to the registry the manifest is being fetched from. * `verifyAttestations` A boolean that will make pacote verify Sigstore attestations, if present. There must be a configured `_keys` entry in the config that is scoped to the registry the manifest is being fetched from. * `tufCache` Where to store metadata/target files when retrieving the package attestation key material via TUF. Defaults to the same cache directory that npm will use by default, based on platform and environment. ### Advanced API Each different type of fetcher is exposed for more advanced usage such as using helper methods from this classes: * `DirFetcher` * `FileFetcher` * `GitFetcher` * `RegistryFetcher` * `RemoteFetcher` ## Extracted File Modes Files are extracted with a mode matching the following formula: ``` ( (tarball entry mode value) | (minimum mode option) ) ~ (umask) ``` This is in order to prevent unreadable files or unlistable directories from cluttering a project's `node_modules` folder, even if the package tarball specifies that the file should be inaccessible. It also prevents files from being group- or world-writable without explicit opt-in by the user, because all file and directory modes are masked against the `umask` value. So, a file which is `0o771` in the tarball, using the default `fmode` of `0o666` and `umask` of `0o22`, will result in a file mode of `0o755`: ``` (0o771 | 0o666) => 0o777 (0o777 ~ 0o22) => 0o755 ``` In almost every case, the defaults are appropriate. To respect exactly what is in the package tarball (even if this makes an unusable system), set both `dmode` and `fmode` options to `0`. Otherwise, the `umask` config should be used in most cases where file mode modifications are required, and this functions more or less the same as the `umask` value in most Unix systems. ## Extracted File Ownership When running as `root` on Unix systems, all extracted files and folders will have their owning `uid` and `gid` values set to match the ownership of the containing folder. This prevents `root`-owned files showing up in a project's `node_modules` folder when a user runs `sudo npm install`. ## Manifests A `manifest` is similar to a `package.json` file. However, it has a few pieces of extra metadata, and sometimes lacks metadata that is inessential to package installation. In addition to the common `package.json` fields, manifests include: * `manifest._resolved` The tarball url or file path where the package artifact can be found. * `manifest._from` A normalized form of the spec passed in as an argument. * `manifest._integrity` The integrity value for the package artifact. * `manifest._id` The canonical spec of this package version: name@version. * `manifest.dist` Registry manifests (those included in a packument) have a `dist` object. Only `tarball` is required, though at least one of `shasum` or `integrity` is almost always present. * `tarball` The url to the associated package artifact. (Copied by Pacote to `manifest._resolved`.) * `integrity` The integrity SRI string for the artifact. This may not be present for older packages on the npm registry. (Copied by Pacote to `manifest._integrity`.) * `shasum` Legacy integrity value. Hexadecimal-encoded sha1 hash. (Converted to an SRI string and copied by Pacote to `manifest._integrity` when `dist.integrity` is not present.) * `fileCount` Number of files in the tarball. * `unpackedSize` Size on disk of the package when unpacked. * `signatures` Signatures of the shasum. Includes the keyid that correlates to a [`key from the npm registry`](https://registry.npmjs.org/-/npm/v1/keys) ## Packuments A packument is the top-level package document that lists the set of manifests for available versions for a package. When a packument is fetched with `accept: application/vnd.npm.install-v1+json` in the HTTP headers, only the most minimum necessary metadata is returned. Additional metadata is returned when fetched with only `accept: application/json`. For Pacote's purposes, the following fields are relevant: * `versions` An object where each key is a version, and each value is the manifest for that version. * `dist-tags` An object mapping dist-tags to version numbers. This is how `foo@latest` gets turned into `foo@1.2.3`. * `time` In the full packument, an object mapping version numbers to publication times, for the `opts.before` functionality. Pacote adds the following field, regardless of the accept header: * `_contentLength` The size of the packument. PK ~\aMlQ Q cacache/package.jsonnu[{ "_id": "cacache@18.0.3", "_inBundle": true, "_location": "/npm/cacache", "_phantomChildren": {}, "_requiredBy": [ "/npm", "/npm/@npmcli/arborist", "/npm/@npmcli/metavuln-calculator", "/npm/make-fetch-happen", "/npm/pacote" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/cacache/issues" }, "cache-version": { "content": "2", "index": "5" }, "dependencies": { "@npmcli/fs": "^3.1.0", "fs-minipass": "^3.0.0", "glob": "^10.2.2", "lru-cache": "^10.0.1", "minipass": "^7.0.3", "minipass-collect": "^2.0.1", "minipass-flush": "^1.0.5", "minipass-pipeline": "^1.2.4", "p-map": "^4.0.0", "ssri": "^10.0.0", "tar": "^6.1.11", "unique-filename": "^3.0.0" }, "description": "Fast, fault-tolerant, cross-platform, disk-based, data-agnostic, content-addressable cache.", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.22.0", "tap": "^16.0.0" }, "engines": { "node": "^16.14.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/cacache#readme", "keywords": [ "cache", "caching", "content-addressable", "sri", "sri hash", "subresource integrity", "cache", "storage", "store", "file store", "filesystem", "disk cache", "disk storage" ], "license": "ISC", "main": "lib/index.js", "name": "cacache", "repository": { "type": "git", "url": "git+https://github.com/npm/cacache.git" }, "scripts": { "coverage": "tap", "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "npmclilint": "npmcli-lint", "postlint": "template-oss-check", "postsnap": "npm run lintfix --", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap", "test-docker": "docker run -it --rm --name pacotest -v \"$PWD\":/tmp -w /tmp node:latest npm test" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "windowsCI": false, "version": "4.22.0", "publish": "true" }, "version": "18.0.3" } PK ~\aG#uucacache/lib/content/write.jsnu['use strict' const events = require('events') const contentPath = require('./path') const fs = require('fs/promises') const { moveFile } = require('@npmcli/fs') const { Minipass } = require('minipass') const Pipeline = require('minipass-pipeline') const Flush = require('minipass-flush') const path = require('path') const ssri = require('ssri') const uniqueFilename = require('unique-filename') const fsm = require('fs-minipass') module.exports = write // Cache of move operations in process so we don't duplicate const moveOperations = new Map() async function write (cache, data, opts = {}) { const { algorithms, size, integrity } = opts if (typeof size === 'number' && data.length !== size) { throw sizeError(size, data.length) } const sri = ssri.fromData(data, algorithms ? { algorithms } : {}) if (integrity && !ssri.checkData(data, integrity, opts)) { throw checksumError(integrity, sri) } for (const algo in sri) { const tmp = await makeTmp(cache, opts) const hash = sri[algo].toString() try { await fs.writeFile(tmp.target, data, { flag: 'wx' }) await moveToDestination(tmp, cache, hash, opts) } finally { if (!tmp.moved) { await fs.rm(tmp.target, { recursive: true, force: true }) } } } return { integrity: sri, size: data.length } } module.exports.stream = writeStream // writes proxied to the 'inputStream' that is passed to the Promise // 'end' is deferred until content is handled. class CacacheWriteStream extends Flush { constructor (cache, opts) { super() this.opts = opts this.cache = cache this.inputStream = new Minipass() this.inputStream.on('error', er => this.emit('error', er)) this.inputStream.on('drain', () => this.emit('drain')) this.handleContentP = null } write (chunk, encoding, cb) { if (!this.handleContentP) { this.handleContentP = handleContent( this.inputStream, this.cache, this.opts ) this.handleContentP.catch(error => this.emit('error', error)) } return this.inputStream.write(chunk, encoding, cb) } flush (cb) { this.inputStream.end(() => { if (!this.handleContentP) { const e = new Error('Cache input stream was empty') e.code = 'ENODATA' // empty streams are probably emitting end right away. // defer this one tick by rejecting a promise on it. return Promise.reject(e).catch(cb) } // eslint-disable-next-line promise/catch-or-return this.handleContentP.then( (res) => { res.integrity && this.emit('integrity', res.integrity) // eslint-disable-next-line promise/always-return res.size !== null && this.emit('size', res.size) cb() }, (er) => cb(er) ) }) } } function writeStream (cache, opts = {}) { return new CacacheWriteStream(cache, opts) } async function handleContent (inputStream, cache, opts) { const tmp = await makeTmp(cache, opts) try { const res = await pipeToTmp(inputStream, cache, tmp.target, opts) await moveToDestination( tmp, cache, res.integrity, opts ) return res } finally { if (!tmp.moved) { await fs.rm(tmp.target, { recursive: true, force: true }) } } } async function pipeToTmp (inputStream, cache, tmpTarget, opts) { const outStream = new fsm.WriteStream(tmpTarget, { flags: 'wx', }) if (opts.integrityEmitter) { // we need to create these all simultaneously since they can fire in any order const [integrity, size] = await Promise.all([ events.once(opts.integrityEmitter, 'integrity').then(res => res[0]), events.once(opts.integrityEmitter, 'size').then(res => res[0]), new Pipeline(inputStream, outStream).promise(), ]) return { integrity, size } } let integrity let size const hashStream = ssri.integrityStream({ integrity: opts.integrity, algorithms: opts.algorithms, size: opts.size, }) hashStream.on('integrity', i => { integrity = i }) hashStream.on('size', s => { size = s }) const pipeline = new Pipeline(inputStream, hashStream, outStream) await pipeline.promise() return { integrity, size } } async function makeTmp (cache, opts) { const tmpTarget = uniqueFilename(path.join(cache, 'tmp'), opts.tmpPrefix) await fs.mkdir(path.dirname(tmpTarget), { recursive: true }) return { target: tmpTarget, moved: false, } } async function moveToDestination (tmp, cache, sri) { const destination = contentPath(cache, sri) const destDir = path.dirname(destination) if (moveOperations.has(destination)) { return moveOperations.get(destination) } moveOperations.set( destination, fs.mkdir(destDir, { recursive: true }) .then(async () => { await moveFile(tmp.target, destination, { overwrite: false }) tmp.moved = true return tmp.moved }) .catch(err => { if (!err.message.startsWith('The destination file exists')) { throw Object.assign(err, { code: 'EEXIST' }) } }).finally(() => { moveOperations.delete(destination) }) ) return moveOperations.get(destination) } function sizeError (expected, found) { /* eslint-disable-next-line max-len */ const err = new Error(`Bad data size: expected inserted data to be ${expected} bytes, but got ${found} instead`) err.expected = expected err.found = found err.code = 'EBADSIZE' return err } function checksumError (expected, found) { const err = new Error(`Integrity check failed: Wanted: ${expected} Found: ${found}`) err.code = 'EINTEGRITY' err.expected = expected err.found = found return err } PK ~\D?cacache/lib/content/rm.jsnu['use strict' const fs = require('fs/promises') const contentPath = require('./path') const { hasContent } = require('./read') module.exports = rm async function rm (cache, integrity) { const content = await hasContent(cache, integrity) // ~pretty~ sure we can't end up with a content lacking sri, but be safe if (content && content.sri) { await fs.rm(contentPath(cache, content.sri), { recursive: true, force: true }) return true } else { return false } } PK ~\ |cacache/lib/content/read.jsnu['use strict' const fs = require('fs/promises') const fsm = require('fs-minipass') const ssri = require('ssri') const contentPath = require('./path') const Pipeline = require('minipass-pipeline') module.exports = read const MAX_SINGLE_READ_SIZE = 64 * 1024 * 1024 async function read (cache, integrity, opts = {}) { const { size } = opts const { stat, cpath, sri } = await withContentSri(cache, integrity, async (cpath, sri) => { // get size const stat = size ? { size } : await fs.stat(cpath) return { stat, cpath, sri } }) if (stat.size > MAX_SINGLE_READ_SIZE) { return readPipeline(cpath, stat.size, sri, new Pipeline()).concat() } const data = await fs.readFile(cpath, { encoding: null }) if (stat.size !== data.length) { throw sizeError(stat.size, data.length) } if (!ssri.checkData(data, sri)) { throw integrityError(sri, cpath) } return data } const readPipeline = (cpath, size, sri, stream) => { stream.push( new fsm.ReadStream(cpath, { size, readSize: MAX_SINGLE_READ_SIZE, }), ssri.integrityStream({ integrity: sri, size, }) ) return stream } module.exports.stream = readStream module.exports.readStream = readStream function readStream (cache, integrity, opts = {}) { const { size } = opts const stream = new Pipeline() // Set all this up to run on the stream and then just return the stream Promise.resolve().then(async () => { const { stat, cpath, sri } = await withContentSri(cache, integrity, async (cpath, sri) => { // get size const stat = size ? { size } : await fs.stat(cpath) return { stat, cpath, sri } }) return readPipeline(cpath, stat.size, sri, stream) }).catch(err => stream.emit('error', err)) return stream } module.exports.copy = copy function copy (cache, integrity, dest) { return withContentSri(cache, integrity, (cpath) => { return fs.copyFile(cpath, dest) }) } module.exports.hasContent = hasContent async function hasContent (cache, integrity) { if (!integrity) { return false } try { return await withContentSri(cache, integrity, async (cpath, sri) => { const stat = await fs.stat(cpath) return { size: stat.size, sri, stat } }) } catch (err) { if (err.code === 'ENOENT') { return false } if (err.code === 'EPERM') { /* istanbul ignore else */ if (process.platform !== 'win32') { throw err } else { return false } } } } async function withContentSri (cache, integrity, fn) { const sri = ssri.parse(integrity) // If `integrity` has multiple entries, pick the first digest // with available local data. const algo = sri.pickAlgorithm() const digests = sri[algo] if (digests.length <= 1) { const cpath = contentPath(cache, digests[0]) return fn(cpath, digests[0]) } else { // Can't use race here because a generic error can happen before // a ENOENT error, and can happen before a valid result const results = await Promise.all(digests.map(async (meta) => { try { return await withContentSri(cache, meta, fn) } catch (err) { if (err.code === 'ENOENT') { return Object.assign( new Error('No matching content found for ' + sri.toString()), { code: 'ENOENT' } ) } return err } })) // Return the first non error if it is found const result = results.find((r) => !(r instanceof Error)) if (result) { return result } // Throw the No matching content found error const enoentError = results.find((r) => r.code === 'ENOENT') if (enoentError) { throw enoentError } // Throw generic error throw results.find((r) => r instanceof Error) } } function sizeError (expected, found) { /* eslint-disable-next-line max-len */ const err = new Error(`Bad data size: expected inserted data to be ${expected} bytes, but got ${found} instead`) err.expected = expected err.found = found err.code = 'EBADSIZE' return err } function integrityError (sri, path) { const err = new Error(`Integrity verification failed for ${sri} (${path})`) err.code = 'EINTEGRITY' err.sri = sri err.path = path return err } PK ~\*cacache/lib/content/path.jsnu['use strict' const contentVer = require('../../package.json')['cache-version'].content const hashToSegments = require('../util/hash-to-segments') const path = require('path') const ssri = require('ssri') // Current format of content file path: // // sha512-BaSE64Hex= -> // ~/.my-cache/content-v2/sha512/ba/da/55deadbeefc0ffee // module.exports = contentPath function contentPath (cache, integrity) { const sri = ssri.parse(integrity, { single: true }) // contentPath is the *strongest* algo given return path.join( contentDir(cache), sri.algorithm, ...hashToSegments(sri.hexDigest()) ) } module.exports.contentDir = contentDir function contentDir (cache) { return path.join(cache, `content-v${contentVer}`) } PK ~\Jnncacache/lib/get.jsnu['use strict' const Collect = require('minipass-collect') const { Minipass } = require('minipass') const Pipeline = require('minipass-pipeline') const index = require('./entry-index') const memo = require('./memoization') const read = require('./content/read') async function getData (cache, key, opts = {}) { const { integrity, memoize, size } = opts const memoized = memo.get(cache, key, opts) if (memoized && memoize !== false) { return { metadata: memoized.entry.metadata, data: memoized.data, integrity: memoized.entry.integrity, size: memoized.entry.size, } } const entry = await index.find(cache, key, opts) if (!entry) { throw new index.NotFoundError(cache, key) } const data = await read(cache, entry.integrity, { integrity, size }) if (memoize) { memo.put(cache, entry, data, opts) } return { data, metadata: entry.metadata, size: entry.size, integrity: entry.integrity, } } module.exports = getData async function getDataByDigest (cache, key, opts = {}) { const { integrity, memoize, size } = opts const memoized = memo.get.byDigest(cache, key, opts) if (memoized && memoize !== false) { return memoized } const res = await read(cache, key, { integrity, size }) if (memoize) { memo.put.byDigest(cache, key, res, opts) } return res } module.exports.byDigest = getDataByDigest const getMemoizedStream = (memoized) => { const stream = new Minipass() stream.on('newListener', function (ev, cb) { ev === 'metadata' && cb(memoized.entry.metadata) ev === 'integrity' && cb(memoized.entry.integrity) ev === 'size' && cb(memoized.entry.size) }) stream.end(memoized.data) return stream } function getStream (cache, key, opts = {}) { const { memoize, size } = opts const memoized = memo.get(cache, key, opts) if (memoized && memoize !== false) { return getMemoizedStream(memoized) } const stream = new Pipeline() // Set all this up to run on the stream and then just return the stream Promise.resolve().then(async () => { const entry = await index.find(cache, key) if (!entry) { throw new index.NotFoundError(cache, key) } stream.emit('metadata', entry.metadata) stream.emit('integrity', entry.integrity) stream.emit('size', entry.size) stream.on('newListener', function (ev, cb) { ev === 'metadata' && cb(entry.metadata) ev === 'integrity' && cb(entry.integrity) ev === 'size' && cb(entry.size) }) const src = read.readStream( cache, entry.integrity, { ...opts, size: typeof size !== 'number' ? entry.size : size } ) if (memoize) { const memoStream = new Collect.PassThrough() memoStream.on('collect', data => memo.put(cache, entry, data, opts)) stream.unshift(memoStream) } stream.unshift(src) return stream }).catch((err) => stream.emit('error', err)) return stream } module.exports.stream = getStream function getStreamDigest (cache, integrity, opts = {}) { const { memoize } = opts const memoized = memo.get.byDigest(cache, integrity, opts) if (memoized && memoize !== false) { const stream = new Minipass() stream.end(memoized) return stream } else { const stream = read.readStream(cache, integrity, opts) if (!memoize) { return stream } const memoStream = new Collect.PassThrough() memoStream.on('collect', data => memo.put.byDigest( cache, integrity, data, opts )) return new Pipeline(stream, memoStream) } } module.exports.stream.byDigest = getStreamDigest function info (cache, key, opts = {}) { const { memoize } = opts const memoized = memo.get(cache, key, opts) if (memoized && memoize !== false) { return Promise.resolve(memoized.entry) } else { return index.find(cache, key) } } module.exports.info = info async function copy (cache, key, dest, opts = {}) { const entry = await index.find(cache, key, opts) if (!entry) { throw new index.NotFoundError(cache, key) } await read.copy(cache, entry.integrity, dest, opts) return { metadata: entry.metadata, size: entry.size, integrity: entry.integrity, } } module.exports.copy = copy async function copyByDigest (cache, key, dest, opts = {}) { await read.copy(cache, key, dest, opts) return key } module.exports.copy.byDigest = copyByDigest module.exports.hasContent = read.hasContent PK ~\ٷcacache/lib/put.jsnu['use strict' const index = require('./entry-index') const memo = require('./memoization') const write = require('./content/write') const Flush = require('minipass-flush') const { PassThrough } = require('minipass-collect') const Pipeline = require('minipass-pipeline') const putOpts = (opts) => ({ algorithms: ['sha512'], ...opts, }) module.exports = putData async function putData (cache, key, data, opts = {}) { const { memoize } = opts opts = putOpts(opts) const res = await write(cache, data, opts) const entry = await index.insert(cache, key, res.integrity, { ...opts, size: res.size }) if (memoize) { memo.put(cache, entry, data, opts) } return res.integrity } module.exports.stream = putStream function putStream (cache, key, opts = {}) { const { memoize } = opts opts = putOpts(opts) let integrity let size let error let memoData const pipeline = new Pipeline() // first item in the pipeline is the memoizer, because we need // that to end first and get the collected data. if (memoize) { const memoizer = new PassThrough().on('collect', data => { memoData = data }) pipeline.push(memoizer) } // contentStream is a write-only, not a passthrough // no data comes out of it. const contentStream = write.stream(cache, opts) .on('integrity', (int) => { integrity = int }) .on('size', (s) => { size = s }) .on('error', (err) => { error = err }) pipeline.push(contentStream) // last but not least, we write the index and emit hash and size, // and memoize if we're doing that pipeline.push(new Flush({ async flush () { if (!error) { const entry = await index.insert(cache, key, integrity, { ...opts, size }) if (memoize && memoData) { memo.put(cache, entry, memoData, opts) } pipeline.emit('integrity', integrity) pipeline.emit('size', size) } }, })) return pipeline } PK ~\cacache/lib/index.jsnu['use strict' const get = require('./get.js') const put = require('./put.js') const rm = require('./rm.js') const verify = require('./verify.js') const { clearMemoized } = require('./memoization.js') const tmp = require('./util/tmp.js') const index = require('./entry-index.js') module.exports.index = {} module.exports.index.compact = index.compact module.exports.index.insert = index.insert module.exports.ls = index.ls module.exports.ls.stream = index.lsStream module.exports.get = get module.exports.get.byDigest = get.byDigest module.exports.get.stream = get.stream module.exports.get.stream.byDigest = get.stream.byDigest module.exports.get.copy = get.copy module.exports.get.copy.byDigest = get.copy.byDigest module.exports.get.info = get.info module.exports.get.hasContent = get.hasContent module.exports.put = put module.exports.put.stream = put.stream module.exports.rm = rm.entry module.exports.rm.all = rm.all module.exports.rm.entry = module.exports.rm module.exports.rm.content = rm.content module.exports.clearMemoized = clearMemoized module.exports.tmp = {} module.exports.tmp.mkdir = tmp.mkdir module.exports.tmp.withTmp = tmp.withTmp module.exports.verify = verify module.exports.verify.lastRun = verify.lastRun PK ~\nr@##cacache/lib/entry-index.jsnu['use strict' const crypto = require('crypto') const { appendFile, mkdir, readFile, readdir, rm, writeFile, } = require('fs/promises') const { Minipass } = require('minipass') const path = require('path') const ssri = require('ssri') const uniqueFilename = require('unique-filename') const contentPath = require('./content/path') const hashToSegments = require('./util/hash-to-segments') const indexV = require('../package.json')['cache-version'].index const { moveFile } = require('@npmcli/fs') module.exports.NotFoundError = class NotFoundError extends Error { constructor (cache, key) { super(`No cache entry for ${key} found in ${cache}`) this.code = 'ENOENT' this.cache = cache this.key = key } } module.exports.compact = compact async function compact (cache, key, matchFn, opts = {}) { const bucket = bucketPath(cache, key) const entries = await bucketEntries(bucket) const newEntries = [] // we loop backwards because the bottom-most result is the newest // since we add new entries with appendFile for (let i = entries.length - 1; i >= 0; --i) { const entry = entries[i] // a null integrity could mean either a delete was appended // or the user has simply stored an index that does not map // to any content. we determine if the user wants to keep the // null integrity based on the validateEntry function passed in options. // if the integrity is null and no validateEntry is provided, we break // as we consider the null integrity to be a deletion of everything // that came before it. if (entry.integrity === null && !opts.validateEntry) { break } // if this entry is valid, and it is either the first entry or // the newEntries array doesn't already include an entry that // matches this one based on the provided matchFn, then we add // it to the beginning of our list if ((!opts.validateEntry || opts.validateEntry(entry) === true) && (newEntries.length === 0 || !newEntries.find((oldEntry) => matchFn(oldEntry, entry)))) { newEntries.unshift(entry) } } const newIndex = '\n' + newEntries.map((entry) => { const stringified = JSON.stringify(entry) const hash = hashEntry(stringified) return `${hash}\t${stringified}` }).join('\n') const setup = async () => { const target = uniqueFilename(path.join(cache, 'tmp'), opts.tmpPrefix) await mkdir(path.dirname(target), { recursive: true }) return { target, moved: false, } } const teardown = async (tmp) => { if (!tmp.moved) { return rm(tmp.target, { recursive: true, force: true }) } } const write = async (tmp) => { await writeFile(tmp.target, newIndex, { flag: 'wx' }) await mkdir(path.dirname(bucket), { recursive: true }) // we use @npmcli/move-file directly here because we // want to overwrite the existing file await moveFile(tmp.target, bucket) tmp.moved = true } // write the file atomically const tmp = await setup() try { await write(tmp) } finally { await teardown(tmp) } // we reverse the list we generated such that the newest // entries come first in order to make looping through them easier // the true passed to formatEntry tells it to keep null // integrity values, if they made it this far it's because // validateEntry returned true, and as such we should return it return newEntries.reverse().map((entry) => formatEntry(cache, entry, true)) } module.exports.insert = insert async function insert (cache, key, integrity, opts = {}) { const { metadata, size, time } = opts const bucket = bucketPath(cache, key) const entry = { key, integrity: integrity && ssri.stringify(integrity), time: time || Date.now(), size, metadata, } try { await mkdir(path.dirname(bucket), { recursive: true }) const stringified = JSON.stringify(entry) // NOTE - Cleverness ahoy! // // This works because it's tremendously unlikely for an entry to corrupt // another while still preserving the string length of the JSON in // question. So, we just slap the length in there and verify it on read. // // Thanks to @isaacs for the whiteboarding session that ended up with // this. await appendFile(bucket, `\n${hashEntry(stringified)}\t${stringified}`) } catch (err) { if (err.code === 'ENOENT') { return undefined } throw err } return formatEntry(cache, entry) } module.exports.find = find async function find (cache, key) { const bucket = bucketPath(cache, key) try { const entries = await bucketEntries(bucket) return entries.reduce((latest, next) => { if (next && next.key === key) { return formatEntry(cache, next) } else { return latest } }, null) } catch (err) { if (err.code === 'ENOENT') { return null } else { throw err } } } module.exports.delete = del function del (cache, key, opts = {}) { if (!opts.removeFully) { return insert(cache, key, null, opts) } const bucket = bucketPath(cache, key) return rm(bucket, { recursive: true, force: true }) } module.exports.lsStream = lsStream function lsStream (cache) { const indexDir = bucketDir(cache) const stream = new Minipass({ objectMode: true }) // Set all this up to run on the stream and then just return the stream Promise.resolve().then(async () => { const buckets = await readdirOrEmpty(indexDir) await Promise.all(buckets.map(async (bucket) => { const bucketPath = path.join(indexDir, bucket) const subbuckets = await readdirOrEmpty(bucketPath) await Promise.all(subbuckets.map(async (subbucket) => { const subbucketPath = path.join(bucketPath, subbucket) // "/cachename//./*" const subbucketEntries = await readdirOrEmpty(subbucketPath) await Promise.all(subbucketEntries.map(async (entry) => { const entryPath = path.join(subbucketPath, entry) try { const entries = await bucketEntries(entryPath) // using a Map here prevents duplicate keys from showing up // twice, I guess? const reduced = entries.reduce((acc, entry) => { acc.set(entry.key, entry) return acc }, new Map()) // reduced is a map of key => entry for (const entry of reduced.values()) { const formatted = formatEntry(cache, entry) if (formatted) { stream.write(formatted) } } } catch (err) { if (err.code === 'ENOENT') { return undefined } throw err } })) })) })) stream.end() return stream }).catch(err => stream.emit('error', err)) return stream } module.exports.ls = ls async function ls (cache) { const entries = await lsStream(cache).collect() return entries.reduce((acc, xs) => { acc[xs.key] = xs return acc }, {}) } module.exports.bucketEntries = bucketEntries async function bucketEntries (bucket, filter) { const data = await readFile(bucket, 'utf8') return _bucketEntries(data, filter) } function _bucketEntries (data) { const entries = [] data.split('\n').forEach((entry) => { if (!entry) { return } const pieces = entry.split('\t') if (!pieces[1] || hashEntry(pieces[1]) !== pieces[0]) { // Hash is no good! Corruption or malice? Doesn't matter! // EJECT EJECT return } let obj try { obj = JSON.parse(pieces[1]) } catch (_) { // eslint-ignore-next-line no-empty-block } // coverage disabled here, no need to test with an entry that parses to something falsey // istanbul ignore else if (obj) { entries.push(obj) } }) return entries } module.exports.bucketDir = bucketDir function bucketDir (cache) { return path.join(cache, `index-v${indexV}`) } module.exports.bucketPath = bucketPath function bucketPath (cache, key) { const hashed = hashKey(key) return path.join.apply( path, [bucketDir(cache)].concat(hashToSegments(hashed)) ) } module.exports.hashKey = hashKey function hashKey (key) { return hash(key, 'sha256') } module.exports.hashEntry = hashEntry function hashEntry (str) { return hash(str, 'sha1') } function hash (str, digest) { return crypto .createHash(digest) .update(str) .digest('hex') } function formatEntry (cache, entry, keepAll) { // Treat null digests as deletions. They'll shadow any previous entries. if (!entry.integrity && !keepAll) { return null } return { key: entry.key, integrity: entry.integrity, path: entry.integrity ? contentPath(cache, entry.integrity) : undefined, size: entry.size, time: entry.time, metadata: entry.metadata, } } function readdirOrEmpty (dir) { return readdir(dir).catch((err) => { if (err.code === 'ENOENT' || err.code === 'ENOTDIR') { return [] } throw err }) } PK ~\zfcacache/lib/rm.jsnu['use strict' const { rm } = require('fs/promises') const glob = require('./util/glob.js') const index = require('./entry-index') const memo = require('./memoization') const path = require('path') const rmContent = require('./content/rm') module.exports = entry module.exports.entry = entry function entry (cache, key, opts) { memo.clearMemoized() return index.delete(cache, key, opts) } module.exports.content = content function content (cache, integrity) { memo.clearMemoized() return rmContent(cache, integrity) } module.exports.all = all async function all (cache) { memo.clearMemoized() const paths = await glob(path.join(cache, '*(content-*|index-*)'), { silent: true, nosort: true }) return Promise.all(paths.map((p) => rm(p, { recursive: true, force: true }))) } PK ~\Pcacache/lib/memoization.jsnu['use strict' const { LRUCache } = require('lru-cache') const MEMOIZED = new LRUCache({ max: 500, maxSize: 50 * 1024 * 1024, // 50MB ttl: 3 * 60 * 1000, // 3 minutes sizeCalculation: (entry, key) => key.startsWith('key:') ? entry.data.length : entry.length, }) module.exports.clearMemoized = clearMemoized function clearMemoized () { const old = {} MEMOIZED.forEach((v, k) => { old[k] = v }) MEMOIZED.clear() return old } module.exports.put = put function put (cache, entry, data, opts) { pickMem(opts).set(`key:${cache}:${entry.key}`, { entry, data }) putDigest(cache, entry.integrity, data, opts) } module.exports.put.byDigest = putDigest function putDigest (cache, integrity, data, opts) { pickMem(opts).set(`digest:${cache}:${integrity}`, data) } module.exports.get = get function get (cache, key, opts) { return pickMem(opts).get(`key:${cache}:${key}`) } module.exports.get.byDigest = getDigest function getDigest (cache, integrity, opts) { return pickMem(opts).get(`digest:${cache}:${integrity}`) } class ObjProxy { constructor (obj) { this.obj = obj } get (key) { return this.obj[key] } set (key, val) { this.obj[key] = val } } function pickMem (opts) { if (!opts || !opts.memoize) { return MEMOIZED } else if (opts.memoize.get && opts.memoize.set) { return opts.memoize } else if (typeof opts.memoize === 'object') { return new ObjProxy(opts.memoize) } else { return MEMOIZED } } PK ~\Owcacache/lib/util/tmp.jsnu['use strict' const { withTempDir } = require('@npmcli/fs') const fs = require('fs/promises') const path = require('path') module.exports.mkdir = mktmpdir async function mktmpdir (cache, opts = {}) { const { tmpPrefix } = opts const tmpDir = path.join(cache, 'tmp') await fs.mkdir(tmpDir, { recursive: true, owner: 'inherit' }) // do not use path.join(), it drops the trailing / if tmpPrefix is unset const target = `${tmpDir}${path.sep}${tmpPrefix || ''}` return fs.mkdtemp(target, { owner: 'inherit' }) } module.exports.withTmp = withTmp function withTmp (cache, opts, cb) { if (!cb) { cb = opts opts = {} } return withTempDir(path.join(cache, 'tmp'), cb, opts) } PK ~\_Qcacache/lib/util/glob.jsnu['use strict' const { glob } = require('glob') const path = require('path') const globify = (pattern) => pattern.split(path.win32.sep).join(path.posix.sep) module.exports = (path, options) => glob(globify(path), options) PK ~\4$cacache/lib/util/hash-to-segments.jsnu['use strict' module.exports = hashToSegments function hashToSegments (hash) { return [hash.slice(0, 2), hash.slice(2, 4), hash.slice(4)] } PK ~\'cacache/lib/verify.jsnu['use strict' const { mkdir, readFile, rm, stat, truncate, writeFile, } = require('fs/promises') const pMap = require('p-map') const contentPath = require('./content/path') const fsm = require('fs-minipass') const glob = require('./util/glob.js') const index = require('./entry-index') const path = require('path') const ssri = require('ssri') const hasOwnProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key) const verifyOpts = (opts) => ({ concurrency: 20, log: { silly () {} }, ...opts, }) module.exports = verify async function verify (cache, opts) { opts = verifyOpts(opts) opts.log.silly('verify', 'verifying cache at', cache) const steps = [ markStartTime, fixPerms, garbageCollect, rebuildIndex, cleanTmp, writeVerifile, markEndTime, ] const stats = {} for (const step of steps) { const label = step.name const start = new Date() const s = await step(cache, opts) if (s) { Object.keys(s).forEach((k) => { stats[k] = s[k] }) } const end = new Date() if (!stats.runTime) { stats.runTime = {} } stats.runTime[label] = end - start } stats.runTime.total = stats.endTime - stats.startTime opts.log.silly( 'verify', 'verification finished for', cache, 'in', `${stats.runTime.total}ms` ) return stats } async function markStartTime () { return { startTime: new Date() } } async function markEndTime () { return { endTime: new Date() } } async function fixPerms (cache, opts) { opts.log.silly('verify', 'fixing cache permissions') await mkdir(cache, { recursive: true }) return null } // Implements a naive mark-and-sweep tracing garbage collector. // // The algorithm is basically as follows: // 1. Read (and filter) all index entries ("pointers") // 2. Mark each integrity value as "live" // 3. Read entire filesystem tree in `content-vX/` dir // 4. If content is live, verify its checksum and delete it if it fails // 5. If content is not marked as live, rm it. // async function garbageCollect (cache, opts) { opts.log.silly('verify', 'garbage collecting content') const indexStream = index.lsStream(cache) const liveContent = new Set() indexStream.on('data', (entry) => { if (opts.filter && !opts.filter(entry)) { return } // integrity is stringified, re-parse it so we can get each hash const integrity = ssri.parse(entry.integrity) for (const algo in integrity) { liveContent.add(integrity[algo].toString()) } }) await new Promise((resolve, reject) => { indexStream.on('end', resolve).on('error', reject) }) const contentDir = contentPath.contentDir(cache) const files = await glob(path.join(contentDir, '**'), { follow: false, nodir: true, nosort: true, }) const stats = { verifiedContent: 0, reclaimedCount: 0, reclaimedSize: 0, badContentCount: 0, keptSize: 0, } await pMap( files, async (f) => { const split = f.split(/[/\\]/) const digest = split.slice(split.length - 3).join('') const algo = split[split.length - 4] const integrity = ssri.fromHex(digest, algo) if (liveContent.has(integrity.toString())) { const info = await verifyContent(f, integrity) if (!info.valid) { stats.reclaimedCount++ stats.badContentCount++ stats.reclaimedSize += info.size } else { stats.verifiedContent++ stats.keptSize += info.size } } else { // No entries refer to this content. We can delete. stats.reclaimedCount++ const s = await stat(f) await rm(f, { recursive: true, force: true }) stats.reclaimedSize += s.size } return stats }, { concurrency: opts.concurrency } ) return stats } async function verifyContent (filepath, sri) { const contentInfo = {} try { const { size } = await stat(filepath) contentInfo.size = size contentInfo.valid = true await ssri.checkStream(new fsm.ReadStream(filepath), sri) } catch (err) { if (err.code === 'ENOENT') { return { size: 0, valid: false } } if (err.code !== 'EINTEGRITY') { throw err } await rm(filepath, { recursive: true, force: true }) contentInfo.valid = false } return contentInfo } async function rebuildIndex (cache, opts) { opts.log.silly('verify', 'rebuilding index') const entries = await index.ls(cache) const stats = { missingContent: 0, rejectedEntries: 0, totalEntries: 0, } const buckets = {} for (const k in entries) { /* istanbul ignore else */ if (hasOwnProperty(entries, k)) { const hashed = index.hashKey(k) const entry = entries[k] const excluded = opts.filter && !opts.filter(entry) excluded && stats.rejectedEntries++ if (buckets[hashed] && !excluded) { buckets[hashed].push(entry) } else if (buckets[hashed] && excluded) { // skip } else if (excluded) { buckets[hashed] = [] buckets[hashed]._path = index.bucketPath(cache, k) } else { buckets[hashed] = [entry] buckets[hashed]._path = index.bucketPath(cache, k) } } } await pMap( Object.keys(buckets), (key) => { return rebuildBucket(cache, buckets[key], stats, opts) }, { concurrency: opts.concurrency } ) return stats } async function rebuildBucket (cache, bucket, stats) { await truncate(bucket._path) // This needs to be serialized because cacache explicitly // lets very racy bucket conflicts clobber each other. for (const entry of bucket) { const content = contentPath(cache, entry.integrity) try { await stat(content) await index.insert(cache, entry.key, entry.integrity, { metadata: entry.metadata, size: entry.size, time: entry.time, }) stats.totalEntries++ } catch (err) { if (err.code === 'ENOENT') { stats.rejectedEntries++ stats.missingContent++ } else { throw err } } } } function cleanTmp (cache, opts) { opts.log.silly('verify', 'cleaning tmp directory') return rm(path.join(cache, 'tmp'), { recursive: true, force: true }) } async function writeVerifile (cache, opts) { const verifile = path.join(cache, '_lastverified') opts.log.silly('verify', 'writing verifile to ' + verifile) return writeFile(verifile, `${Date.now()}`) } module.exports.lastRun = lastRun async function lastRun (cache) { const data = await readFile(path.join(cache, '_lastverified'), { encoding: 'utf8' }) return new Date(+data) } PK ~\ gcacache/LICENSE.mdnu[ISC License Copyright (c) npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE COPYRIGHT HOLDER DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\.bin/semver.ps1nu[#!/usr/bin/env pwsh $basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent $exe="" if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { # Fix case when both the Windows and Linux builds of Node # are installed in the same directory $exe=".exe" } $ret=0 if (Test-Path "$basedir/node$exe") { & "$basedir/node$exe" "$basedir/../semver/bin/semver.js" $args $ret=$LASTEXITCODE } else { & "node$exe" "$basedir/../semver/bin/semver.js" $args $ret=$LASTEXITCODE } exit $ret PK ~\ԃ.bin/semver.cmdnu[@ECHO off SETLOCAL CALL :find_dp0 IF EXIST "%dp0%\node.exe" ( SET "_prog=%dp0%\node.exe" ) ELSE ( SET "_prog=node" SET PATHEXT=%PATHEXT:;.JS;=;% ) "%_prog%" "%dp0%\..\semver\bin\semver.js" %* ENDLOCAL EXIT /b %errorlevel% :find_dp0 SET dp0=%~dp0 EXIT /b PK ~\F..bin/node-gyp.ps1nu[#!/usr/bin/env pwsh $basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent $exe="" if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { # Fix case when both the Windows and Linux builds of Node # are installed in the same directory $exe=".exe" } $ret=0 if (Test-Path "$basedir/node$exe") { & "$basedir/node$exe" "$basedir/../node-gyp/bin/node-gyp.js" $args $ret=$LASTEXITCODE } else { & "node$exe" "$basedir/../node-gyp/bin/node-gyp.js" $args $ret=$LASTEXITCODE } exit $ret PK ~\@@ .bin/mkdirpnu[#!/bin/sh basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") case `uname` in *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; esac if [ -x "$basedir/node" ]; then "$basedir/node" "$basedir/../mkdirp/bin/cmd.js" "$@" ret=$? else node "$basedir/../mkdirp/bin/cmd.js" "$@" ret=$? fi exit $ret PK ~\'.bin/node-gyp.cmdnu[@ECHO off SETLOCAL CALL :find_dp0 IF EXIST "%dp0%\node.exe" ( SET "_prog=%dp0%\node.exe" ) ELSE ( SET "_prog=node" SET PATHEXT=%PATHEXT:;.JS;=;% ) "%_prog%" "%dp0%\..\node-gyp\bin\node-gyp.js" %* ENDLOCAL EXIT /b %errorlevel% :find_dp0 SET dp0=%~dp0 EXIT /b PK ~\c.bin/qrcode-terminal.ps1nu[#!/usr/bin/env pwsh $basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent $exe="" if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { # Fix case when both the Windows and Linux builds of Node # are installed in the same directory $exe=".exe" } $ret=0 if (Test-Path "$basedir/node$exe") { & "$basedir/node$exe" "$basedir/../qrcode-terminal/bin/qrcode-terminal.js" $args $ret=$LASTEXITCODE } else { & "node$exe" "$basedir/../qrcode-terminal/bin/qrcode-terminal.js" $args $ret=$LASTEXITCODE } exit $ret PK ~\Sf .bin/glob.cmdnu[@ECHO off SETLOCAL CALL :find_dp0 IF EXIST "%dp0%\node.exe" ( SET "_prog=%dp0%\node.exe" ) ELSE ( SET "_prog=node" SET PATHEXT=%PATHEXT:;.JS;=;% ) "%_prog%" "%dp0%\..\glob\dist\esm\bin.mjs" %* ENDLOCAL EXIT /b %errorlevel% :find_dp0 SET dp0=%~dp0 EXIT /b PK ~\ S7.bin/cssesc.cmdnu[@ECHO off SETLOCAL CALL :find_dp0 IF EXIST "%dp0%\node.exe" ( SET "_prog=%dp0%\node.exe" ) ELSE ( SET "_prog=node" SET PATHEXT=%PATHEXT:;.JS;=;% ) "%_prog%" "%dp0%\..\cssesc\bin\cssesc" %* ENDLOCAL EXIT /b %errorlevel% :find_dp0 SET dp0=%~dp0 EXIT /b PK ~\,.bin/pacote.cmdnu[@ECHO off SETLOCAL CALL :find_dp0 IF EXIST "%dp0%\node.exe" ( SET "_prog=%dp0%\node.exe" ) ELSE ( SET "_prog=node" SET PATHEXT=%PATHEXT:;.JS;=;% ) "%_prog%" "%dp0%\..\pacote\bin\index.js" %* ENDLOCAL EXIT /b %errorlevel% :find_dp0 SET dp0=%~dp0 EXIT /b PK ~\ҴEU.bin/arborist.ps1nu[#!/usr/bin/env pwsh $basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent $exe="" if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { # Fix case when both the Windows and Linux builds of Node # are installed in the same directory $exe=".exe" } $ret=0 if (Test-Path "$basedir/node$exe") { & "$basedir/node$exe" "$basedir/../@npmcli/arborist/bin/index.js" $args $ret=$LASTEXITCODE } else { & "node$exe" "$basedir/../@npmcli/arborist/bin/index.js" $args $ret=$LASTEXITCODE } exit $ret PK ~\&XX .bin/arboristnu[#!/bin/sh basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") case `uname` in *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; esac if [ -x "$basedir/node" ]; then "$basedir/node" "$basedir/../@npmcli/arborist/bin/index.js" "$@" ret=$? else node "$basedir/../@npmcli/arborist/bin/index.js" "$@" ret=$? fi exit $ret PK ~\x.bin/node-which.ps1nu[#!/usr/bin/env pwsh $basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent $exe="" if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { # Fix case when both the Windows and Linux builds of Node # are installed in the same directory $exe=".exe" } $ret=0 if (Test-Path "$basedir/node$exe") { & "$basedir/node$exe" "$basedir/../which/bin/which.js" $args $ret=$LASTEXITCODE } else { & "node$exe" "$basedir/../which/bin/which.js" $args $ret=$LASTEXITCODE } exit $ret PK ~\-\.bin/cssesc.ps1nu[#!/usr/bin/env pwsh $basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent $exe="" if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { # Fix case when both the Windows and Linux builds of Node # are installed in the same directory $exe=".exe" } $ret=0 if (Test-Path "$basedir/node$exe") { & "$basedir/node$exe" "$basedir/../cssesc/bin/cssesc" $args $ret=$LASTEXITCODE } else { & "node$exe" "$basedir/../cssesc/bin/cssesc" $args $ret=$LASTEXITCODE } exit $ret PK ~\fx**.bin/qrcode-terminal.cmdnu[@ECHO off SETLOCAL CALL :find_dp0 IF EXIST "%dp0%\node.exe" ( SET "_prog=%dp0%\node.exe" ) ELSE ( SET "_prog=node" SET PATHEXT=%PATHEXT:;.JS;=;% ) "%_prog%" "%dp0%\..\qrcode-terminal\bin\qrcode-terminal.js" %* ENDLOCAL EXIT /b %errorlevel% :find_dp0 SET dp0=%~dp0 EXIT /b PK ~\i!!.bin/arborist.cmdnu[@ECHO off SETLOCAL CALL :find_dp0 IF EXIST "%dp0%\node.exe" ( SET "_prog=%dp0%\node.exe" ) ELSE ( SET "_prog=node" SET PATHEXT=%PATHEXT:;.JS;=;% ) "%_prog%" "%dp0%\..\@npmcli\arborist\bin\index.js" %* ENDLOCAL EXIT /b %errorlevel% :find_dp0 SET dp0=%~dp0 EXIT /b PK ~\nHH .bin/globnu[#!/bin/sh basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") case `uname` in *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; esac if [ -x "$basedir/node" ]; then "$basedir/node" "$basedir/../glob/dist/esm/bin.mjs" "$@" ret=$? else node "$basedir/../glob/dist/esm/bin.mjs" "$@" ret=$? fi exit $ret PK ~\ր.bin/node-which.cmdnu[@ECHO off SETLOCAL CALL :find_dp0 IF EXIST "%dp0%\node.exe" ( SET "_prog=%dp0%\node.exe" ) ELSE ( SET "_prog=node" SET PATHEXT=%PATHEXT:;.JS;=;% ) "%_prog%" "%dp0%\..\which\bin\which.js" %* ENDLOCAL EXIT /b %errorlevel% :find_dp0 SET dp0=%~dp0 EXIT /b PK ~\ܥDD .bin/pacotenu[#!/bin/sh basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") case `uname` in *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; esac if [ -x "$basedir/node" ]; then "$basedir/node" "$basedir/../pacote/bin/index.js" "$@" ret=$? else node "$basedir/../pacote/bin/index.js" "$@" ret=$? fi exit $ret PK ~\qFF .bin/semvernu[#!/bin/sh basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") case `uname` in *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; esac if [ -x "$basedir/node" ]; then "$basedir/node" "$basedir/../semver/bin/semver.js" "$@" ret=$? else node "$basedir/../semver/bin/semver.js" "$@" ret=$? fi exit $ret PK ~\fBB.bin/node-whichnu[#!/bin/sh basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") case `uname` in *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; esac if [ -x "$basedir/node" ]; then "$basedir/node" "$basedir/../which/bin/which.js" "$@" ret=$? else node "$basedir/../which/bin/which.js" "$@" ret=$? fi exit $ret PK ~\||.bin/installed-package-contentsnu[#!/bin/sh basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") case `uname` in *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; esac if [ -x "$basedir/node" ]; then "$basedir/node" "$basedir/../@npmcli/installed-package-contents/bin/index.js" "$@" ret=$? else node "$basedir/../@npmcli/installed-package-contents/bin/index.js" "$@" ret=$? fi exit $ret PK ~\Y#NN .bin/node-gypnu[#!/bin/sh basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") case `uname` in *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; esac if [ -x "$basedir/node" ]; then "$basedir/node" "$basedir/../node-gyp/bin/node-gyp.js" "$@" ret=$? else node "$basedir/../node-gyp/bin/node-gyp.js" "$@" ret=$? fi exit $ret PK ~\;wv>> .bin/noptnu[#!/bin/sh basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") case `uname` in *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; esac if [ -x "$basedir/node" ]; then "$basedir/node" "$basedir/../nopt/bin/nopt.js" "$@" ret=$? else node "$basedir/../nopt/bin/nopt.js" "$@" ret=$? fi exit $ret PK ~\ ߓ' .bin/nopt.cmdnu[@ECHO off SETLOCAL CALL :find_dp0 IF EXIST "%dp0%\node.exe" ( SET "_prog=%dp0%\node.exe" ) ELSE ( SET "_prog=node" SET PATHEXT=%PATHEXT:;.JS;=;% ) "%_prog%" "%dp0%\..\nopt\bin\nopt.js" %* ENDLOCAL EXIT /b %errorlevel% :find_dp0 SET dp0=%~dp0 EXIT /b PK ~\!0E33#.bin/installed-package-contents.cmdnu[@ECHO off SETLOCAL CALL :find_dp0 IF EXIST "%dp0%\node.exe" ( SET "_prog=%dp0%\node.exe" ) ELSE ( SET "_prog=node" SET PATHEXT=%PATHEXT:;.JS;=;% ) "%_prog%" "%dp0%\..\@npmcli\installed-package-contents\bin\index.js" %* ENDLOCAL EXIT /b %errorlevel% :find_dp0 SET dp0=%~dp0 EXIT /b PK ~\ .bin/glob.ps1nu[#!/usr/bin/env pwsh $basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent $exe="" if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { # Fix case when both the Windows and Linux builds of Node # are installed in the same directory $exe=".exe" } $ret=0 if (Test-Path "$basedir/node$exe") { & "$basedir/node$exe" "$basedir/../glob/dist/esm/bin.mjs" $args $ret=$LASTEXITCODE } else { & "node$exe" "$basedir/../glob/dist/esm/bin.mjs" $args $ret=$LASTEXITCODE } exit $ret PK ~\p8.bin/mkdirp.cmdnu[@ECHO off SETLOCAL CALL :find_dp0 IF EXIST "%dp0%\node.exe" ( SET "_prog=%dp0%\node.exe" ) ELSE ( SET "_prog=node" SET PATHEXT=%PATHEXT:;.JS;=;% ) "%_prog%" "%dp0%\..\mkdirp\bin\cmd.js" %* ENDLOCAL EXIT /b %errorlevel% :find_dp0 SET dp0=%~dp0 EXIT /b PK ~\ف .bin/mkdirp.ps1nu[#!/usr/bin/env pwsh $basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent $exe="" if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { # Fix case when both the Windows and Linux builds of Node # are installed in the same directory $exe=".exe" } $ret=0 if (Test-Path "$basedir/node$exe") { & "$basedir/node$exe" "$basedir/../mkdirp/bin/cmd.js" $args $ret=$LASTEXITCODE } else { & "node$exe" "$basedir/../mkdirp/bin/cmd.js" $args $ret=$LASTEXITCODE } exit $ret PK ~\FYA .bin/nopt.ps1nu[#!/usr/bin/env pwsh $basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent $exe="" if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { # Fix case when both the Windows and Linux builds of Node # are installed in the same directory $exe=".exe" } $ret=0 if (Test-Path "$basedir/node$exe") { & "$basedir/node$exe" "$basedir/../nopt/bin/nopt.js" $args $ret=$LASTEXITCODE } else { & "node$exe" "$basedir/../nopt/bin/nopt.js" $args $ret=$LASTEXITCODE } exit $ret PK ~\;]@@ .bin/cssescnu[#!/bin/sh basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") case `uname` in *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; esac if [ -x "$basedir/node" ]; then "$basedir/node" "$basedir/../cssesc/bin/cssesc" "$@" ret=$? else node "$basedir/../cssesc/bin/cssesc" "$@" ret=$? fi exit $ret PK ~\ڪ>jj.bin/qrcode-terminalnu[#!/bin/sh basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") case `uname` in *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; esac if [ -x "$basedir/node" ]; then "$basedir/node" "$basedir/../qrcode-terminal/bin/qrcode-terminal.js" "$@" ret=$? else node "$basedir/../qrcode-terminal/bin/qrcode-terminal.js" "$@" ret=$? fi exit $ret PK ~\rKY.bin/pacote.ps1nu[#!/usr/bin/env pwsh $basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent $exe="" if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { # Fix case when both the Windows and Linux builds of Node # are installed in the same directory $exe=".exe" } $ret=0 if (Test-Path "$basedir/node$exe") { & "$basedir/node$exe" "$basedir/../pacote/bin/index.js" $args $ret=$LASTEXITCODE } else { & "node$exe" "$basedir/../pacote/bin/index.js" $args $ret=$LASTEXITCODE } exit $ret PK ~\&&#.bin/installed-package-contents.ps1nu[#!/usr/bin/env pwsh $basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent $exe="" if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { # Fix case when both the Windows and Linux builds of Node # are installed in the same directory $exe=".exe" } $ret=0 if (Test-Path "$basedir/node$exe") { & "$basedir/node$exe" "$basedir/../@npmcli/installed-package-contents/bin/index.js" $args $ret=$LASTEXITCODE } else { & "node$exe" "$basedir/../@npmcli/installed-package-contents/bin/index.js" $args $ret=$LASTEXITCODE } exit $ret PK ~\v{**libnpmaccess/package.jsonnu[{ "_id": "libnpmaccess@8.0.6", "_inBundle": true, "_location": "/npm/libnpmaccess", "_phantomChildren": {}, "_requiredBy": [ "/npm" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/libnpmaccess/issues" }, "dependencies": { "npm-package-arg": "^11.0.2", "npm-registry-fetch": "^17.0.1" }, "description": "programmatic library for `npm access` commands", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/mock-registry": "^1.0.0", "@npmcli/template-oss": "4.22.0", "nock": "^13.3.3", "tap": "^16.3.8" }, "engines": { "node": "^16.14.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://npmjs.com/package/libnpmaccess", "license": "ISC", "main": "lib/index.js", "name": "libnpmaccess", "repository": { "type": "git", "url": "git+https://github.com/npm/cli.git", "directory": "workspaces/libnpmaccess" }, "scripts": { "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.22.0", "content": "../../scripts/template-oss/index.js" }, "version": "8.0.6" } PK ~\bV8p p libnpmaccess/lib/index.jsnu['use strict' const npa = require('npm-package-arg') const npmFetch = require('npm-registry-fetch') const npar = (spec) => { spec = npa(spec) if (!spec.registry) { throw new Error('must use package name only') } return spec } const parseTeam = (scopeTeam) => { let slice = 0 if (scopeTeam.startsWith('@')) { slice = 1 } const [scope, team] = scopeTeam.slice(slice).split(':').map(encodeURIComponent) return { scope, team } } const getPackages = async (scopeTeam, opts) => { const { scope, team } = parseTeam(scopeTeam) let uri if (team) { uri = `/-/team/${scope}/${team}/package` } else { uri = `/-/org/${scope}/package` } try { return await npmFetch.json(uri, opts) } catch (err) { if (err.code === 'E404') { uri = `/-/user/${scope}/package` return npmFetch.json(uri, opts) } throw err } } const getCollaborators = async (pkg, opts) => { const spec = npar(pkg) const uri = `/-/package/${spec.escapedName}/collaborators` return npmFetch.json(uri, opts) } const getVisibility = async (pkg, opts) => { const spec = npar(pkg) const uri = `/-/package/${spec.escapedName}/visibility` return npmFetch.json(uri, opts) } const setAccess = async (pkg, access, opts) => { const spec = npar(pkg) const uri = `/-/package/${spec.escapedName}/access` await npmFetch(uri, { ...opts, method: 'POST', body: { access }, spec, ignoreBody: true, }) return true } const setMfa = async (pkg, level, opts) => { const spec = npar(pkg) const body = {} switch (level) { case 'none': body.publish_requires_tfa = false break case 'publish': // tfa is required, automation tokens can not override tfa body.publish_requires_tfa = true body.automation_token_overrides_tfa = false break case 'automation': // tfa is required, automation tokens can override tfa body.publish_requires_tfa = true body.automation_token_overrides_tfa = true break default: throw new Error(`Invalid mfa setting ${level}`) } const uri = `/-/package/${spec.escapedName}/access` await npmFetch(uri, { ...opts, method: 'POST', body, spec, ignoreBody: true, }) return true } const setPermissions = async (scopeTeam, pkg, permissions, opts) => { const spec = npar(pkg) const { scope, team } = parseTeam(scopeTeam) if (!scope || !team) { throw new Error('team must be in format `scope:team`') } const uri = `/-/team/${scope}/${team}/package` await npmFetch(uri, { ...opts, method: 'PUT', body: { package: spec.name, permissions }, scope, spec, ignoreBody: true, }) return true } const removePermissions = async (scopeTeam, pkg, opts) => { const spec = npar(pkg) const { scope, team } = parseTeam(scopeTeam) const uri = `/-/team/${scope}/${team}/package` await npmFetch(uri, { ...opts, method: 'DELETE', body: { package: spec.name }, scope, spec, ignoreBody: true, }) return true } module.exports = { getCollaborators, getPackages, getVisibility, removePermissions, setAccess, setMfa, setPermissions, } PK ~\gXlibnpmaccess/LICENSEnu[Copyright npm, Inc Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\4w w libnpmaccess/README.mdnu[# libnpmaccess [![npm version](https://img.shields.io/npm/v/libnpmaccess.svg)](https://npm.im/libnpmaccess) [![license](https://img.shields.io/npm/l/libnpmaccess.svg)](https://npm.im/libnpmaccess) [![CI - libnpmaccess](https://github.com/npm/cli/actions/workflows/ci-libnpmaccess.yml/badge.svg)](https://github.com/npm/cli/actions/workflows/ci-libnpmaccess.yml) [`libnpmaccess`](https://github.com/npm/libnpmaccess) is a Node.js library that provides programmatic access to the guts of the npm CLI's `npm access` command. This includes managing account mfa settings, listing packages and permissions, looking at package collaborators, and defining package permissions for users, orgs, and teams. ## Example ```javascript const access = require('libnpmaccess') const opts = { '//registry.npmjs.org/:_authToken: 'npm_token } // List all packages @zkat has access to on the npm registry. console.log(Object.keys(await access.getPackages('zkat', opts))) ``` ### API #### `opts` for all `libnpmaccess` commands `libnpmaccess` uses [`npm-registry-fetch`](https://npm.im/npm-registry-fetch). All options are passed through directly to that library, so please refer to [its own `opts` documentation](https://www.npmjs.com/package/npm-registry-fetch#fetch-options) for options that can be passed in. #### `spec` parameter for all `libnpmaccess` commands `spec` must be an [`npm-package-arg`](https://npm.im/npm-package-arg)-compatible registry spec. #### `access.getCollaborators(spec, opts) -> Promise` Gets collaborators for a given package #### `access.getPackages(user|scope|team, opts) -> Promise` Gets all packages for a given user, scope, or team. Teams should be in the format `scope:team` or `@scope:team` Users and scopes can be in the format `@scope` or `scope` #### `access.getVisibility(spec, opts) -> Promise` Gets the visibility of a given package #### `access.removePermissions(team, spec, opts) -> Promise` Removes the access for a given team to a package. Teams should be in the format `scope:team` or `@scope:team` #### `access.setAccess(package, access, opts) -> Promise` Sets access level for package described by `spec`. The npm registry accepts the following `access` levels: `public`: package is public `private`: package is private The npm registry also only allows scoped packages to have their access level set. #### access.setMfa(spec, level, opts) -> Promise` Sets the publishing mfa requirements for a given package. Level must be one of the following `none`: mfa is not required to publish this package. `publish`: mfa is required to publish this package, automation tokens cannot be used to publish. `automation`: mfa is required to publish this package, automation tokens may also be used for publishing from continuous integration workflows. #### access.setPermissions(team, spec, permssions, opts) -> Promise` Sets permissions levels for a given team to a package. Teams should be in the format `scope:team` or `@scope:team` The npm registry accepts the following `permissions`: `read-only`: Read only permissions `read-write`: Read and write (aka publish) permissions PK ~\*cross-spawn/package.jsonnu[{ "_id": "cross-spawn@7.0.3", "_inBundle": true, "_location": "/npm/cross-spawn", "_phantomChildren": { "isexe": "2.0.0" }, "_requiredBy": [ "/npm/foreground-child" ], "author": { "name": "André Cruz", "email": "andre@moxy.studio" }, "bugs": { "url": "https://github.com/moxystudio/node-cross-spawn/issues" }, "commitlint": { "extends": [ "@commitlint/config-conventional" ] }, "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" }, "description": "Cross platform child_process#spawn and child_process#spawnSync", "devDependencies": { "@commitlint/cli": "^8.1.0", "@commitlint/config-conventional": "^8.1.0", "babel-core": "^6.26.3", "babel-jest": "^24.9.0", "babel-preset-moxy": "^3.1.0", "eslint": "^5.16.0", "eslint-config-moxy": "^7.1.0", "husky": "^3.0.5", "jest": "^24.9.0", "lint-staged": "^9.2.5", "mkdirp": "^0.5.1", "rimraf": "^3.0.0", "standard-version": "^7.0.0" }, "engines": { "node": ">= 8" }, "files": [ "lib" ], "homepage": "https://github.com/moxystudio/node-cross-spawn", "husky": { "hooks": { "commit-msg": "commitlint -E HUSKY_GIT_PARAMS", "pre-commit": "lint-staged" } }, "keywords": [ "spawn", "spawnSync", "windows", "cross-platform", "path-ext", "shebang", "cmd", "execute" ], "license": "MIT", "lint-staged": { "*.js": [ "eslint --fix", "git add" ] }, "main": "index.js", "name": "cross-spawn", "repository": { "type": "git", "url": "git+ssh://git@github.com/moxystudio/node-cross-spawn.git" }, "scripts": { "lint": "eslint .", "postrelease": "git push --follow-tags origin HEAD && npm publish", "prerelease": "npm t && npm run lint", "release": "standard-version", "test": "jest --env node --coverage" }, "version": "7.0.3" } PK ~\,cross-spawn/node_modules/.bin/node-which.ps1nu[#!/usr/bin/env pwsh $basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent $exe="" if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { # Fix case when both the Windows and Linux builds of Node # are installed in the same directory $exe=".exe" } $ret=0 if (Test-Path "$basedir/node$exe") { & "$basedir/node$exe" "$basedir/../which/bin/node-which" $args $ret=$LASTEXITCODE } else { & "node$exe" "$basedir/../which/bin/node-which" $args $ret=$LASTEXITCODE } exit $ret PK ~\h,cross-spawn/node_modules/.bin/node-which.cmdnu[@ECHO off SETLOCAL CALL :find_dp0 IF EXIST "%dp0%\node.exe" ( SET "_prog=%dp0%\node.exe" ) ELSE ( SET "_prog=node" SET PATHEXT=%PATHEXT:;.JS;=;% ) "%_prog%" "%dp0%\..\which\bin\node-which" %* ENDLOCAL EXIT /b %errorlevel% :find_dp0 SET dp0=%~dp0 EXIT /b PK ~\FF(cross-spawn/node_modules/.bin/node-whichnu[#!/bin/sh basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") case `uname` in *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; esac if [ -x "$basedir/node" ]; then "$basedir/node" "$basedir/../which/bin/node-which" "$@" ret=$? else node "$basedir/../which/bin/node-which" "$@" ret=$? fi exit $ret PK ~\[cc+cross-spawn/node_modules/which/package.jsonnu[{ "_id": "which@2.0.2", "_inBundle": true, "_location": "/npm/cross-spawn/which", "_phantomChildren": {}, "_requiredBy": [ "/npm/cross-spawn" ], "author": { "name": "Isaac Z. Schlueter", "email": "i@izs.me", "url": "http://blog.izs.me" }, "bin": { "node-which": "bin/node-which" }, "bugs": { "url": "https://github.com/isaacs/node-which/issues" }, "dependencies": { "isexe": "^2.0.0" }, "description": "Like which(1) unix command. Find the first instance of an executable in the PATH.", "devDependencies": { "mkdirp": "^0.5.0", "rimraf": "^2.6.2", "tap": "^14.6.9" }, "engines": { "node": ">= 8" }, "files": [ "which.js", "bin/node-which" ], "homepage": "https://github.com/isaacs/node-which#readme", "license": "ISC", "main": "which.js", "name": "which", "repository": { "type": "git", "url": "git://github.com/isaacs/node-which.git" }, "scripts": { "changelog": "git add CHANGELOG.md", "postchangelog": "git commit -m 'update changelog - '${npm_package_version}", "postpublish": "git push origin --follow-tags", "postversion": "npm publish", "prechangelog": "bash gen-changelog.sh", "prepublish": "npm run changelog", "preversion": "npm test", "test": "tap" }, "tap": { "check-coverage": true }, "version": "2.0.2" } PK ~\aGW&cross-spawn/node_modules/which/LICENSEnu[The ISC License Copyright (c) Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\Fڧ-cross-spawn/node_modules/which/bin/node-whichnu[#!/usr/bin/env node var which = require("../") if (process.argv.length < 3) usage() function usage () { console.error('usage: which [-as] program ...') process.exit(1) } var all = false var silent = false var dashdash = false var args = process.argv.slice(2).filter(function (arg) { if (dashdash || !/^-/.test(arg)) return true if (arg === '--') { dashdash = true return false } var flags = arg.substr(1).split('') for (var f = 0; f < flags.length; f++) { var flag = flags[f] switch (flag) { case 's': silent = true break case 'a': all = true break default: console.error('which: illegal option -- ' + flag) usage() } } return false }) process.exit(args.reduce(function (pv, current) { try { var f = which.sync(current, { all: all }) if (all) f = f.join('\n') if (!silent) console.log(f) return pv; } catch (e) { return 1; } }, 0)) PK ~\r-[ [ 'cross-spawn/node_modules/which/which.jsnu[const isWindows = process.platform === 'win32' || process.env.OSTYPE === 'cygwin' || process.env.OSTYPE === 'msys' const path = require('path') const COLON = isWindows ? ';' : ':' const isexe = require('isexe') const getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' }) const getPathInfo = (cmd, opt) => { const colon = opt.colon || COLON // If it has a slash, then we don't bother searching the pathenv. // just check the file itself, and that's it. const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [''] : ( [ // windows always checks the cwd first ...(isWindows ? [process.cwd()] : []), ...(opt.path || process.env.PATH || /* istanbul ignore next: very unusual */ '').split(colon), ] ) const pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM' : '' const pathExt = isWindows ? pathExtExe.split(colon) : [''] if (isWindows) { if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') pathExt.unshift('') } return { pathEnv, pathExt, pathExtExe, } } const which = (cmd, opt, cb) => { if (typeof opt === 'function') { cb = opt opt = {} } if (!opt) opt = {} const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) const found = [] const step = i => new Promise((resolve, reject) => { if (i === pathEnv.length) return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd)) const ppRaw = pathEnv[i] const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw const pCmd = path.join(pathPart, cmd) const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd resolve(subStep(p, i, 0)) }) const subStep = (p, i, ii) => new Promise((resolve, reject) => { if (ii === pathExt.length) return resolve(step(i + 1)) const ext = pathExt[ii] isexe(p + ext, { pathExt: pathExtExe }, (er, is) => { if (!er && is) { if (opt.all) found.push(p + ext) else return resolve(p + ext) } return resolve(subStep(p, i, ii + 1)) }) }) return cb ? step(0).then(res => cb(null, res), cb) : step(0) } const whichSync = (cmd, opt) => { opt = opt || {} const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt) const found = [] for (let i = 0; i < pathEnv.length; i ++) { const ppRaw = pathEnv[i] const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw const pCmd = path.join(pathPart, cmd) const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd for (let j = 0; j < pathExt.length; j ++) { const cur = p + pathExt[j] try { const is = isexe.sync(cur, { pathExt: pathExtExe }) if (is) { if (opt.all) found.push(cur) else return cur } } catch (ex) {} } } if (opt.all && found.length) return found if (opt.nothrow) return null throw getNotFoundError(cmd) } module.exports = which which.sync = whichSync PK ~\撱UHH(cross-spawn/node_modules/which/README.mdnu[# which Like the unix `which` utility. Finds the first instance of a specified executable in the PATH environment variable. Does not cache the results, so `hash -r` is not needed when the PATH changes. ## USAGE ```javascript var which = require('which') // async usage which('node', function (er, resolvedPath) { // er is returned if no "node" is found on the PATH // if it is found, then the absolute path to the exec is returned }) // or promise which('node').then(resolvedPath => { ... }).catch(er => { ... not found ... }) // sync usage // throws if not found var resolved = which.sync('node') // if nothrow option is used, returns null if not found resolved = which.sync('node', {nothrow: true}) // Pass options to override the PATH and PATHEXT environment vars. which('node', { path: someOtherPath }, function (er, resolved) { if (er) throw er console.log('found at %j', resolved) }) ``` ## CLI USAGE Same as the BSD `which(1)` binary. ``` usage: which [-as] program ... ``` ## OPTIONS You may pass an options object as the second argument. - `path`: Use instead of the `PATH` environment variable. - `pathExt`: Use instead of the `PATHEXT` environment variable. - `all`: Return all matches, instead of just the first one. Note that this means the function returns an array of strings instead of a single string. PK ~\; cross-spawn/lib/parse.jsnu['use strict'; const path = require('path'); const resolveCommand = require('./util/resolveCommand'); const escape = require('./util/escape'); const readShebang = require('./util/readShebang'); const isWin = process.platform === 'win32'; const isExecutableRegExp = /\.(?:com|exe)$/i; const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; function detectShebang(parsed) { parsed.file = resolveCommand(parsed); const shebang = parsed.file && readShebang(parsed.file); if (shebang) { parsed.args.unshift(parsed.file); parsed.command = shebang; return resolveCommand(parsed); } return parsed.file; } function parseNonShell(parsed) { if (!isWin) { return parsed; } // Detect & add support for shebangs const commandFile = detectShebang(parsed); // We don't need a shell if the command filename is an executable const needsShell = !isExecutableRegExp.test(commandFile); // If a shell is required, use cmd.exe and take care of escaping everything correctly // Note that `forceShell` is an hidden option used only in tests if (parsed.options.forceShell || needsShell) { // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/` // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called, // we need to double escape them const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile); // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar) // This is necessary otherwise it will always fail with ENOENT in those cases parsed.command = path.normalize(parsed.command); // Escape command & arguments parsed.command = escape.command(parsed.command); parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars)); const shellCommand = [parsed.command].concat(parsed.args).join(' '); parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; parsed.command = process.env.comspec || 'cmd.exe'; parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped } return parsed; } function parse(command, args, options) { // Normalize arguments, similar to nodejs if (args && !Array.isArray(args)) { options = args; args = null; } args = args ? args.slice(0) : []; // Clone array to avoid changing the original options = Object.assign({}, options); // Clone object to avoid changing the original // Build our parsed object const parsed = { command, args, options, file: undefined, original: { command, args, }, }; // Delegate further parsing to shell or non-shell return options.shell ? parsed : parseNonShell(parsed); } module.exports = parse; PK ~\ͨcross-spawn/lib/enoent.jsnu['use strict'; const isWin = process.platform === 'win32'; function notFoundError(original, syscall) { return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), { code: 'ENOENT', errno: 'ENOENT', syscall: `${syscall} ${original.command}`, path: original.command, spawnargs: original.args, }); } function hookChildProcess(cp, parsed) { if (!isWin) { return; } const originalEmit = cp.emit; cp.emit = function (name, arg1) { // If emitting "exit" event and exit code is 1, we need to check if // the command exists and emit an "error" instead // See https://github.com/IndigoUnited/node-cross-spawn/issues/16 if (name === 'exit') { const err = verifyENOENT(arg1, parsed, 'spawn'); if (err) { return originalEmit.call(cp, 'error', err); } } return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params }; } function verifyENOENT(status, parsed) { if (isWin && status === 1 && !parsed.file) { return notFoundError(parsed.original, 'spawn'); } return null; } function verifyENOENTSync(status, parsed) { if (isWin && status === 1 && !parsed.file) { return notFoundError(parsed.original, 'spawnSync'); } return null; } module.exports = { hookChildProcess, verifyENOENT, verifyENOENTSync, notFoundError, }; PK ~\+cross-spawn/lib/util/escape.jsnu['use strict'; // See http://www.robvanderwoude.com/escapechars.php const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; function escapeCommand(arg) { // Escape meta chars arg = arg.replace(metaCharsRegExp, '^$1'); return arg; } function escapeArgument(arg, doubleEscapeMetaChars) { // Convert to string arg = `${arg}`; // Algorithm below is based on https://qntm.org/cmd // Sequence of backslashes followed by a double quote: // double up all the backslashes and escape the double quote arg = arg.replace(/(\\*)"/g, '$1$1\\"'); // Sequence of backslashes followed by the end of the string // (which will become a double quote later): // double up all the backslashes arg = arg.replace(/(\\*)$/, '$1$1'); // All other backslashes occur literally // Quote the whole thing: arg = `"${arg}"`; // Escape meta chars arg = arg.replace(metaCharsRegExp, '^$1'); // Double escape meta chars if necessary if (doubleEscapeMetaChars) { arg = arg.replace(metaCharsRegExp, '^$1'); } return arg; } module.exports.command = escapeCommand; module.exports.argument = escapeArgument; PK ~\(9&cross-spawn/lib/util/resolveCommand.jsnu['use strict'; const path = require('path'); const which = require('which'); const getPathKey = require('path-key'); function resolveCommandAttempt(parsed, withoutPathExt) { const env = parsed.options.env || process.env; const cwd = process.cwd(); const hasCustomCwd = parsed.options.cwd != null; // Worker threads do not have process.chdir() const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled; // If a custom `cwd` was specified, we need to change the process cwd // because `which` will do stat calls but does not support a custom cwd if (shouldSwitchCwd) { try { process.chdir(parsed.options.cwd); } catch (err) { /* Empty */ } } let resolved; try { resolved = which.sync(parsed.command, { path: env[getPathKey({ env })], pathExt: withoutPathExt ? path.delimiter : undefined, }); } catch (e) { /* Empty */ } finally { if (shouldSwitchCwd) { process.chdir(cwd); } } // If we successfully resolved, ensure that an absolute path is returned // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it if (resolved) { resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved); } return resolved; } function resolveCommand(parsed) { return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); } module.exports = resolveCommand; PK ~\>%%#cross-spawn/lib/util/readShebang.jsnu['use strict'; const fs = require('fs'); const shebangCommand = require('shebang-command'); function readShebang(command) { // Read the first 150 bytes from the file const size = 150; const buffer = Buffer.alloc(size); let fd; try { fd = fs.openSync(command, 'r'); fs.readSync(fd, buffer, 0, size, 0); fs.closeSync(fd); } catch (e) { /* Empty */ } // Attempt to extract shebang (null is returned if not a shebang) return shebangCommand(buffer.toString()); } module.exports = readShebang; PK ~\}QQcross-spawn/LICENSEnu[The MIT License (MIT) Copyright (c) 2018 Made With MOXY Lda Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\&<cross-spawn/index.jsnu['use strict'; const cp = require('child_process'); const parse = require('./lib/parse'); const enoent = require('./lib/enoent'); function spawn(command, args, options) { // Parse the arguments const parsed = parse(command, args, options); // Spawn the child process const spawned = cp.spawn(parsed.command, parsed.args, parsed.options); // Hook into child process "exit" event to emit an error if the command // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 enoent.hookChildProcess(spawned, parsed); return spawned; } function spawnSync(command, args, options) { // Parse the arguments const parsed = parse(command, args, options); // Spawn the child process const result = cp.spawnSync(parsed.command, parsed.args, parsed.options); // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 result.error = result.error || enoent.verifyENOENTSync(result.status, parsed); return result; } module.exports = spawn; module.exports.spawn = spawn; module.exports.sync = spawnSync; module.exports._parse = parse; module.exports._enoent = enoent; PK ~\~m!minipass-json-stream/package.jsonnu[{ "_id": "minipass-json-stream@1.0.1", "_inBundle": true, "_location": "/npm/minipass-json-stream", "_phantomChildren": { "yallist": "4.0.0" }, "_requiredBy": [ "/npm/npm-registry-fetch" ], "author": { "name": "Isaac Z. Schlueter", "email": "i@izs.me", "url": "https://izs.me" }, "bugs": { "url": "https://github.com/npm/minipass-json-stream/issues" }, "dependencies": { "jsonparse": "^1.3.1", "minipass": "^3.0.0" }, "description": "Like JSONStream, but using Minipass streams", "devDependencies": { "JSONStream": "^1.3.5", "tap": "^14.6.9" }, "files": [ "index.js" ], "homepage": "https://github.com/npm/minipass-json-stream#readme", "keywords": [ "stream", "json", "parse", "minipass", "JSONStream" ], "license": "MIT", "name": "minipass-json-stream", "repository": { "type": "git", "url": "git+https://github.com/npm/minipass-json-stream.git" }, "scripts": { "postpublish": "git push origin --follow-tags", "postversion": "npm publish", "preversion": "npm test", "snap": "tap", "test": "tap" }, "tap": { "check-coverage": true }, "version": "1.0.1" } PK ~\uP  7minipass-json-stream/node_modules/minipass/package.jsonnu[{ "_id": "minipass@3.3.6", "_inBundle": true, "_location": "/npm/minipass-json-stream/minipass", "_phantomChildren": {}, "_requiredBy": [ "/npm/minipass-json-stream" ], "author": { "name": "Isaac Z. Schlueter", "email": "i@izs.me", "url": "http://blog.izs.me/" }, "bugs": { "url": "https://github.com/isaacs/minipass/issues" }, "dependencies": { "yallist": "^4.0.0" }, "description": "minimal implementation of a PassThrough stream", "devDependencies": { "@types/node": "^17.0.41", "end-of-stream": "^1.4.0", "prettier": "^2.6.2", "tap": "^16.2.0", "through2": "^2.0.3", "ts-node": "^10.8.1", "typescript": "^4.7.3" }, "engines": { "node": ">=8" }, "files": [ "index.d.ts", "index.js" ], "homepage": "https://github.com/isaacs/minipass#readme", "keywords": [ "passthrough", "stream" ], "license": "ISC", "main": "index.js", "name": "minipass", "prettier": { "semi": false, "printWidth": 80, "tabWidth": 2, "useTabs": false, "singleQuote": true, "jsxSingleQuote": false, "bracketSameLine": true, "arrowParens": "avoid", "endOfLine": "lf" }, "repository": { "type": "git", "url": "git+https://github.com/isaacs/minipass.git" }, "scripts": { "postpublish": "git push origin --follow-tags", "postversion": "npm publish", "preversion": "npm test", "test": "tap" }, "tap": { "check-coverage": true }, "types": "index.d.ts", "version": "3.3.6" } PK ~\2minipass-json-stream/node_modules/minipass/LICENSEnu[The ISC License Copyright (c) 2017-2022 npm, Inc., Isaac Z. Schlueter, and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\-@@3minipass-json-stream/node_modules/minipass/index.jsnu['use strict' const proc = typeof process === 'object' && process ? process : { stdout: null, stderr: null, } const EE = require('events') const Stream = require('stream') const SD = require('string_decoder').StringDecoder const EOF = Symbol('EOF') const MAYBE_EMIT_END = Symbol('maybeEmitEnd') const EMITTED_END = Symbol('emittedEnd') const EMITTING_END = Symbol('emittingEnd') const EMITTED_ERROR = Symbol('emittedError') const CLOSED = Symbol('closed') const READ = Symbol('read') const FLUSH = Symbol('flush') const FLUSHCHUNK = Symbol('flushChunk') const ENCODING = Symbol('encoding') const DECODER = Symbol('decoder') const FLOWING = Symbol('flowing') const PAUSED = Symbol('paused') const RESUME = Symbol('resume') const BUFFERLENGTH = Symbol('bufferLength') const BUFFERPUSH = Symbol('bufferPush') const BUFFERSHIFT = Symbol('bufferShift') const OBJECTMODE = Symbol('objectMode') const DESTROYED = Symbol('destroyed') const EMITDATA = Symbol('emitData') const EMITEND = Symbol('emitEnd') const EMITEND2 = Symbol('emitEnd2') const ASYNC = Symbol('async') const defer = fn => Promise.resolve().then(fn) // TODO remove when Node v8 support drops const doIter = global._MP_NO_ITERATOR_SYMBOLS_ !== '1' const ASYNCITERATOR = doIter && Symbol.asyncIterator || Symbol('asyncIterator not implemented') const ITERATOR = doIter && Symbol.iterator || Symbol('iterator not implemented') // events that mean 'the stream is over' // these are treated specially, and re-emitted // if they are listened for after emitting. const isEndish = ev => ev === 'end' || ev === 'finish' || ev === 'prefinish' const isArrayBuffer = b => b instanceof ArrayBuffer || typeof b === 'object' && b.constructor && b.constructor.name === 'ArrayBuffer' && b.byteLength >= 0 const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b) class Pipe { constructor (src, dest, opts) { this.src = src this.dest = dest this.opts = opts this.ondrain = () => src[RESUME]() dest.on('drain', this.ondrain) } unpipe () { this.dest.removeListener('drain', this.ondrain) } // istanbul ignore next - only here for the prototype proxyErrors () {} end () { this.unpipe() if (this.opts.end) this.dest.end() } } class PipeProxyErrors extends Pipe { unpipe () { this.src.removeListener('error', this.proxyErrors) super.unpipe() } constructor (src, dest, opts) { super(src, dest, opts) this.proxyErrors = er => dest.emit('error', er) src.on('error', this.proxyErrors) } } module.exports = class Minipass extends Stream { constructor (options) { super() this[FLOWING] = false // whether we're explicitly paused this[PAUSED] = false this.pipes = [] this.buffer = [] this[OBJECTMODE] = options && options.objectMode || false if (this[OBJECTMODE]) this[ENCODING] = null else this[ENCODING] = options && options.encoding || null if (this[ENCODING] === 'buffer') this[ENCODING] = null this[ASYNC] = options && !!options.async || false this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null this[EOF] = false this[EMITTED_END] = false this[EMITTING_END] = false this[CLOSED] = false this[EMITTED_ERROR] = null this.writable = true this.readable = true this[BUFFERLENGTH] = 0 this[DESTROYED] = false } get bufferLength () { return this[BUFFERLENGTH] } get encoding () { return this[ENCODING] } set encoding (enc) { if (this[OBJECTMODE]) throw new Error('cannot set encoding in objectMode') if (this[ENCODING] && enc !== this[ENCODING] && (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH])) throw new Error('cannot change encoding') if (this[ENCODING] !== enc) { this[DECODER] = enc ? new SD(enc) : null if (this.buffer.length) this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk)) } this[ENCODING] = enc } setEncoding (enc) { this.encoding = enc } get objectMode () { return this[OBJECTMODE] } set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om } get ['async'] () { return this[ASYNC] } set ['async'] (a) { this[ASYNC] = this[ASYNC] || !!a } write (chunk, encoding, cb) { if (this[EOF]) throw new Error('write after end') if (this[DESTROYED]) { this.emit('error', Object.assign( new Error('Cannot call write after a stream was destroyed'), { code: 'ERR_STREAM_DESTROYED' } )) return true } if (typeof encoding === 'function') cb = encoding, encoding = 'utf8' if (!encoding) encoding = 'utf8' const fn = this[ASYNC] ? defer : f => f() // convert array buffers and typed array views into buffers // at some point in the future, we may want to do the opposite! // leave strings and buffers as-is // anything else switches us into object mode if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { if (isArrayBufferView(chunk)) chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) else if (isArrayBuffer(chunk)) chunk = Buffer.from(chunk) else if (typeof chunk !== 'string') // use the setter so we throw if we have encoding set this.objectMode = true } // handle object mode up front, since it's simpler // this yields better performance, fewer checks later. if (this[OBJECTMODE]) { /* istanbul ignore if - maybe impossible? */ if (this.flowing && this[BUFFERLENGTH] !== 0) this[FLUSH](true) if (this.flowing) this.emit('data', chunk) else this[BUFFERPUSH](chunk) if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } // at this point the chunk is a buffer or string // don't buffer it up or send it to the decoder if (!chunk.length) { if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } // fast-path writing strings of same encoding to a stream with // an empty buffer, skipping the buffer/decoder dance if (typeof chunk === 'string' && // unless it is a string already ready for us to use !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) { chunk = Buffer.from(chunk, encoding) } if (Buffer.isBuffer(chunk) && this[ENCODING]) chunk = this[DECODER].write(chunk) // Note: flushing CAN potentially switch us into not-flowing mode if (this.flowing && this[BUFFERLENGTH] !== 0) this[FLUSH](true) if (this.flowing) this.emit('data', chunk) else this[BUFFERPUSH](chunk) if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } read (n) { if (this[DESTROYED]) return null if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) { this[MAYBE_EMIT_END]() return null } if (this[OBJECTMODE]) n = null if (this.buffer.length > 1 && !this[OBJECTMODE]) { if (this.encoding) this.buffer = [this.buffer.join('')] else this.buffer = [Buffer.concat(this.buffer, this[BUFFERLENGTH])] } const ret = this[READ](n || null, this.buffer[0]) this[MAYBE_EMIT_END]() return ret } [READ] (n, chunk) { if (n === chunk.length || n === null) this[BUFFERSHIFT]() else { this.buffer[0] = chunk.slice(n) chunk = chunk.slice(0, n) this[BUFFERLENGTH] -= n } this.emit('data', chunk) if (!this.buffer.length && !this[EOF]) this.emit('drain') return chunk } end (chunk, encoding, cb) { if (typeof chunk === 'function') cb = chunk, chunk = null if (typeof encoding === 'function') cb = encoding, encoding = 'utf8' if (chunk) this.write(chunk, encoding) if (cb) this.once('end', cb) this[EOF] = true this.writable = false // if we haven't written anything, then go ahead and emit, // even if we're not reading. // we'll re-emit if a new 'end' listener is added anyway. // This makes MP more suitable to write-only use cases. if (this.flowing || !this[PAUSED]) this[MAYBE_EMIT_END]() return this } // don't let the internal resume be overwritten [RESUME] () { if (this[DESTROYED]) return this[PAUSED] = false this[FLOWING] = true this.emit('resume') if (this.buffer.length) this[FLUSH]() else if (this[EOF]) this[MAYBE_EMIT_END]() else this.emit('drain') } resume () { return this[RESUME]() } pause () { this[FLOWING] = false this[PAUSED] = true } get destroyed () { return this[DESTROYED] } get flowing () { return this[FLOWING] } get paused () { return this[PAUSED] } [BUFFERPUSH] (chunk) { if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1 else this[BUFFERLENGTH] += chunk.length this.buffer.push(chunk) } [BUFFERSHIFT] () { if (this.buffer.length) { if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1 else this[BUFFERLENGTH] -= this.buffer[0].length } return this.buffer.shift() } [FLUSH] (noDrain) { do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]())) if (!noDrain && !this.buffer.length && !this[EOF]) this.emit('drain') } [FLUSHCHUNK] (chunk) { return chunk ? (this.emit('data', chunk), this.flowing) : false } pipe (dest, opts) { if (this[DESTROYED]) return const ended = this[EMITTED_END] opts = opts || {} if (dest === proc.stdout || dest === proc.stderr) opts.end = false else opts.end = opts.end !== false opts.proxyErrors = !!opts.proxyErrors // piping an ended stream ends immediately if (ended) { if (opts.end) dest.end() } else { this.pipes.push(!opts.proxyErrors ? new Pipe(this, dest, opts) : new PipeProxyErrors(this, dest, opts)) if (this[ASYNC]) defer(() => this[RESUME]()) else this[RESUME]() } return dest } unpipe (dest) { const p = this.pipes.find(p => p.dest === dest) if (p) { this.pipes.splice(this.pipes.indexOf(p), 1) p.unpipe() } } addListener (ev, fn) { return this.on(ev, fn) } on (ev, fn) { const ret = super.on(ev, fn) if (ev === 'data' && !this.pipes.length && !this.flowing) this[RESUME]() else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) super.emit('readable') else if (isEndish(ev) && this[EMITTED_END]) { super.emit(ev) this.removeAllListeners(ev) } else if (ev === 'error' && this[EMITTED_ERROR]) { if (this[ASYNC]) defer(() => fn.call(this, this[EMITTED_ERROR])) else fn.call(this, this[EMITTED_ERROR]) } return ret } get emittedEnd () { return this[EMITTED_END] } [MAYBE_EMIT_END] () { if (!this[EMITTING_END] && !this[EMITTED_END] && !this[DESTROYED] && this.buffer.length === 0 && this[EOF]) { this[EMITTING_END] = true this.emit('end') this.emit('prefinish') this.emit('finish') if (this[CLOSED]) this.emit('close') this[EMITTING_END] = false } } emit (ev, data, ...extra) { // error and close are only events allowed after calling destroy() if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED]) return else if (ev === 'data') { return !data ? false : this[ASYNC] ? defer(() => this[EMITDATA](data)) : this[EMITDATA](data) } else if (ev === 'end') { return this[EMITEND]() } else if (ev === 'close') { this[CLOSED] = true // don't emit close before 'end' and 'finish' if (!this[EMITTED_END] && !this[DESTROYED]) return const ret = super.emit('close') this.removeAllListeners('close') return ret } else if (ev === 'error') { this[EMITTED_ERROR] = data const ret = super.emit('error', data) this[MAYBE_EMIT_END]() return ret } else if (ev === 'resume') { const ret = super.emit('resume') this[MAYBE_EMIT_END]() return ret } else if (ev === 'finish' || ev === 'prefinish') { const ret = super.emit(ev) this.removeAllListeners(ev) return ret } // Some other unknown event const ret = super.emit(ev, data, ...extra) this[MAYBE_EMIT_END]() return ret } [EMITDATA] (data) { for (const p of this.pipes) { if (p.dest.write(data) === false) this.pause() } const ret = super.emit('data', data) this[MAYBE_EMIT_END]() return ret } [EMITEND] () { if (this[EMITTED_END]) return this[EMITTED_END] = true this.readable = false if (this[ASYNC]) defer(() => this[EMITEND2]()) else this[EMITEND2]() } [EMITEND2] () { if (this[DECODER]) { const data = this[DECODER].end() if (data) { for (const p of this.pipes) { p.dest.write(data) } super.emit('data', data) } } for (const p of this.pipes) { p.end() } const ret = super.emit('end') this.removeAllListeners('end') return ret } // const all = await stream.collect() collect () { const buf = [] if (!this[OBJECTMODE]) buf.dataLength = 0 // set the promise first, in case an error is raised // by triggering the flow here. const p = this.promise() this.on('data', c => { buf.push(c) if (!this[OBJECTMODE]) buf.dataLength += c.length }) return p.then(() => buf) } // const data = await stream.concat() concat () { return this[OBJECTMODE] ? Promise.reject(new Error('cannot concat in objectMode')) : this.collect().then(buf => this[OBJECTMODE] ? Promise.reject(new Error('cannot concat in objectMode')) : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength)) } // stream.promise().then(() => done, er => emitted error) promise () { return new Promise((resolve, reject) => { this.on(DESTROYED, () => reject(new Error('stream destroyed'))) this.on('error', er => reject(er)) this.on('end', () => resolve()) }) } // for await (let chunk of stream) [ASYNCITERATOR] () { const next = () => { const res = this.read() if (res !== null) return Promise.resolve({ done: false, value: res }) if (this[EOF]) return Promise.resolve({ done: true }) let resolve = null let reject = null const onerr = er => { this.removeListener('data', ondata) this.removeListener('end', onend) reject(er) } const ondata = value => { this.removeListener('error', onerr) this.removeListener('end', onend) this.pause() resolve({ value: value, done: !!this[EOF] }) } const onend = () => { this.removeListener('error', onerr) this.removeListener('data', ondata) resolve({ done: true }) } const ondestroy = () => onerr(new Error('stream destroyed')) return new Promise((res, rej) => { reject = rej resolve = res this.once(DESTROYED, ondestroy) this.once('error', onerr) this.once('end', onend) this.once('data', ondata) }) } return { next } } // for (let chunk of stream) [ITERATOR] () { const next = () => { const value = this.read() const done = value === null return { value, done } } return { next } } destroy (er) { if (this[DESTROYED]) { if (er) this.emit('error', er) else this.emit(DESTROYED) return this } this[DESTROYED] = true // throw away all buffered data, it's never coming out this.buffer.length = 0 this[BUFFERLENGTH] = 0 if (typeof this.close === 'function' && !this[CLOSED]) this.close() if (er) this.emit('error', er) else // if no error to emit, still reject pending promises this.emit(DESTROYED) return this } static isStream (s) { return !!s && (s instanceof Minipass || s instanceof Stream || s instanceof EE && ( typeof s.pipe === 'function' || // readable (typeof s.write === 'function' && typeof s.end === 'function') // writable )) } } PK ~\{minipass-json-stream/LICENSEnu[The MIT License Copyright (c) Isaac Z. Schlueter and Contributors Copyright (c) 2011 Dominic Tarr Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ---- This is a derivative work based on JSONStream by Dominic Tarr, modified and redistributed according to the terms of the MIT license above. https://github.com/dominictarr/JSONStream PK ~\V typeof x === 'string' ? String(y) === x : x && typeof x.test === 'function' ? x.test(y) : typeof x === 'boolean' || typeof x === 'object' ? x : typeof x === 'function' ? x(y) : false const _parser = Symbol('_parser') const _onValue = Symbol('_onValue') const _onTokenOriginal = Symbol('_onTokenOriginal') const _onToken = Symbol('_onToken') const _onError = Symbol('_onError') const _count = Symbol('_count') const _path = Symbol('_path') const _map = Symbol('_map') const _root = Symbol('_root') const _header = Symbol('_header') const _footer = Symbol('_footer') const _setHeaderFooter = Symbol('_setHeaderFooter') const _ending = Symbol('_ending') class JSONStream extends Minipass { constructor (opts = {}) { super({ ...opts, objectMode: true, }) this[_ending] = false const parser = this[_parser] = new Parser() parser.onValue = value => this[_onValue](value) this[_onTokenOriginal] = parser.onToken parser.onToken = (token, value) => this[_onToken](token, value) parser.onError = er => this[_onError](er) this[_count] = 0 this[_path] = typeof opts.path === 'string' ? opts.path.split('.').map(e => e === '$*' ? { emitKey: true } : e === '*' ? true : e === '' ? { recurse: true } : e) : Array.isArray(opts.path) && opts.path.length ? opts.path : null this[_map] = typeof opts.map === 'function' ? opts.map : null this[_root] = null this[_header] = null this[_footer] = null this[_count] = 0 } [_setHeaderFooter] (key, value) { // header has not been emitted yet if (this[_header] !== false) { this[_header] = this[_header] || {} this[_header][key] = value } // footer has not been emitted yet but header has if (this[_footer] !== false && this[_header] === false) { this[_footer] = this[_footer] || {} this[_footer][key] = value } } [_onError] (er) { // error will always happen during a write() call. const caller = this[_ending] ? this.end : this.write this[_ending] = false return this.emit('error', new JSONStreamError(er, caller)) } [_onToken] (token, value) { const parser = this[_parser] this[_onTokenOriginal].call(parser, token, value) if (parser.stack.length === 0) { if (this[_root]) { const root = this[_root] if (!this[_path]) super.write(root) this[_root] = null this[_count] = 0 } } } [_onValue] (value) { const parser = this[_parser] // the LAST onValue encountered is the root object. // just overwrite it each time. this[_root] = value if(!this[_path]) return let i = 0 // iterates on path let j = 0 // iterates on stack let emitKey = false let emitPath = false while (i < this[_path].length) { const key = this[_path][i] j++ if (key && !key.recurse) { const c = (j === parser.stack.length) ? parser : parser.stack[j] if (!c) return if (!check(key, c.key)) { this[_setHeaderFooter](c.key, value) return } emitKey = !!key.emitKey; emitPath = !!key.emitPath; i++ } else { i++ if (i >= this[_path].length) return const nextKey = this[_path][i] if (!nextKey) return while (true) { const c = (j === parser.stack.length) ? parser : parser.stack[j] if (!c) return if (check(nextKey, c.key)) { i++ if (!Object.isFrozen(parser.stack[j])) parser.stack[j].value = null break } else { this[_setHeaderFooter](c.key, value) } j++ } } } // emit header if (this[_header]) { const header = this[_header] this[_header] = false this.emit('header', header) } if (j !== parser.stack.length) return this[_count] ++ const actualPath = parser.stack.slice(1) .map(e => e.key).concat([parser.key]) if (value !== null && value !== undefined) { const data = this[_map] ? this[_map](value, actualPath) : value if (data !== null && data !== undefined) { const emit = emitKey || emitPath ? { value: data } : data if (emitKey) emit.key = parser.key if (emitPath) emit.path = actualPath super.write(emit) } } if (parser.value) delete parser.value[parser.key] for (const k of parser.stack) { k.value = null } } write (chunk, encoding, cb) { if (typeof encoding === 'function') cb = encoding, encoding = null if (typeof chunk === 'string') chunk = Buffer.from(chunk, encoding) else if (!Buffer.isBuffer(chunk)) return this.emit('error', new TypeError( 'Can only parse JSON from string or buffer input')) this[_parser].write(chunk) if (cb) cb() return this.flowing } end (chunk, encoding, cb) { this[_ending] = true if (typeof encoding === 'function') cb = encoding, encoding = null if (typeof chunk === 'function') cb = chunk, chunk = null if (chunk) this.write(chunk, encoding) if (cb) this.once('end', cb) const h = this[_header] this[_header] = null const f = this[_footer] this[_footer] = null if (h) this.emit('header', h) if (f) this.emit('footer', f) return super.end() } static get JSONStreamError () { return JSONStreamError } static parse (path, map) { return new JSONStream({path, map}) } } module.exports = JSONStream PK ~\_hh#node-gyp/src/win_delay_load_hook.ccnu[/* * When this file is linked to a DLL, it sets up a delay-load hook that * intervenes when the DLL is trying to load the host executable * dynamically. Instead of trying to locate the .exe file it'll just * return a handle to the process image. * * This allows compiled addons to work when the host executable is renamed. */ #ifdef _MSC_VER #pragma managed(push, off) #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include #include #include static FARPROC WINAPI load_exe_hook(unsigned int event, DelayLoadInfo* info) { HMODULE m; if (event != dliNotePreLoadLibrary) return NULL; if (_stricmp(info->szDll, HOST_BINARY) != 0) return NULL; m = GetModuleHandle(NULL); return (FARPROC) m; } decltype(__pfnDliNotifyHook2) __pfnDliNotifyHook2 = load_exe_hook; #pragma managed(pop) #endif PK ~\*k9eenode-gyp/CONTRIBUTING.mdnu[# Contributing to node-gyp ## Code of Conduct Please read the [Code of Conduct](https://github.com/nodejs/admin/blob/main/CODE_OF_CONDUCT.md) which explains the minimum behavior expectations for node-gyp contributors. ## Developer's Certificate of Origin 1.1 By making a contribution to this project, I certify that: * (a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or * (b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or * (c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it. * (d) I understand and agree that this project and the contribution are public and that a record of the contribution (including all personal information I submit with it, including my sign-off) is maintained indefinitely and may be redistributed consistent with this project or the open source license(s) involved. PK ~\i2HHnode-gyp/package.jsonnu[{ "_id": "node-gyp@10.1.0", "_inBundle": true, "_location": "/npm/node-gyp", "_phantomChildren": {}, "_requiredBy": [ "/npm", "/npm/@npmcli/run-script" ], "author": { "name": "Nathan Rajlich", "email": "nathan@tootallnate.net", "url": "http://tootallnate.net" }, "bin": { "node-gyp": "bin/node-gyp.js" }, "bugs": { "url": "https://github.com/nodejs/node-gyp/issues" }, "dependencies": { "env-paths": "^2.2.0", "exponential-backoff": "^3.1.1", "glob": "^10.3.10", "graceful-fs": "^4.2.6", "make-fetch-happen": "^13.0.0", "nopt": "^7.0.0", "proc-log": "^3.0.0", "semver": "^7.3.5", "tar": "^6.1.2", "which": "^4.0.0" }, "description": "Node.js native addon build tool", "devDependencies": { "bindings": "^1.5.0", "cross-env": "^7.0.3", "mocha": "^10.2.0", "nan": "^2.14.2", "require-inject": "^1.4.4", "standard": "^17.0.0" }, "engines": { "node": "^16.14.0 || >=18.0.0" }, "homepage": "https://github.com/nodejs/node-gyp#readme", "installVersion": 11, "keywords": [ "native", "addon", "module", "c", "c++", "bindings", "gyp" ], "license": "MIT", "main": "./lib/node-gyp.js", "name": "node-gyp", "preferGlobal": true, "repository": { "type": "git", "url": "git://github.com/nodejs/node-gyp.git" }, "scripts": { "lint": "standard \"*/*.js\" \"test/**/*.js\" \".github/**/*.js\"", "test": "cross-env NODE_GYP_NULL_LOGGER=true mocha --timeout 15000 test/test-download.js test/test-*" }, "version": "10.1.0" } PK ~\=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/proc-log#readme", "license": "ISC", "main": "lib/index.js", "name": "proc-log", "repository": { "type": "git", "url": "git+https://github.com/npm/proc-log.git" }, "scripts": { "lint": "eslint \"**/*.js\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "postsnap": "eslint index.js test/*.js --fix", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.5.1" }, "version": "3.0.0" } PK ~\:dd+node-gyp/node_modules/proc-log/lib/index.jsnu[// emits 'log' events on the process const LEVELS = [ 'notice', 'error', 'warn', 'info', 'verbose', 'http', 'silly', 'pause', 'resume', ] const log = level => (...args) => process.emit('log', level, ...args) const logger = {} for (const level of LEVELS) { logger[level] = log(level) } logger.LEVELS = LEVELS module.exports = logger PK ~\<&node-gyp/node_modules/proc-log/LICENSEnu[The ISC License Copyright (c) GitHub, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\&DDnode-gyp/lib/list.jsnu['use strict' const fs = require('graceful-fs').promises const log = require('./log') async function list (gyp, args) { const devDir = gyp.devDir log.verbose('list', 'using node-gyp dir:', devDir) let versions = [] try { const dir = await fs.readdir(devDir) if (Array.isArray(dir)) { versions = dir.filter((v) => v !== 'current') } } catch (err) { if (err && err.code !== 'ENOENT') { throw err } } return versions } module.exports = list module.exports.usage = 'Prints a listing of the currently installed node development files' PK ~\e%node-gyp/lib/download.jsnu[const fetch = require('make-fetch-happen') const { promises: fs } = require('graceful-fs') const log = require('./log') async function download (gyp, url) { log.http('GET', url) const requestOpts = { headers: { 'User-Agent': `node-gyp v${gyp.version} (node ${process.version})`, Connection: 'keep-alive' }, proxy: gyp.opts.proxy, noProxy: gyp.opts.noproxy } const cafile = gyp.opts.cafile if (cafile) { requestOpts.ca = await readCAFile(cafile) } const res = await fetch(url, requestOpts) log.http(res.status, res.url) return res } async function readCAFile (filename) { // The CA file can contain multiple certificates so split on certificate // boundaries. [\S\s]*? is used to match everything including newlines. const ca = await fs.readFile(filename, 'utf8') const re = /(-----BEGIN CERTIFICATE-----[\S\s]*?-----END CERTIFICATE-----)/g return ca.match(re) } module.exports = { download, readCAFile } PK ~\Ш9N,N,node-gyp/lib/configure.jsnu['use strict' const { promises: fs, readFileSync } = require('graceful-fs') const path = require('path') const log = require('./log') const os = require('os') const processRelease = require('./process-release') const win = process.platform === 'win32' const findNodeDirectory = require('./find-node-directory') const { createConfigGypi } = require('./create-config-gypi') const { format: msgFormat } = require('util') const { findAccessibleSync } = require('./util') const { findPython } = require('./find-python') const { findVisualStudio } = win ? require('./find-visualstudio') : {} const majorRe = /^#define NODE_MAJOR_VERSION (\d+)/m const minorRe = /^#define NODE_MINOR_VERSION (\d+)/m const patchRe = /^#define NODE_PATCH_VERSION (\d+)/m async function configure (gyp, argv) { const buildDir = path.resolve('build') const configNames = ['config.gypi', 'common.gypi'] const configs = [] let nodeDir const release = processRelease(argv, gyp, process.version, process.release) const python = await findPython(gyp.opts.python) return getNodeDir() async function getNodeDir () { // 'python' should be set by now process.env.PYTHON = python if (!gyp.opts.nodedir && process.config.variables.use_prefix_to_find_headers) { // check if the headers can be found using the prefix specified // at build time. Use them if they match the version expected const prefix = process.config.variables.node_prefix let availVersion try { const nodeVersionH = readFileSync(path.join(prefix, 'include', 'node', 'node_version.h'), { encoding: 'utf8' }) const major = nodeVersionH.match(majorRe)[1] const minor = nodeVersionH.match(minorRe)[1] const patch = nodeVersionH.match(patchRe)[1] availVersion = major + '.' + minor + '.' + patch } catch {} if (availVersion === release.version) { // ok version matches, use the headers gyp.opts.nodedir = prefix log.verbose('using local node headers based on prefix', 'setting nodedir to ' + gyp.opts.nodedir) } } if (gyp.opts.nodedir) { // --nodedir was specified. use that for the dev files nodeDir = gyp.opts.nodedir.replace(/^~/, os.homedir()) log.verbose('get node dir', 'compiling against specified --nodedir dev files: %s', nodeDir) } else { // if no --nodedir specified, ensure node dependencies are installed if ('v' + release.version !== process.version) { // if --target was given, then determine a target version to compile for log.verbose('get node dir', 'compiling against --target node version: %s', release.version) } else { // if no --target was specified then use the current host node version log.verbose('get node dir', 'no --target version specified, falling back to host node version: %s', release.version) } if (!release.semver) { // could not parse the version string with semver throw new Error('Invalid version number: ' + release.version) } // If the tarball option is set, always remove and reinstall the headers // into devdir. Otherwise only install if they're not already there. gyp.opts.ensure = !gyp.opts.tarball await gyp.commands.install([release.version]) log.verbose('get node dir', 'target node version installed:', release.versionDir) nodeDir = path.resolve(gyp.devDir, release.versionDir) } return createBuildDir() } async function createBuildDir () { log.verbose('build dir', 'attempting to create "build" dir: %s', buildDir) const isNew = await fs.mkdir(buildDir, { recursive: true }) log.verbose( 'build dir', '"build" dir needed to be created?', isNew ? 'Yes' : 'No' ) const vsInfo = win ? await findVisualStudio(release.semver, gyp.opts['msvs-version']) : null return createConfigFile(vsInfo) } async function createConfigFile (vsInfo) { if (win) { process.env.GYP_MSVS_VERSION = Math.min(vsInfo.versionYear, 2015) process.env.GYP_MSVS_OVERRIDE_PATH = vsInfo.path } const configPath = await createConfigGypi({ gyp, buildDir, nodeDir, vsInfo, python }) configs.push(configPath) return findConfigs() } async function findConfigs () { const name = configNames.shift() if (!name) { return runGyp() } const fullPath = path.resolve(name) log.verbose(name, 'checking for gypi file: %s', fullPath) try { await fs.stat(fullPath) log.verbose(name, 'found gypi file') configs.push(fullPath) } catch (err) { // ENOENT will check next gypi filename if (err.code !== 'ENOENT') { throw err } } return findConfigs() } async function runGyp () { if (!~argv.indexOf('-f') && !~argv.indexOf('--format')) { if (win) { log.verbose('gyp', 'gyp format was not specified; forcing "msvs"') // force the 'make' target for non-Windows argv.push('-f', 'msvs') } else { log.verbose('gyp', 'gyp format was not specified; forcing "make"') // force the 'make' target for non-Windows argv.push('-f', 'make') } } // include all the ".gypi" files that were found configs.forEach(function (config) { argv.push('-I', config) }) // For AIX and z/OS we need to set up the path to the exports file // which contains the symbols needed for linking. let nodeExpFile let nodeRootDir let candidates let logprefix = 'find exports file' if (process.platform === 'aix' || process.platform === 'os390' || process.platform === 'os400') { const ext = process.platform === 'os390' ? 'x' : 'exp' nodeRootDir = findNodeDirectory() if (process.platform === 'aix' || process.platform === 'os400') { candidates = [ 'include/node/node', 'out/Release/node', 'out/Debug/node', 'node' ].map(function (file) { return file + '.' + ext }) } else { candidates = [ 'out/Release/lib.target/libnode', 'out/Debug/lib.target/libnode', 'out/Release/obj.target/libnode', 'out/Debug/obj.target/libnode', 'lib/libnode' ].map(function (file) { return file + '.' + ext }) } nodeExpFile = findAccessibleSync(logprefix, nodeRootDir, candidates) if (nodeExpFile !== undefined) { log.verbose(logprefix, 'Found exports file: %s', nodeExpFile) } else { const msg = msgFormat('Could not find node.%s file in %s', ext, nodeRootDir) log.error(logprefix, 'Could not find exports file') throw new Error(msg) } } // For z/OS we need to set up the path to zoslib include directory, // which contains headers included in v8config.h. let zoslibIncDir if (process.platform === 'os390') { logprefix = "find zoslib's zos-base.h:" let msg let zoslibIncPath = process.env.ZOSLIB_INCLUDES if (zoslibIncPath) { zoslibIncPath = findAccessibleSync(logprefix, zoslibIncPath, ['zos-base.h']) if (zoslibIncPath === undefined) { msg = msgFormat('Could not find zos-base.h file in the directory set ' + 'in ZOSLIB_INCLUDES environment variable: %s; set it ' + 'to the correct path, or unset it to search %s', process.env.ZOSLIB_INCLUDES, nodeRootDir) } } else { candidates = [ 'include/node/zoslib/zos-base.h', 'include/zoslib/zos-base.h', 'zoslib/include/zos-base.h', 'install/include/node/zoslib/zos-base.h' ] zoslibIncPath = findAccessibleSync(logprefix, nodeRootDir, candidates) if (zoslibIncPath === undefined) { msg = msgFormat('Could not find any of %s in directory %s; set ' + 'environmant variable ZOSLIB_INCLUDES to the path ' + 'that contains zos-base.h', candidates.toString(), nodeRootDir) } } if (zoslibIncPath !== undefined) { zoslibIncDir = path.dirname(zoslibIncPath) log.verbose(logprefix, "Found zoslib's zos-base.h in: %s", zoslibIncDir) } else if (release.version.split('.')[0] >= 16) { // zoslib is only shipped in Node v16 and above. log.error(logprefix, msg) throw new Error(msg) } } // this logic ported from the old `gyp_addon` python file const gypScript = path.resolve(__dirname, '..', 'gyp', 'gyp_main.py') const addonGypi = path.resolve(__dirname, '..', 'addon.gypi') let commonGypi = path.resolve(nodeDir, 'include/node/common.gypi') try { await fs.stat(commonGypi) } catch (err) { commonGypi = path.resolve(nodeDir, 'common.gypi') } let outputDir = 'build' if (win) { // Windows expects an absolute path outputDir = buildDir } const nodeGypDir = path.resolve(__dirname, '..') let nodeLibFile = path.join(nodeDir, !gyp.opts.nodedir ? '<(target_arch)' : '$(Configuration)', release.name + '.lib') argv.push('-I', addonGypi) argv.push('-I', commonGypi) argv.push('-Dlibrary=shared_library') argv.push('-Dvisibility=default') argv.push('-Dnode_root_dir=' + nodeDir) if (process.platform === 'aix' || process.platform === 'os390' || process.platform === 'os400') { argv.push('-Dnode_exp_file=' + nodeExpFile) if (process.platform === 'os390' && zoslibIncDir) { argv.push('-Dzoslib_include_dir=' + zoslibIncDir) } } argv.push('-Dnode_gyp_dir=' + nodeGypDir) // Do this to keep Cygwin environments happy, else the unescaped '\' gets eaten up, // resulting in bad paths, Ex c:parentFolderfolderanotherFolder instead of c:\parentFolder\folder\anotherFolder if (win) { nodeLibFile = nodeLibFile.replace(/\\/g, '\\\\') } argv.push('-Dnode_lib_file=' + nodeLibFile) argv.push('-Dmodule_root_dir=' + process.cwd()) argv.push('-Dnode_engine=' + (gyp.opts.node_engine || process.jsEngine || 'v8')) argv.push('--depth=.') argv.push('--no-parallel') // tell gyp to write the Makefile/Solution files into output_dir argv.push('--generator-output', outputDir) // tell make to write its output into the same dir argv.push('-Goutput_dir=.') // enforce use of the "binding.gyp" file argv.unshift('binding.gyp') // execute `gyp` from the current target nodedir argv.unshift(gypScript) // make sure python uses files that came with this particular node package const pypath = [path.join(__dirname, '..', 'gyp', 'pylib')] if (process.env.PYTHONPATH) { pypath.push(process.env.PYTHONPATH) } process.env.PYTHONPATH = pypath.join(win ? ';' : ':') await new Promise((resolve, reject) => { const cp = gyp.spawn(python, argv) cp.on('exit', (code) => { if (code !== 0) { reject(new Error('`gyp` failed with exit code: ' + code)) } else { // we're done resolve() } }) }) } } module.exports = configure module.exports.usage = 'Generates ' + (win ? 'MSVC project files' : 'a Makefile') + ' for the current module' PK ~\l 7 7node-gyp/lib/install.jsnu['use strict' const { createWriteStream, promises: fs } = require('graceful-fs') const os = require('os') const { backOff } = require('exponential-backoff') const tar = require('tar') const path = require('path') const { Transform, promises: { pipeline } } = require('stream') const crypto = require('crypto') const log = require('./log') const semver = require('semver') const { download } = require('./download') const processRelease = require('./process-release') const win = process.platform === 'win32' async function install (gyp, argv) { log.stdout() const release = processRelease(argv, gyp, process.version, process.release) // Detecting target_arch based on logic from create-cnfig-gyp.js. Used on Windows only. const arch = win ? (gyp.opts.target_arch || gyp.opts.arch || process.arch || 'ia32') : '' // Used to prevent downloading tarball if only new node.lib is required on Windows. let shouldDownloadTarball = true // Determine which node dev files version we are installing log.verbose('install', 'input version string %j', release.version) if (!release.semver) { // could not parse the version string with semver throw new Error('Invalid version number: ' + release.version) } if (semver.lt(release.version, '0.8.0')) { throw new Error('Minimum target version is `0.8.0` or greater. Got: ' + release.version) } // 0.x.y-pre versions are not published yet and cannot be installed. Bail. if (release.semver.prerelease[0] === 'pre') { log.verbose('detected "pre" node version', release.version) if (!gyp.opts.nodedir) { throw new Error('"pre" versions of node cannot be installed, use the --nodedir flag instead') } log.verbose('--nodedir flag was passed; skipping install', gyp.opts.nodedir) return } // flatten version into String log.verbose('install', 'installing version: %s', release.versionDir) // the directory where the dev files will be installed const devDir = path.resolve(gyp.devDir, release.versionDir) // If '--ensure' was passed, then don't *always* install the version; // check if it is already installed, and only install when needed if (gyp.opts.ensure) { log.verbose('install', '--ensure was passed, so won\'t reinstall if already installed') try { await fs.stat(devDir) } catch (err) { if (err.code === 'ENOENT') { log.verbose('install', 'version not already installed, continuing with install', release.version) try { return await go() } catch (err) { return rollback(err) } } else if (err.code === 'EACCES') { return eaccesFallback(err) } throw err } log.verbose('install', 'version is already installed, need to check "installVersion"') const installVersionFile = path.resolve(devDir, 'installVersion') let installVersion = 0 try { const ver = await fs.readFile(installVersionFile, 'ascii') installVersion = parseInt(ver, 10) || 0 } catch (err) { if (err.code !== 'ENOENT') { throw err } } log.verbose('got "installVersion"', installVersion) log.verbose('needs "installVersion"', gyp.package.installVersion) if (installVersion < gyp.package.installVersion) { log.verbose('install', 'version is no good; reinstalling') try { return await go() } catch (err) { return rollback(err) } } log.verbose('install', 'version is good') if (win) { log.verbose('on Windows; need to check node.lib') const nodeLibPath = path.resolve(devDir, arch, 'node.lib') try { await fs.stat(nodeLibPath) } catch (err) { if (err.code === 'ENOENT') { log.verbose('install', `version not already installed for ${arch}, continuing with install`, release.version) try { shouldDownloadTarball = false return await go() } catch (err) { return rollback(err) } } else if (err.code === 'EACCES') { return eaccesFallback(err) } throw err } } } else { try { return await go() } catch (err) { return rollback(err) } } async function copyDirectory (src, dest) { try { await fs.stat(src) } catch { throw new Error(`Missing source directory for copy: ${src}`) } await fs.mkdir(dest, { recursive: true }) const entries = await fs.readdir(src, { withFileTypes: true }) for (const entry of entries) { if (entry.isDirectory()) { await copyDirectory(path.join(src, entry.name), path.join(dest, entry.name)) } else if (entry.isFile()) { // with parallel installs, copying files may cause file errors on // Windows so use an exponential backoff to resolve collisions await backOff(async () => { try { await fs.copyFile(path.join(src, entry.name), path.join(dest, entry.name)) } catch (err) { // if ensure, check if file already exists and that's good enough if (gyp.opts.ensure && err.code === 'EBUSY') { try { await fs.stat(path.join(dest, entry.name)) return } catch {} } throw err } }) } else { throw new Error('Unexpected file directory entry type') } } } async function go () { log.verbose('ensuring devDir is created', devDir) // first create the dir for the node dev files try { const created = await fs.mkdir(devDir, { recursive: true }) if (created) { log.verbose('created devDir', created) } } catch (err) { if (err.code === 'EACCES') { return eaccesFallback(err) } throw err } // now download the node tarball const tarPath = gyp.opts.tarball let extractErrors = false let extractCount = 0 const contentShasums = {} const expectShasums = {} // checks if a file to be extracted from the tarball is valid. // only .h header files and the gyp files get extracted function isValid (path) { const isValid = valid(path) if (isValid) { log.verbose('extracted file from tarball', path) extractCount++ } else { // invalid log.silly('ignoring from tarball', path) } return isValid } function onwarn (code, message) { extractErrors = true log.error('error while extracting tarball', code, message) } // download the tarball and extract! // Ommited on Windows if only new node.lib is required // on Windows there can be file errors from tar if parallel installs // are happening (not uncommon with multiple native modules) so // extract the tarball to a temp directory first and then copy over const tarExtractDir = win ? await fs.mkdtemp(path.join(os.tmpdir(), 'node-gyp-tmp-')) : devDir try { if (shouldDownloadTarball) { if (tarPath) { await tar.extract({ file: tarPath, strip: 1, filter: isValid, onwarn, cwd: tarExtractDir }) } else { try { const res = await download(gyp, release.tarballUrl) if (res.status !== 200) { throw new Error(`${res.status} response downloading ${release.tarballUrl}`) } await pipeline( res.body, // content checksum new ShaSum((_, checksum) => { const filename = path.basename(release.tarballUrl).trim() contentShasums[filename] = checksum log.verbose('content checksum', filename, checksum) }), tar.extract({ strip: 1, cwd: tarExtractDir, filter: isValid, onwarn }) ) } catch (err) { // something went wrong downloading the tarball? if (err.code === 'ENOTFOUND') { throw new Error('This is most likely not a problem with node-gyp or the package itself and\n' + 'is related to network connectivity. In most cases you are behind a proxy or have bad \n' + 'network settings.') } throw err } } // invoked after the tarball has finished being extracted if (extractErrors || extractCount === 0) { throw new Error('There was a fatal problem while downloading/extracting the tarball') } log.verbose('tarball', 'done parsing tarball') } const installVersionPath = path.resolve(tarExtractDir, 'installVersion') await Promise.all([ // need to download node.lib ...(win ? [downloadNodeLib()] : []), // write the "installVersion" file fs.writeFile(installVersionPath, gyp.package.installVersion + '\n'), // Only download SHASUMS.txt if we downloaded something in need of SHA verification ...(!tarPath || win ? [downloadShasums()] : []) ]) log.verbose('download contents checksum', JSON.stringify(contentShasums)) // check content shasums for (const k in contentShasums) { log.verbose('validating download checksum for ' + k, '(%s == %s)', contentShasums[k], expectShasums[k]) if (contentShasums[k] !== expectShasums[k]) { throw new Error(k + ' local checksum ' + contentShasums[k] + ' not match remote ' + expectShasums[k]) } } // copy over the files from the temp tarball extract directory to devDir if (tarExtractDir !== devDir) { await copyDirectory(tarExtractDir, devDir) } } finally { if (tarExtractDir !== devDir) { try { // try to cleanup temp dir await fs.rm(tarExtractDir, { recursive: true }) } catch { log.warn('failed to clean up temp tarball extract directory') } } } async function downloadShasums () { log.verbose('check download content checksum, need to download `SHASUMS256.txt`...') log.verbose('checksum url', release.shasumsUrl) const res = await download(gyp, release.shasumsUrl) if (res.status !== 200) { throw new Error(`${res.status} status code downloading checksum`) } for (const line of (await res.text()).trim().split('\n')) { const items = line.trim().split(/\s+/) if (items.length !== 2) { return } // 0035d18e2dcf9aad669b1c7c07319e17abfe3762 ./node-v0.11.4.tar.gz const name = items[1].replace(/^\.\//, '') expectShasums[name] = items[0] } log.verbose('checksum data', JSON.stringify(expectShasums)) } async function downloadNodeLib () { log.verbose('on Windows; need to download `' + release.name + '.lib`...') const dir = path.resolve(tarExtractDir, arch) const targetLibPath = path.resolve(dir, release.name + '.lib') const { libUrl, libPath } = release[arch] const name = `${arch} ${release.name}.lib` log.verbose(name, 'dir', dir) log.verbose(name, 'url', libUrl) await fs.mkdir(dir, { recursive: true }) log.verbose('streaming', name, 'to:', targetLibPath) const res = await download(gyp, libUrl) // Since only required node.lib is downloaded throw error if it is not fetched if (res.status !== 200) { throw new Error(`${res.status} status code downloading ${name}`) } return pipeline( res.body, new ShaSum((_, checksum) => { contentShasums[libPath] = checksum log.verbose('content checksum', libPath, checksum) }), createWriteStream(targetLibPath) ) } // downloadNodeLib() } // go() /** * Checks if a given filename is "valid" for this installation. */ function valid (file) { // header files const extname = path.extname(file) return extname === '.h' || extname === '.gypi' } async function rollback (err) { log.warn('install', 'got an error, rolling back install') // roll-back the install if anything went wrong await gyp.commands.remove([release.versionDir]) throw err } /** * The EACCES fallback is a workaround for npm's `sudo` behavior, where * it drops the permissions before invoking any child processes (like * node-gyp). So what happens is the "nobody" user doesn't have * permission to create the dev dir. As a fallback, make the tmpdir() be * the dev dir for this installation. This is not ideal, but at least * the compilation will succeed... */ async function eaccesFallback (err) { const noretry = '--node_gyp_internal_noretry' if (argv.indexOf(noretry) !== -1) { throw err } const tmpdir = os.tmpdir() gyp.devDir = path.resolve(tmpdir, '.node-gyp') let userString = '' try { // os.userInfo can fail on some systems, it's not critical here userString = ` ("${os.userInfo().username}")` } catch (e) {} log.warn('EACCES', 'current user%s does not have permission to access the dev dir "%s"', userString, devDir) log.warn('EACCES', 'attempting to reinstall using temporary dev dir "%s"', gyp.devDir) if (process.cwd() === tmpdir) { log.verbose('tmpdir == cwd', 'automatically will remove dev files after to save disk space') gyp.todo.push({ name: 'remove', args: argv }) } return gyp.commands.install([noretry].concat(argv)) } } class ShaSum extends Transform { constructor (callback) { super() this._callback = callback this._digester = crypto.createHash('sha256') } _transform (chunk, _, callback) { this._digester.update(chunk) callback(null, chunk) } _flush (callback) { this._callback(null, this._digester.digest('hex')) callback() } } module.exports = install module.exports.usage = 'Install node development files for the specified node version.' PK ~\$#node-gyp/lib/remove.jsnu['use strict' const fs = require('graceful-fs').promises const path = require('path') const log = require('./log') const semver = require('semver') async function remove (gyp, argv) { const devDir = gyp.devDir log.verbose('remove', 'using node-gyp dir:', devDir) // get the user-specified version to remove let version = argv[0] || gyp.opts.target log.verbose('remove', 'removing target version:', version) if (!version) { throw new Error('You must specify a version number to remove. Ex: "' + process.version + '"') } const versionSemver = semver.parse(version) if (versionSemver) { // flatten the version Array into a String version = versionSemver.version } const versionPath = path.resolve(gyp.devDir, version) log.verbose('remove', 'removing development files for version:', version) // first check if its even installed try { await fs.stat(versionPath) } catch (err) { if (err.code === 'ENOENT') { return 'version was already uninstalled: ' + version } throw err } await fs.rm(versionPath, { recursive: true, force: true }) } module.exports = remove module.exports.usage = 'Removes the node development files for the specified version' PK ~\0Dnode-gyp/lib/rebuild.jsnu['use strict' async function rebuild (gyp, argv) { gyp.todo.push( { name: 'clean', args: [] } , { name: 'configure', args: argv } , { name: 'build', args: [] } ) } module.exports = rebuild module.exports.usage = 'Runs "clean", "configure" and "build" all at once' PK ~\4.__node-gyp/lib/process-release.jsnu[/* eslint-disable n/no-deprecated-api */ 'use strict' const semver = require('semver') const url = require('url') const path = require('path') const log = require('./log') // versions where -headers.tar.gz started shipping const headersTarballRange = '>= 3.0.0 || ~0.12.10 || ~0.10.42' const bitsre = /\/win-(x86|x64|arm64)\// const bitsreV3 = /\/win-(x86|ia32|x64)\// // io.js v3.x.x shipped with "ia32" but should // have been "x86" // Captures all the logic required to determine download URLs, local directory and // file names. Inputs come from command-line switches (--target, --dist-url), // `process.version` and `process.release` where it exists. function processRelease (argv, gyp, defaultVersion, defaultRelease) { let version = (semver.valid(argv[0]) && argv[0]) || gyp.opts.target || defaultVersion const versionSemver = semver.parse(version) let overrideDistUrl = gyp.opts['dist-url'] || gyp.opts.disturl let isNamedForLegacyIojs let name let distBaseUrl let baseUrl let libUrl32 let libUrl64 let libUrlArm64 let tarballUrl let canGetHeaders if (!versionSemver) { // not a valid semver string, nothing we can do return { version } } // flatten version into String version = versionSemver.version // defaultVersion should come from process.version so ought to be valid semver const isDefaultVersion = version === semver.parse(defaultVersion).version // can't use process.release if we're using --target=x.y.z if (!isDefaultVersion) { defaultRelease = null } if (defaultRelease) { // v3 onward, has process.release name = defaultRelease.name.replace(/io\.js/, 'iojs') // remove the '.' for directory naming purposes } else { // old node or alternative --target= // semver.satisfies() doesn't like prerelease tags so test major directly isNamedForLegacyIojs = versionSemver.major >= 1 && versionSemver.major < 4 // isNamedForLegacyIojs is required to support Electron < 4 (in particular Electron 3) // as previously this logic was used to ensure "iojs" was used to download iojs releases // and "node" for node releases. Unfortunately the logic was broad enough that electron@3 // published release assets as "iojs" so that the node-gyp logic worked. Once Electron@3 has // been EOL for a while (late 2019) we should remove this hack. name = isNamedForLegacyIojs ? 'iojs' : 'node' } // check for the nvm.sh standard mirror env variables if (!overrideDistUrl && process.env.NODEJS_ORG_MIRROR) { overrideDistUrl = process.env.NODEJS_ORG_MIRROR } if (overrideDistUrl) { log.verbose('download', 'using dist-url', overrideDistUrl) } if (overrideDistUrl) { distBaseUrl = overrideDistUrl.replace(/\/+$/, '') } else { distBaseUrl = 'https://nodejs.org/dist' } distBaseUrl += '/v' + version + '/' // new style, based on process.release so we have a lot of the data we need if (defaultRelease && defaultRelease.headersUrl && !overrideDistUrl) { baseUrl = url.resolve(defaultRelease.headersUrl, './') libUrl32 = resolveLibUrl(name, defaultRelease.libUrl || baseUrl || distBaseUrl, 'x86', versionSemver.major) libUrl64 = resolveLibUrl(name, defaultRelease.libUrl || baseUrl || distBaseUrl, 'x64', versionSemver.major) libUrlArm64 = resolveLibUrl(name, defaultRelease.libUrl || baseUrl || distBaseUrl, 'arm64', versionSemver.major) tarballUrl = defaultRelease.headersUrl } else { // older versions without process.release are captured here and we have to make // a lot of assumptions, additionally if you --target=x.y.z then we can't use the // current process.release baseUrl = distBaseUrl libUrl32 = resolveLibUrl(name, baseUrl, 'x86', versionSemver.major) libUrl64 = resolveLibUrl(name, baseUrl, 'x64', versionSemver.major) libUrlArm64 = resolveLibUrl(name, baseUrl, 'arm64', versionSemver.major) // making the bold assumption that anything with a version number >3.0.0 will // have a *-headers.tar.gz file in its dist location, even some frankenstein // custom version canGetHeaders = semver.satisfies(versionSemver, headersTarballRange) tarballUrl = url.resolve(baseUrl, name + '-v' + version + (canGetHeaders ? '-headers' : '') + '.tar.gz') } return { version, semver: versionSemver, name, baseUrl, tarballUrl, shasumsUrl: url.resolve(baseUrl, 'SHASUMS256.txt'), versionDir: (name !== 'node' ? name + '-' : '') + version, ia32: { libUrl: libUrl32, libPath: normalizePath(path.relative(url.parse(baseUrl).path, url.parse(libUrl32).path)) }, x64: { libUrl: libUrl64, libPath: normalizePath(path.relative(url.parse(baseUrl).path, url.parse(libUrl64).path)) }, arm64: { libUrl: libUrlArm64, libPath: normalizePath(path.relative(url.parse(baseUrl).path, url.parse(libUrlArm64).path)) } } } function normalizePath (p) { return path.normalize(p).replace(/\\/g, '/') } function resolveLibUrl (name, defaultUrl, arch, versionMajor) { const base = url.resolve(defaultUrl, './') const hasLibUrl = bitsre.test(defaultUrl) || (versionMajor === 3 && bitsreV3.test(defaultUrl)) if (!hasLibUrl) { // let's assume it's a baseUrl then if (versionMajor >= 1) { return url.resolve(base, 'win-' + arch + '/' + name + '.lib') } // prior to io.js@1.0.0 32-bit node.lib lives in /, 64-bit lives in /x64/ return url.resolve(base, (arch === 'x86' ? '' : arch + '/') + name + '.lib') } // else we have a proper url to a .lib, just make sure it's the right arch return defaultUrl.replace(versionMajor === 3 ? bitsreV3 : bitsre, '/win-' + arch + '/') } module.exports = processRelease PK ~\anode-gyp/lib/node-gyp.jsnu['use strict' const path = require('path') const nopt = require('nopt') const log = require('./log') const childProcess = require('child_process') const { EventEmitter } = require('events') const commands = [ // Module build commands 'build', 'clean', 'configure', 'rebuild', // Development Header File management commands 'install', 'list', 'remove' ] class Gyp extends EventEmitter { /** * Export the contents of the package.json. */ package = require('../package.json') /** * nopt configuration definitions */ configDefs = { help: Boolean, // everywhere arch: String, // 'configure' cafile: String, // 'install' debug: Boolean, // 'build' directory: String, // bin make: String, // 'build' 'msvs-version': String, // 'configure' ensure: Boolean, // 'install' solution: String, // 'build' (windows only) proxy: String, // 'install' noproxy: String, // 'install' devdir: String, // everywhere nodedir: String, // 'configure' loglevel: String, // everywhere python: String, // 'configure' 'dist-url': String, // 'install' tarball: String, // 'install' jobs: String, // 'build' thin: String, // 'configure' 'force-process-config': Boolean // 'configure' } /** * nopt shorthands */ shorthands = { release: '--no-debug', C: '--directory', debug: '--debug', j: '--jobs', silly: '--loglevel=silly', verbose: '--loglevel=verbose', silent: '--loglevel=silent' } /** * expose the command aliases for the bin file to use. */ aliases = { ls: 'list', rm: 'remove' } constructor (...args) { super(...args) this.devDir = '' this.commands = commands.reduce((acc, command) => { acc[command] = (argv) => require('./' + command)(this, argv) return acc }, {}) Object.defineProperty(this, 'version', { enumerable: true, get: function () { return this.package.version } }) } /** * Parses the given argv array and sets the 'opts', * 'argv' and 'command' properties. */ parseArgv (argv) { this.opts = nopt(this.configDefs, this.shorthands, argv) this.argv = this.opts.argv.remain.slice() const commands = this.todo = [] // create a copy of the argv array with aliases mapped argv = this.argv.map((arg) => { // is this an alias? if (arg in this.aliases) { arg = this.aliases[arg] } return arg }) // process the mapped args into "command" objects ("name" and "args" props) argv.slice().forEach((arg) => { if (arg in this.commands) { const args = argv.splice(0, argv.indexOf(arg)) argv.shift() if (commands.length > 0) { commands[commands.length - 1].args = args } commands.push({ name: arg, args: [] }) } }) if (commands.length > 0) { commands[commands.length - 1].args = argv.splice(0) } // support for inheriting config env variables from npm const npmConfigPrefix = 'npm_config_' Object.keys(process.env).forEach((name) => { if (name.indexOf(npmConfigPrefix) !== 0) { return } const val = process.env[name] if (name === npmConfigPrefix + 'loglevel') { log.logger.level = val } else { // add the user-defined options to the config name = name.substring(npmConfigPrefix.length) // gyp@741b7f1 enters an infinite loop when it encounters // zero-length options so ensure those don't get through. if (name) { // convert names like force_process_config to force-process-config if (name.includes('_')) { name = name.replace(/_/g, '-') } this.opts[name] = val } } }) if (this.opts.loglevel) { log.logger.level = this.opts.loglevel } log.resume() } /** * Spawns a child process and emits a 'spawn' event. */ spawn (command, args, opts) { if (!opts) { opts = {} } if (!opts.silent && !opts.stdio) { opts.stdio = [0, 1, 2] } const cp = childProcess.spawn(command, args, opts) log.info('spawn', command) log.info('spawn args', args) return cp } /** * Returns the usage instructions for node-gyp. */ usage () { return [ '', ' Usage: node-gyp [options]', '', ' where is one of:', commands.map((c) => ' - ' + c + ' - ' + require('./' + c).usage).join('\n'), '', 'node-gyp@' + this.version + ' ' + path.resolve(__dirname, '..'), 'node@' + process.versions.node ].join('\n') } } module.exports = () => new Gyp() module.exports.Gyp = Gyp PK ~\Z0 nnnode-gyp/lib/build.jsnu['use strict' const fs = require('graceful-fs').promises const path = require('path') const { glob } = require('glob') const log = require('./log') const which = require('which') const win = process.platform === 'win32' async function build (gyp, argv) { let platformMake = 'make' if (process.platform === 'aix') { platformMake = 'gmake' } else if (process.platform === 'os400') { platformMake = 'gmake' } else if (process.platform.indexOf('bsd') !== -1) { platformMake = 'gmake' } else if (win && argv.length > 0) { argv = argv.map(function (target) { return '/t:' + target }) } const makeCommand = gyp.opts.make || process.env.MAKE || platformMake let command = win ? 'msbuild' : makeCommand const jobs = gyp.opts.jobs || process.env.JOBS let buildType let config let arch let nodeDir let guessedSolution let python let buildBinsDir await loadConfigGypi() /** * Load the "config.gypi" file that was generated during "configure". */ async function loadConfigGypi () { let data try { const configPath = path.resolve('build', 'config.gypi') data = await fs.readFile(configPath, 'utf8') } catch (err) { if (err.code === 'ENOENT') { throw new Error('You must run `node-gyp configure` first!') } else { throw err } } config = JSON.parse(data.replace(/#.+\n/, '')) // get the 'arch', 'buildType', and 'nodeDir' vars from the config buildType = config.target_defaults.default_configuration arch = config.variables.target_arch nodeDir = config.variables.nodedir python = config.variables.python if ('debug' in gyp.opts) { buildType = gyp.opts.debug ? 'Debug' : 'Release' } if (!buildType) { buildType = 'Release' } log.verbose('build type', buildType) log.verbose('architecture', arch) log.verbose('node dev dir', nodeDir) log.verbose('python', python) if (win) { await findSolutionFile() } else { await doWhich() } } /** * On Windows, find the first build/*.sln file. */ async function findSolutionFile () { const files = await glob('build/*.sln') if (files.length === 0) { throw new Error('Could not find *.sln file. Did you run "configure"?') } guessedSolution = files[0] log.verbose('found first Solution file', guessedSolution) await doWhich() } /** * Uses node-which to locate the msbuild / make executable. */ async function doWhich () { // On Windows use msbuild provided by node-gyp configure if (win) { if (!config.variables.msbuild_path) { throw new Error('MSBuild is not set, please run `node-gyp configure`.') } command = config.variables.msbuild_path log.verbose('using MSBuild:', command) await doBuild() return } // First make sure we have the build command in the PATH const execPath = await which(command) log.verbose('`which` succeeded for `' + command + '`', execPath) await doBuild() } /** * Actually spawn the process and compile the module. */ async function doBuild () { // Enable Verbose build const verbose = log.logger.isVisible('verbose') let j if (!win && verbose) { argv.push('V=1') } if (win && !verbose) { argv.push('/clp:Verbosity=minimal') } if (win) { // Turn off the Microsoft logo on Windows argv.push('/nologo') } // Specify the build type, Release by default if (win) { // Convert .gypi config target_arch to MSBuild /Platform // Since there are many ways to state '32-bit Intel', default to it. // N.B. msbuild's Condition string equality tests are case-insensitive. const archLower = arch.toLowerCase() const p = archLower === 'x64' ? 'x64' : (archLower === 'arm' ? 'ARM' : (archLower === 'arm64' ? 'ARM64' : 'Win32')) argv.push('/p:Configuration=' + buildType + ';Platform=' + p) if (jobs) { j = parseInt(jobs, 10) if (!isNaN(j) && j > 0) { argv.push('/m:' + j) } else if (jobs.toUpperCase() === 'MAX') { argv.push('/m:' + require('os').cpus().length) } } } else { argv.push('BUILDTYPE=' + buildType) // Invoke the Makefile in the 'build' dir. argv.push('-C') argv.push('build') if (jobs) { j = parseInt(jobs, 10) if (!isNaN(j) && j > 0) { argv.push('--jobs') argv.push(j) } else if (jobs.toUpperCase() === 'MAX') { argv.push('--jobs') argv.push(require('os').cpus().length) } } } if (win) { // did the user specify their own .sln file? const hasSln = argv.some(function (arg) { return path.extname(arg) === '.sln' }) if (!hasSln) { argv.unshift(gyp.opts.solution || guessedSolution) } } if (!win) { // Add build-time dependency symlinks (such as Python) to PATH buildBinsDir = path.resolve('build', 'node_gyp_bins') process.env.PATH = `${buildBinsDir}:${process.env.PATH}` await fs.mkdir(buildBinsDir, { recursive: true }) const symlinkDestination = path.join(buildBinsDir, 'python3') try { await fs.unlink(symlinkDestination) } catch (err) { if (err.code !== 'ENOENT') throw err } await fs.symlink(python, symlinkDestination) log.verbose('bin symlinks', `created symlink to "${python}" in "${buildBinsDir}" and added to PATH`) } const proc = gyp.spawn(command, argv) await new Promise((resolve, reject) => proc.on('exit', async (code, signal) => { if (buildBinsDir) { // Clean up the build-time dependency symlinks: await fs.rm(buildBinsDir, { recursive: true }) } if (code !== 0) { return reject(new Error('`' + command + '` failed with exit code: ' + code)) } if (signal) { return reject(new Error('`' + command + '` got signal: ' + signal)) } resolve() })) } } module.exports = build module.exports.usage = 'Invokes `' + (win ? 'msbuild' : 'make') + '` and builds the module' PK ~\K`node-gyp/lib/util.jsnu['use strict' const cp = require('child_process') const path = require('path') const { openSync, closeSync } = require('graceful-fs') const log = require('./log') const execFile = async (...args) => new Promise((resolve) => { const child = cp.execFile(...args, (...a) => resolve(a)) child.stdin.end() }) async function regGetValue (key, value, addOpts) { const outReValue = value.replace(/\W/g, '.') const outRe = new RegExp(`^\\s+${outReValue}\\s+REG_\\w+\\s+(\\S.*)$`, 'im') const reg = path.join(process.env.SystemRoot, 'System32', 'reg.exe') const regArgs = ['query', key, '/v', value].concat(addOpts) log.silly('reg', 'running', reg, regArgs) const [err, stdout, stderr] = await execFile(reg, regArgs, { encoding: 'utf8' }) log.silly('reg', 'reg.exe stdout = %j', stdout) if (err || stderr.trim() !== '') { log.silly('reg', 'reg.exe err = %j', err && (err.stack || err)) log.silly('reg', 'reg.exe stderr = %j', stderr) if (err) { throw err } throw new Error(stderr) } const result = outRe.exec(stdout) if (!result) { log.silly('reg', 'error parsing stdout') throw new Error('Could not parse output of reg.exe') } log.silly('reg', 'found: %j', result[1]) return result[1] } async function regSearchKeys (keys, value, addOpts) { for (const key of keys) { try { return await regGetValue(key, value, addOpts) } catch { continue } } } /** * Returns the first file or directory from an array of candidates that is * readable by the current user, or undefined if none of the candidates are * readable. */ function findAccessibleSync (logprefix, dir, candidates) { for (let next = 0; next < candidates.length; next++) { const candidate = path.resolve(dir, candidates[next]) let fd try { fd = openSync(candidate, 'r') } catch (e) { // this candidate was not found or not readable, do nothing log.silly(logprefix, 'Could not open %s: %s', candidate, e.message) continue } closeSync(fd) log.silly(logprefix, 'Found readable %s', candidate) return candidate } return undefined } module.exports = { execFile, regGetValue, regSearchKeys, findAccessibleSync } PK ~\%!node-gyp/lib/Find-VisualStudio.csnu[// Copyright 2017 - Refael Ackermann // Distributed under MIT style license // See accompanying file LICENSE at https://github.com/node4good/windows-autoconf // Usage: // powershell -ExecutionPolicy Unrestricted -Command "Add-Type -Path Find-VisualStudio.cs; [VisualStudioConfiguration.Main]::PrintJson()" // This script needs to be compatible with PowerShell v2 to run on Windows 2008R2 and Windows 7. using System; using System.Text; using System.Runtime.InteropServices; using System.Collections.Generic; namespace VisualStudioConfiguration { [Flags] public enum InstanceState : uint { None = 0, Local = 1, Registered = 2, NoRebootRequired = 4, NoErrors = 8, Complete = 4294967295, } [Guid("6380BCFF-41D3-4B2E-8B2E-BF8A6810C848")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface IEnumSetupInstances { void Next([MarshalAs(UnmanagedType.U4), In] int celt, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.Interface), Out] ISetupInstance[] rgelt, [MarshalAs(UnmanagedType.U4)] out int pceltFetched); void Skip([MarshalAs(UnmanagedType.U4), In] int celt); void Reset(); [return: MarshalAs(UnmanagedType.Interface)] IEnumSetupInstances Clone(); } [Guid("42843719-DB4C-46C2-8E7C-64F1816EFD5B")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface ISetupConfiguration { } [Guid("26AAB78C-4A60-49D6-AF3B-3C35BC93365D")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface ISetupConfiguration2 : ISetupConfiguration { [return: MarshalAs(UnmanagedType.Interface)] IEnumSetupInstances EnumInstances(); [return: MarshalAs(UnmanagedType.Interface)] ISetupInstance GetInstanceForCurrentProcess(); [return: MarshalAs(UnmanagedType.Interface)] ISetupInstance GetInstanceForPath([MarshalAs(UnmanagedType.LPWStr), In] string path); [return: MarshalAs(UnmanagedType.Interface)] IEnumSetupInstances EnumAllInstances(); } [Guid("B41463C3-8866-43B5-BC33-2B0676F7F42E")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface ISetupInstance { } [Guid("89143C9A-05AF-49B0-B717-72E218A2185C")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface ISetupInstance2 : ISetupInstance { [return: MarshalAs(UnmanagedType.BStr)] string GetInstanceId(); [return: MarshalAs(UnmanagedType.Struct)] System.Runtime.InteropServices.ComTypes.FILETIME GetInstallDate(); [return: MarshalAs(UnmanagedType.BStr)] string GetInstallationName(); [return: MarshalAs(UnmanagedType.BStr)] string GetInstallationPath(); [return: MarshalAs(UnmanagedType.BStr)] string GetInstallationVersion(); [return: MarshalAs(UnmanagedType.BStr)] string GetDisplayName([MarshalAs(UnmanagedType.U4), In] int lcid); [return: MarshalAs(UnmanagedType.BStr)] string GetDescription([MarshalAs(UnmanagedType.U4), In] int lcid); [return: MarshalAs(UnmanagedType.BStr)] string ResolvePath([MarshalAs(UnmanagedType.LPWStr), In] string pwszRelativePath); [return: MarshalAs(UnmanagedType.U4)] InstanceState GetState(); [return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_UNKNOWN)] ISetupPackageReference[] GetPackages(); ISetupPackageReference GetProduct(); [return: MarshalAs(UnmanagedType.BStr)] string GetProductPath(); [return: MarshalAs(UnmanagedType.VariantBool)] bool IsLaunchable(); [return: MarshalAs(UnmanagedType.VariantBool)] bool IsComplete(); [return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_UNKNOWN)] ISetupPropertyStore GetProperties(); [return: MarshalAs(UnmanagedType.BStr)] string GetEnginePath(); } [Guid("DA8D8A16-B2B6-4487-A2F1-594CCCCD6BF5")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface ISetupPackageReference { [return: MarshalAs(UnmanagedType.BStr)] string GetId(); [return: MarshalAs(UnmanagedType.BStr)] string GetVersion(); [return: MarshalAs(UnmanagedType.BStr)] string GetChip(); [return: MarshalAs(UnmanagedType.BStr)] string GetLanguage(); [return: MarshalAs(UnmanagedType.BStr)] string GetBranch(); [return: MarshalAs(UnmanagedType.BStr)] string GetType(); [return: MarshalAs(UnmanagedType.BStr)] string GetUniqueId(); [return: MarshalAs(UnmanagedType.VariantBool)] bool GetIsExtension(); } [Guid("c601c175-a3be-44bc-91f6-4568d230fc83")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] public interface ISetupPropertyStore { [return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_BSTR)] string[] GetNames(); object GetValue([MarshalAs(UnmanagedType.LPWStr), In] string pwszName); } [Guid("42843719-DB4C-46C2-8E7C-64F1816EFD5B")] [CoClass(typeof(SetupConfigurationClass))] [ComImport] public interface SetupConfiguration : ISetupConfiguration2, ISetupConfiguration { } [Guid("177F0C4A-1CD3-4DE7-A32C-71DBBB9FA36D")] [ClassInterface(ClassInterfaceType.None)] [ComImport] public class SetupConfigurationClass { } public static class Main { public static void PrintJson() { ISetupConfiguration query = new SetupConfiguration(); ISetupConfiguration2 query2 = (ISetupConfiguration2)query; IEnumSetupInstances e = query2.EnumAllInstances(); int pceltFetched; ISetupInstance2[] rgelt = new ISetupInstance2[1]; List instances = new List(); while (true) { e.Next(1, rgelt, out pceltFetched); if (pceltFetched <= 0) { Console.WriteLine(String.Format("[{0}]", string.Join(",", instances.ToArray()))); return; } try { instances.Add(InstanceJson(rgelt[0])); } catch (COMException) { // Ignore instances that can't be queried. } } } private static string JsonString(string s) { return "\"" + s.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\""; } private static string InstanceJson(ISetupInstance2 setupInstance2) { // Visual Studio component directory: // https://docs.microsoft.com/en-us/visualstudio/install/workload-and-component-ids StringBuilder json = new StringBuilder(); json.Append("{"); string path = JsonString(setupInstance2.GetInstallationPath()); json.Append(String.Format("\"path\":{0},", path)); string version = JsonString(setupInstance2.GetInstallationVersion()); json.Append(String.Format("\"version\":{0},", version)); List packages = new List(); foreach (ISetupPackageReference package in setupInstance2.GetPackages()) { string id = JsonString(package.GetId()); packages.Add(id); } json.Append(String.Format("\"packages\":[{0}]", string.Join(",", packages.ToArray()))); json.Append("}"); return json.ToString(); } } } PK ~\%0,soo"node-gyp/lib/create-config-gypi.jsnu['use strict' const fs = require('graceful-fs').promises const log = require('./log') const path = require('path') function parseConfigGypi (config) { // translated from tools/js2c.py of Node.js // 1. string comments config = config.replace(/#.*/g, '') // 2. join multiline strings config = config.replace(/'$\s+'/mg, '') // 3. normalize string literals from ' into " config = config.replace(/'/g, '"') return JSON.parse(config) } async function getBaseConfigGypi ({ gyp, nodeDir }) { // try reading $nodeDir/include/node/config.gypi first when: // 1. --dist-url or --nodedir is specified // 2. and --force-process-config is not specified const useCustomHeaders = gyp.opts.nodedir || gyp.opts.disturl || gyp.opts['dist-url'] const shouldReadConfigGypi = useCustomHeaders && !gyp.opts['force-process-config'] if (shouldReadConfigGypi && nodeDir) { try { const baseConfigGypiPath = path.resolve(nodeDir, 'include/node/config.gypi') const baseConfigGypi = await fs.readFile(baseConfigGypiPath) return parseConfigGypi(baseConfigGypi.toString()) } catch (err) { log.warn('read config.gypi', err.message) } } // fallback to process.config if it is invalid return JSON.parse(JSON.stringify(process.config)) } async function getCurrentConfigGypi ({ gyp, nodeDir, vsInfo, python }) { const config = await getBaseConfigGypi({ gyp, nodeDir }) if (!config.target_defaults) { config.target_defaults = {} } if (!config.variables) { config.variables = {} } const defaults = config.target_defaults const variables = config.variables // don't inherit the "defaults" from the base config.gypi. // doing so could cause problems in cases where the `node` executable was // compiled on a different machine (with different lib/include paths) than // the machine where the addon is being built to defaults.cflags = [] defaults.defines = [] defaults.include_dirs = [] defaults.libraries = [] // set the default_configuration prop if ('debug' in gyp.opts) { defaults.default_configuration = gyp.opts.debug ? 'Debug' : 'Release' } if (!defaults.default_configuration) { defaults.default_configuration = 'Release' } // set the target_arch variable variables.target_arch = gyp.opts.arch || process.arch || 'ia32' if (variables.target_arch === 'arm64') { defaults.msvs_configuration_platform = 'ARM64' defaults.xcode_configuration_platform = 'arm64' } // set the node development directory variables.nodedir = nodeDir // set the configured Python path variables.python = python // disable -T "thin" static archives by default variables.standalone_static_library = gyp.opts.thin ? 0 : 1 if (process.platform === 'win32') { defaults.msbuild_toolset = vsInfo.toolset if (vsInfo.sdk) { defaults.msvs_windows_target_platform_version = vsInfo.sdk } if (variables.target_arch === 'arm64') { if (vsInfo.versionMajor > 15 || (vsInfo.versionMajor === 15 && vsInfo.versionMajor >= 9)) { defaults.msvs_enable_marmasm = 1 } else { log.warn('Compiling ARM64 assembly is only available in\n' + 'Visual Studio 2017 version 15.9 and above') } } variables.msbuild_path = vsInfo.msBuild } // loop through the rest of the opts and add the unknown ones as variables. // this allows for module-specific configure flags like: // // $ node-gyp configure --shared-libxml2 Object.keys(gyp.opts).forEach(function (opt) { if (opt === 'argv') { return } if (opt in gyp.configDefs) { return } variables[opt.replace(/-/g, '_')] = gyp.opts[opt] }) return config } async function createConfigGypi ({ gyp, buildDir, nodeDir, vsInfo, python }) { const configFilename = 'config.gypi' const configPath = path.resolve(buildDir, configFilename) log.verbose('build/' + configFilename, 'creating config file') const config = await getCurrentConfigGypi({ gyp, nodeDir, vsInfo, python }) // ensures that any boolean values in config.gypi get stringified function boolsToString (k, v) { if (typeof v === 'boolean') { return String(v) } return v } log.silly('build/' + configFilename, config) // now write out the config.gypi file to the build/ dir const prefix = '# Do not edit. File was generated by node-gyp\'s "configure" step' const json = JSON.stringify(config, boolsToString, 2) log.verbose('build/' + configFilename, 'writing out config file: %s', configPath) await fs.writeFile(configPath, [prefix, json, ''].join('\n')) return configPath } module.exports = { createConfigGypi, parseConfigGypi, getCurrentConfigGypi } PK ~\n7UuEuE!node-gyp/lib/find-visualstudio.jsnu['use strict' const log = require('./log') const { existsSync } = require('fs') const { win32: path } = require('path') const { regSearchKeys, execFile } = require('./util') class VisualStudioFinder { static findVisualStudio = (...args) => new VisualStudioFinder(...args).findVisualStudio() log = log.withPrefix('find VS') regSearchKeys = regSearchKeys constructor (nodeSemver, configMsvsVersion) { this.nodeSemver = nodeSemver this.configMsvsVersion = configMsvsVersion this.errorLog = [] this.validVersions = [] } // Logs a message at verbose level, but also saves it to be displayed later // at error level if an error occurs. This should help diagnose the problem. addLog (message) { this.log.verbose(message) this.errorLog.push(message) } async findVisualStudio () { this.configVersionYear = null this.configPath = null if (this.configMsvsVersion) { this.addLog('msvs_version was set from command line or npm config') if (this.configMsvsVersion.match(/^\d{4}$/)) { this.configVersionYear = parseInt(this.configMsvsVersion, 10) this.addLog( `- looking for Visual Studio version ${this.configVersionYear}`) } else { this.configPath = path.resolve(this.configMsvsVersion) this.addLog( `- looking for Visual Studio installed in "${this.configPath}"`) } } else { this.addLog('msvs_version not set from command line or npm config') } if (process.env.VCINSTALLDIR) { this.envVcInstallDir = path.resolve(process.env.VCINSTALLDIR, '..') this.addLog('running in VS Command Prompt, installation path is:\n' + `"${this.envVcInstallDir}"\n- will only use this version`) } else { this.addLog('VCINSTALLDIR not set, not running in VS Command Prompt') } const checks = [ () => this.findVisualStudio2019OrNewerUsingSetupModule(), () => this.findVisualStudio2019OrNewer(), () => this.findVisualStudio2017UsingSetupModule(), () => this.findVisualStudio2017(), () => this.findVisualStudio2015(), () => this.findVisualStudio2013() ] for (const check of checks) { const info = await check() if (info) { return this.succeed(info) } } return this.fail() } succeed (info) { this.log.info(`using VS${info.versionYear} (${info.version}) found at:` + `\n"${info.path}"` + '\nrun with --verbose for detailed information') return info } fail () { if (this.configMsvsVersion && this.envVcInstallDir) { this.errorLog.push( 'msvs_version does not match this VS Command Prompt or the', 'installation cannot be used.') } else if (this.configMsvsVersion) { // If msvs_version was specified but finding VS failed, print what would // have been accepted this.errorLog.push('') if (this.validVersions) { this.errorLog.push('valid versions for msvs_version:') this.validVersions.forEach((version) => { this.errorLog.push(`- "${version}"`) }) } else { this.errorLog.push('no valid versions for msvs_version were found') } } const errorLog = this.errorLog.join('\n') // For Windows 80 col console, use up to the column before the one marked // with X (total 79 chars including logger prefix, 62 chars usable here): // X const infoLog = [ '**************************************************************', 'You need to install the latest version of Visual Studio', 'including the "Desktop development with C++" workload.', 'For more information consult the documentation at:', 'https://github.com/nodejs/node-gyp#on-windows', '**************************************************************' ].join('\n') this.log.error(`\n${errorLog}\n\n${infoLog}\n`) throw new Error('Could not find any Visual Studio installation to use') } async findVisualStudio2019OrNewerUsingSetupModule () { return this.findNewVSUsingSetupModule([2019, 2022]) } async findVisualStudio2017UsingSetupModule () { if (this.nodeSemver.major >= 22) { this.addLog( 'not looking for VS2017 as it is only supported up to Node.js 21') return null } return this.findNewVSUsingSetupModule([2017]) } async findNewVSUsingSetupModule (supportedYears) { const ps = path.join(process.env.SystemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe') const vcInstallDir = this.envVcInstallDir const checkModuleArgs = [ '-NoProfile', '-Command', '&{@(Get-Module -ListAvailable -Name VSSetup).Version.ToString()}' ] this.log.silly('Running', ps, checkModuleArgs) const [cErr] = await this.execFile(ps, checkModuleArgs) if (cErr) { this.addLog('VSSetup module doesn\'t seem to exist. You can install it via: "Install-Module VSSetup -Scope CurrentUser"') this.log.silly('VSSetup error = %j', cErr && (cErr.stack || cErr)) return null } const filterArg = vcInstallDir !== undefined ? `| where {$_.InstallationPath -eq '${vcInstallDir}' }` : '' const psArgs = [ '-NoProfile', '-Command', `&{Get-VSSetupInstance ${filterArg} | ConvertTo-Json -Depth 3}` ] this.log.silly('Running', ps, psArgs) const [err, stdout, stderr] = await this.execFile(ps, psArgs) let parsedData = this.parseData(err, stdout, stderr) if (parsedData === null) { return null } this.log.silly('Parsed data', parsedData) if (!Array.isArray(parsedData)) { // if there are only 1 result, then Powershell will output non-array parsedData = [parsedData] } // normalize output parsedData = parsedData.map((info) => { info.path = info.InstallationPath info.version = `${info.InstallationVersion.Major}.${info.InstallationVersion.Minor}.${info.InstallationVersion.Build}.${info.InstallationVersion.Revision}` info.packages = info.Packages.map((p) => p.Id) return info }) // pass for further processing return this.processData(parsedData, supportedYears) } // Invoke the PowerShell script to get information about Visual Studio 2019 // or newer installations async findVisualStudio2019OrNewer () { return this.findNewVS([2019, 2022]) } // Invoke the PowerShell script to get information about Visual Studio 2017 async findVisualStudio2017 () { if (this.nodeSemver.major >= 22) { this.addLog( 'not looking for VS2017 as it is only supported up to Node.js 21') return null } return this.findNewVS([2017]) } // Invoke the PowerShell script to get information about Visual Studio 2017 // or newer installations async findNewVS (supportedYears) { const ps = path.join(process.env.SystemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe') const csFile = path.join(__dirname, 'Find-VisualStudio.cs') const psArgs = [ '-ExecutionPolicy', 'Unrestricted', '-NoProfile', '-Command', '&{Add-Type -Path \'' + csFile + '\';' + '[VisualStudioConfiguration.Main]::PrintJson()}' ] this.log.silly('Running', ps, psArgs) const [err, stdout, stderr] = await this.execFile(ps, psArgs) const parsedData = this.parseData(err, stdout, stderr, { checkIsArray: true }) if (parsedData === null) { return null } return this.processData(parsedData, supportedYears) } // Parse the output of the PowerShell script, make sanity checks parseData (err, stdout, stderr, sanityCheckOptions) { const defaultOptions = { checkIsArray: false } // Merging provided options with the default options const sanityOptions = { ...defaultOptions, ...sanityCheckOptions } this.log.silly('PS stderr = %j', stderr) const failPowershell = (failureDetails) => { this.addLog( `could not use PowerShell to find Visual Studio 2017 or newer, try re-running with '--loglevel silly' for more details. \n Failure details: ${failureDetails}`) return null } if (err) { this.log.silly('PS err = %j', err && (err.stack || err)) return failPowershell(`${err}`.substring(0, 40)) } let vsInfo try { vsInfo = JSON.parse(stdout) } catch (e) { this.log.silly('PS stdout = %j', stdout) this.log.silly(e) return failPowershell() } if (sanityOptions.checkIsArray && !Array.isArray(vsInfo)) { this.log.silly('PS stdout = %j', stdout) return failPowershell('Expected array as output of the PS script') } return vsInfo } // Process parsed data containing information about VS installations // Look for the required parts, extract and output them back processData (vsInfo, supportedYears) { vsInfo = vsInfo.map((info) => { this.log.silly(`processing installation: "${info.path}"`) info.path = path.resolve(info.path) const ret = this.getVersionInfo(info) ret.path = info.path ret.msBuild = this.getMSBuild(info, ret.versionYear) ret.toolset = this.getToolset(info, ret.versionYear) ret.sdk = this.getSDK(info) return ret }) this.log.silly('vsInfo:', vsInfo) // Remove future versions or errors parsing version number // Also remove any unsupported versions vsInfo = vsInfo.filter((info) => { if (info.versionYear && supportedYears.indexOf(info.versionYear) !== -1) { return true } this.addLog(`${info.versionYear ? 'unsupported' : 'unknown'} version "${info.version}" found at "${info.path}"`) return false }) // Sort to place newer versions first vsInfo.sort((a, b) => b.versionYear - a.versionYear) for (let i = 0; i < vsInfo.length; ++i) { const info = vsInfo[i] this.addLog(`checking VS${info.versionYear} (${info.version}) found ` + `at:\n"${info.path}"`) if (info.msBuild) { this.addLog('- found "Visual Studio C++ core features"') } else { this.addLog('- "Visual Studio C++ core features" missing') continue } if (info.toolset) { this.addLog(`- found VC++ toolset: ${info.toolset}`) } else { this.addLog('- missing any VC++ toolset') continue } if (info.sdk) { this.addLog(`- found Windows SDK: ${info.sdk}`) } else { this.addLog('- missing any Windows SDK') continue } if (!this.checkConfigVersion(info.versionYear, info.path)) { continue } return info } this.addLog( 'could not find a version of Visual Studio 2017 or newer to use') return null } // Helper - process version information getVersionInfo (info) { const match = /^(\d+)\.(\d+)\..*/.exec(info.version) if (!match) { this.log.silly('- failed to parse version:', info.version) return {} } this.log.silly('- version match = %j', match) const ret = { version: info.version, versionMajor: parseInt(match[1], 10), versionMinor: parseInt(match[2], 10) } if (ret.versionMajor === 15) { ret.versionYear = 2017 return ret } if (ret.versionMajor === 16) { ret.versionYear = 2019 return ret } if (ret.versionMajor === 17) { ret.versionYear = 2022 return ret } this.log.silly('- unsupported version:', ret.versionMajor) return {} } msBuildPathExists (path) { return existsSync(path) } // Helper - process MSBuild information getMSBuild (info, versionYear) { const pkg = 'Microsoft.VisualStudio.VC.MSBuild.Base' const msbuildPath = path.join(info.path, 'MSBuild', 'Current', 'Bin', 'MSBuild.exe') const msbuildPathArm64 = path.join(info.path, 'MSBuild', 'Current', 'Bin', 'arm64', 'MSBuild.exe') if (info.packages.indexOf(pkg) !== -1) { this.log.silly('- found VC.MSBuild.Base') if (versionYear === 2017) { return path.join(info.path, 'MSBuild', '15.0', 'Bin', 'MSBuild.exe') } if (versionYear === 2019) { return msbuildPath } } /** * Visual Studio 2022 doesn't have the MSBuild package. * Support for compiling _on_ ARM64 was added in MSVC 14.32.31326, * so let's leverage it if the user has an ARM64 device. */ if (process.arch === 'arm64' && this.msBuildPathExists(msbuildPathArm64)) { return msbuildPathArm64 } else if (this.msBuildPathExists(msbuildPath)) { return msbuildPath } return null } // Helper - process toolset information getToolset (info, versionYear) { const pkg = 'Microsoft.VisualStudio.Component.VC.Tools.x86.x64' const express = 'Microsoft.VisualStudio.WDExpress' if (info.packages.indexOf(pkg) !== -1) { this.log.silly('- found VC.Tools.x86.x64') } else if (info.packages.indexOf(express) !== -1) { this.log.silly('- found Visual Studio Express (looking for toolset)') } else { return null } if (versionYear === 2017) { return 'v141' } else if (versionYear === 2019) { return 'v142' } else if (versionYear === 2022) { return 'v143' } this.log.silly('- invalid versionYear:', versionYear) return null } // Helper - process Windows SDK information getSDK (info) { const win8SDK = 'Microsoft.VisualStudio.Component.Windows81SDK' const win10SDKPrefix = 'Microsoft.VisualStudio.Component.Windows10SDK.' const win11SDKPrefix = 'Microsoft.VisualStudio.Component.Windows11SDK.' let Win10or11SDKVer = 0 info.packages.forEach((pkg) => { if (!pkg.startsWith(win10SDKPrefix) && !pkg.startsWith(win11SDKPrefix)) { return } const parts = pkg.split('.') if (parts.length > 5 && parts[5] !== 'Desktop') { this.log.silly('- ignoring non-Desktop Win10/11SDK:', pkg) return } const foundSdkVer = parseInt(parts[4], 10) if (isNaN(foundSdkVer)) { // Microsoft.VisualStudio.Component.Windows10SDK.IpOverUsb this.log.silly('- failed to parse Win10/11SDK number:', pkg) return } this.log.silly('- found Win10/11SDK:', foundSdkVer) Win10or11SDKVer = Math.max(Win10or11SDKVer, foundSdkVer) }) if (Win10or11SDKVer !== 0) { return `10.0.${Win10or11SDKVer}.0` } else if (info.packages.indexOf(win8SDK) !== -1) { this.log.silly('- found Win8SDK') return '8.1' } return null } // Find an installation of Visual Studio 2015 to use async findVisualStudio2015 () { if (this.nodeSemver.major >= 19) { this.addLog( 'not looking for VS2015 as it is only supported up to Node.js 18') return null } return this.findOldVS({ version: '14.0', versionMajor: 14, versionMinor: 0, versionYear: 2015, toolset: 'v140' }) } // Find an installation of Visual Studio 2013 to use async findVisualStudio2013 () { if (this.nodeSemver.major >= 9) { this.addLog( 'not looking for VS2013 as it is only supported up to Node.js 8') return null } return this.findOldVS({ version: '12.0', versionMajor: 12, versionMinor: 0, versionYear: 2013, toolset: 'v120' }) } // Helper - common code for VS2013 and VS2015 async findOldVS (info) { const regVC7 = ['HKLM\\Software\\Microsoft\\VisualStudio\\SxS\\VC7', 'HKLM\\Software\\Wow6432Node\\Microsoft\\VisualStudio\\SxS\\VC7'] const regMSBuild = 'HKLM\\Software\\Microsoft\\MSBuild\\ToolsVersions' this.addLog(`looking for Visual Studio ${info.versionYear}`) try { let res = await this.regSearchKeys(regVC7, info.version, []) const vsPath = path.resolve(res, '..') this.addLog(`- found in "${vsPath}"`) const msBuildRegOpts = process.arch === 'ia32' ? [] : ['/reg:32'] try { res = await this.regSearchKeys([`${regMSBuild}\\${info.version}`], 'MSBuildToolsPath', msBuildRegOpts) } catch (err) { this.addLog('- could not find MSBuild in registry for this version') return null } const msBuild = path.join(res, 'MSBuild.exe') this.addLog(`- MSBuild in "${msBuild}"`) if (!this.checkConfigVersion(info.versionYear, vsPath)) { return null } info.path = vsPath info.msBuild = msBuild info.sdk = null return info } catch (err) { this.addLog('- not found') return null } } // After finding a usable version of Visual Studio: // - add it to validVersions to be displayed at the end if a specific // version was requested and not found; // - check if this is the version that was requested. // - check if this matches the Visual Studio Command Prompt checkConfigVersion (versionYear, vsPath) { this.validVersions.push(versionYear) this.validVersions.push(vsPath) if (this.configVersionYear && this.configVersionYear !== versionYear) { this.addLog('- msvs_version does not match this version') return false } if (this.configPath && path.relative(this.configPath, vsPath) !== '') { this.addLog('- msvs_version does not point to this installation') return false } if (this.envVcInstallDir && path.relative(this.envVcInstallDir, vsPath) !== '') { this.addLog('- does not match this Visual Studio Command Prompt') return false } return true } async execFile (exec, args) { return await execFile(exec, args, { encoding: 'utf8' }) } } module.exports = VisualStudioFinder PK ~\"4J J #node-gyp/lib/find-node-directory.jsnu['use strict' const path = require('path') const log = require('./log') function findNodeDirectory (scriptLocation, processObj) { // set dirname and process if not passed in // this facilitates regression tests if (scriptLocation === undefined) { scriptLocation = __dirname } if (processObj === undefined) { processObj = process } // Have a look to see what is above us, to try and work out where we are const npmParentDirectory = path.join(scriptLocation, '../../../..') log.verbose('node-gyp root', 'npm_parent_directory is ' + path.basename(npmParentDirectory)) let nodeRootDir = '' log.verbose('node-gyp root', 'Finding node root directory') if (path.basename(npmParentDirectory) === 'deps') { // We are in a build directory where this script lives in // deps/npm/node_modules/node-gyp/lib nodeRootDir = path.join(npmParentDirectory, '..') log.verbose('node-gyp root', 'in build directory, root = ' + nodeRootDir) } else if (path.basename(npmParentDirectory) === 'node_modules') { // We are in a node install directory where this script lives in // lib/node_modules/npm/node_modules/node-gyp/lib or // node_modules/npm/node_modules/node-gyp/lib depending on the // platform if (processObj.platform === 'win32') { nodeRootDir = path.join(npmParentDirectory, '..') } else { nodeRootDir = path.join(npmParentDirectory, '../..') } log.verbose('node-gyp root', 'in install directory, root = ' + nodeRootDir) } else { // We don't know where we are, try working it out from the location // of the node binary const nodeDir = path.dirname(processObj.execPath) const directoryUp = path.basename(nodeDir) if (directoryUp === 'bin') { nodeRootDir = path.join(nodeDir, '..') } else if (directoryUp === 'Release' || directoryUp === 'Debug') { // If we are a recently built node, and the directory structure // is that of a repository. If we are on Windows then we only need // to go one level up, everything else, two if (processObj.platform === 'win32') { nodeRootDir = path.join(nodeDir, '..') } else { nodeRootDir = path.join(nodeDir, '../..') } } // Else return the default blank, "". } return nodeRootDir } module.exports = findNodeDirectory PK ~\?Tnode-gyp/lib/clean.jsnu['use strict' const fs = require('graceful-fs').promises const log = require('./log') async function clean (gyp, argv) { // Remove the 'build' dir const buildDir = 'build' log.verbose('clean', 'removing "%s" directory', buildDir) await fs.rm(buildDir, { recursive: true, force: true }) } module.exports = clean module.exports.usage = 'Removes any generated build files and the "out" dir' PK ~\f? node-gyp/lib/log.jsnu['use strict' const procLog = require('proc-log') const { format } = require('util') // helper to emit log messages with a predefined prefix const logLevels = Object.keys(procLog).filter((k) => typeof procLog[k] === 'function') const withPrefix = (prefix) => logLevels.reduce((acc, level) => { acc[level] = (...args) => procLog[level](prefix, ...args) return acc }, {}) // very basic ansi color generator const COLORS = { wrap: (str, colors) => { const codes = colors.filter(c => typeof c === 'number') return `\x1b[${codes.join(';')}m${str}\x1b[0m` }, inverse: 7, fg: { black: 30, red: 31, green: 32, yellow: 33, blue: 34, magenta: 35, cyan: 36, white: 37 }, bg: { black: 40, red: 41, green: 42, yellow: 43, blue: 44, magenta: 45, cyan: 46, white: 47 } } class Logger { #buffer = [] #paused = null #level = null #stream = null // ordered from loudest to quietest #levels = [{ id: 'silly', display: 'sill', style: { inverse: true } }, { id: 'verbose', display: 'verb', style: { fg: 'cyan', bg: 'black' } }, { id: 'info', style: { fg: 'green' } }, { id: 'http', style: { fg: 'green', bg: 'black' } }, { id: 'notice', style: { fg: 'cyan', bg: 'black' } }, { id: 'warn', display: 'WARN', style: { fg: 'black', bg: 'yellow' } }, { id: 'error', display: 'ERR!', style: { fg: 'red', bg: 'black' } }] constructor (stream) { process.on('log', (...args) => this.#onLog(...args)) this.#levels = new Map(this.#levels.map((level, index) => [level.id, { ...level, index }])) this.level = 'info' this.stream = stream procLog.pause() } get stream () { return this.#stream } set stream (stream) { this.#stream = stream } get level () { return this.#levels.get(this.#level) ?? null } set level (level) { this.#level = this.#levels.get(level)?.id ?? null } isVisible (level) { return this.level?.index <= this.#levels.get(level)?.index ?? -1 } #onLog (...args) { const [level] = args if (level === 'pause') { this.#paused = true return } if (level === 'resume') { this.#paused = false this.#buffer.forEach((b) => this.#log(...b)) this.#buffer.length = 0 return } if (this.#paused) { this.#buffer.push(args) return } this.#log(...args) } #color (str, { fg, bg, inverse }) { if (!this.#stream?.isTTY) { return str } return COLORS.wrap(str, [ COLORS.fg[fg], COLORS.bg[bg], inverse && COLORS.inverse ]) } #log (levelId, msgPrefix, ...args) { if (!this.isVisible(levelId) || typeof this.#stream?.write !== 'function') { return } const level = this.#levels.get(levelId) const prefixParts = [ this.#color('gyp', { fg: 'white', bg: 'black' }), this.#color(level.display ?? level.id, level.style) ] if (msgPrefix) { prefixParts.push(this.#color(msgPrefix, { fg: 'magenta' })) } const prefix = prefixParts.join(' ').trim() + ' ' const lines = format(...args).split(/\r?\n/).map(l => prefix + l.trim()) this.#stream.write(lines.join('\n') + '\n') } } // used to suppress logs in tests const NULL_LOGGER = !!process.env.NODE_GYP_NULL_LOGGER module.exports = { logger: new Logger(NULL_LOGGER ? null : process.stderr), stdout: NULL_LOGGER ? () => {} : (...args) => console.log(...args), withPrefix, ...procLog } PK ~\UP**node-gyp/lib/find-python.jsnu['use strict' const log = require('./log') const semver = require('semver') const { execFile } = require('./util') const win = process.platform === 'win32' function getOsUserInfo () { try { return require('os').userInfo().username } catch {} } const systemDrive = process.env.SystemDrive || 'C:' const username = process.env.USERNAME || process.env.USER || getOsUserInfo() const localAppData = process.env.LOCALAPPDATA || `${systemDrive}\\${username}\\AppData\\Local` const foundLocalAppData = process.env.LOCALAPPDATA || username const programFiles = process.env.ProgramW6432 || process.env.ProgramFiles || `${systemDrive}\\Program Files` const programFilesX86 = process.env['ProgramFiles(x86)'] || `${programFiles} (x86)` const winDefaultLocationsArray = [] for (const majorMinor of ['311', '310', '39', '38']) { if (foundLocalAppData) { winDefaultLocationsArray.push( `${localAppData}\\Programs\\Python\\Python${majorMinor}\\python.exe`, `${programFiles}\\Python${majorMinor}\\python.exe`, `${localAppData}\\Programs\\Python\\Python${majorMinor}-32\\python.exe`, `${programFiles}\\Python${majorMinor}-32\\python.exe`, `${programFilesX86}\\Python${majorMinor}-32\\python.exe` ) } else { winDefaultLocationsArray.push( `${programFiles}\\Python${majorMinor}\\python.exe`, `${programFiles}\\Python${majorMinor}-32\\python.exe`, `${programFilesX86}\\Python${majorMinor}-32\\python.exe` ) } } class PythonFinder { static findPython = (...args) => new PythonFinder(...args).findPython() log = log.withPrefix('find Python') argsExecutable = ['-c', 'import sys; sys.stdout.buffer.write(sys.executable.encode(\'utf-8\'));'] argsVersion = ['-c', 'import sys; print("%s.%s.%s" % sys.version_info[:3]);'] semverRange = '>=3.6.0' // These can be overridden for testing: execFile = execFile env = process.env win = win pyLauncher = 'py.exe' winDefaultLocations = winDefaultLocationsArray constructor (configPython) { this.configPython = configPython this.errorLog = [] } // Logs a message at verbose level, but also saves it to be displayed later // at error level if an error occurs. This should help diagnose the problem. addLog (message) { this.log.verbose(message) this.errorLog.push(message) } // Find Python by trying a sequence of possibilities. // Ignore errors, keep trying until Python is found. async findPython () { const SKIP = 0 const FAIL = 1 const toCheck = (() => { if (this.env.NODE_GYP_FORCE_PYTHON) { return [{ before: () => { this.addLog( 'checking Python explicitly set from NODE_GYP_FORCE_PYTHON') this.addLog('- process.env.NODE_GYP_FORCE_PYTHON is ' + `"${this.env.NODE_GYP_FORCE_PYTHON}"`) }, check: () => this.checkCommand(this.env.NODE_GYP_FORCE_PYTHON) }] } const checks = [ { before: () => { if (!this.configPython) { this.addLog( 'Python is not set from command line or npm configuration') return SKIP } this.addLog('checking Python explicitly set from command line or ' + 'npm configuration') this.addLog('- "--python=" or "npm config get python" is ' + `"${this.configPython}"`) }, check: () => this.checkCommand(this.configPython) }, { before: () => { if (!this.env.PYTHON) { this.addLog('Python is not set from environment variable ' + 'PYTHON') return SKIP } this.addLog('checking Python explicitly set from environment ' + 'variable PYTHON') this.addLog(`- process.env.PYTHON is "${this.env.PYTHON}"`) }, check: () => this.checkCommand(this.env.PYTHON) } ] if (this.win) { checks.push({ before: () => { this.addLog( 'checking if the py launcher can be used to find Python 3') }, check: () => this.checkPyLauncher() }) } checks.push(...[ { before: () => { this.addLog('checking if "python3" can be used') }, check: () => this.checkCommand('python3') }, { before: () => { this.addLog('checking if "python" can be used') }, check: () => this.checkCommand('python') } ]) if (this.win) { for (let i = 0; i < this.winDefaultLocations.length; ++i) { const location = this.winDefaultLocations[i] checks.push({ before: () => this.addLog(`checking if Python is ${location}`), check: () => this.checkExecPath(location) }) } } return checks })() for (const check of toCheck) { const before = check.before() if (before === SKIP) { continue } if (before === FAIL) { return this.fail() } try { return await check.check() } catch (err) { this.log.silly('runChecks: err = %j', (err && err.stack) || err) } } return this.fail() } // Check if command is a valid Python to use. // Will exit the Python finder on success. // If on Windows, run in a CMD shell to support BAT/CMD launchers. async checkCommand (command) { let exec = command let args = this.argsExecutable let shell = false if (this.win) { // Arguments have to be manually quoted exec = `"${exec}"` args = args.map(a => `"${a}"`) shell = true } this.log.verbose(`- executing "${command}" to get executable path`) // Possible outcomes: // - Error: not in PATH, not executable or execution fails // - Gibberish: the next command to check version will fail // - Absolute path to executable try { const execPath = await this.run(exec, args, shell) this.addLog(`- executable path is "${execPath}"`) return this.checkExecPath(execPath) } catch (err) { this.addLog(`- "${command}" is not in PATH or produced an error`) throw err } } // Check if the py launcher can find a valid Python to use. // Will exit the Python finder on success. // Distributions of Python on Windows by default install with the "py.exe" // Python launcher which is more likely to exist than the Python executable // being in the $PATH. // Because the Python launcher supports Python 2 and Python 3, we should // explicitly request a Python 3 version. This is done by supplying "-3" as // the first command line argument. Since "py.exe -3" would be an invalid // executable for "execFile", we have to use the launcher to figure out // where the actual "python.exe" executable is located. async checkPyLauncher () { this.log.verbose(`- executing "${this.pyLauncher}" to get Python 3 executable path`) // Possible outcomes: same as checkCommand try { const execPath = await this.run(this.pyLauncher, ['-3', ...this.argsExecutable], false) this.addLog(`- executable path is "${execPath}"`) return this.checkExecPath(execPath) } catch (err) { this.addLog(`- "${this.pyLauncher}" is not in PATH or produced an error`) throw err } } // Check if a Python executable is the correct version to use. // Will exit the Python finder on success. async checkExecPath (execPath) { this.log.verbose(`- executing "${execPath}" to get version`) // Possible outcomes: // - Error: executable can not be run (likely meaning the command wasn't // a Python executable and the previous command produced gibberish) // - Gibberish: somehow the last command produced an executable path, // this will fail when verifying the version // - Version of the Python executable try { const version = await this.run(execPath, this.argsVersion, false) this.addLog(`- version is "${version}"`) const range = new semver.Range(this.semverRange) let valid = false try { valid = range.test(version) } catch (err) { this.log.silly('range.test() threw:\n%s', err.stack) this.addLog(`- "${execPath}" does not have a valid version`) this.addLog('- is it a Python executable?') throw err } if (!valid) { this.addLog(`- version is ${version} - should be ${this.semverRange}`) this.addLog('- THIS VERSION OF PYTHON IS NOT SUPPORTED') throw new Error(`Found unsupported Python version ${version}`) } return this.succeed(execPath, version) } catch (err) { this.addLog(`- "${execPath}" could not be run`) throw err } } // Run an executable or shell command, trimming the output. async run (exec, args, shell) { const env = Object.assign({}, this.env) env.TERM = 'dumb' const opts = { env, shell } this.log.silly('execFile: exec = %j', exec) this.log.silly('execFile: args = %j', args) this.log.silly('execFile: opts = %j', opts) try { const [err, stdout, stderr] = await this.execFile(exec, args, opts) this.log.silly('execFile result: err = %j', (err && err.stack) || err) this.log.silly('execFile result: stdout = %j', stdout) this.log.silly('execFile result: stderr = %j', stderr) return stdout.trim() } catch (err) { this.log.silly('execFile: threw:\n%s', err.stack) throw err } } succeed (execPath, version) { this.log.info(`using Python version ${version} found at "${execPath}"`) return execPath } fail () { const errorLog = this.errorLog.join('\n') const pathExample = this.win ? 'C:\\Path\\To\\python.exe' : '/path/to/pythonexecutable' // For Windows 80 col console, use up to the column before the one marked // with X (total 79 chars including logger prefix, 58 chars usable here): // X const info = [ '**********************************************************', 'You need to install the latest version of Python.', 'Node-gyp should be able to find and use Python. If not,', 'you can try one of the following options:', `- Use the switch --python="${pathExample}"`, ' (accepted by both node-gyp and npm)', '- Set the environment variable PYTHON', '- Set the npm configuration variable python:', ` npm config set python "${pathExample}"`, 'For more information consult the documentation at:', 'https://github.com/nodejs/node-gyp#installation', '**********************************************************' ].join('\n') this.log.error(`\n${errorLog}\n\n${info}\n`) throw new Error('Could not find any Python installation to use') } } module.exports = PythonFinder PK ~\8 NNnode-gyp/LICENSEnu[(The MIT License) Copyright (c) 2012 Nathan Rajlich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\DE..node-gyp/gyp/pylib/gyp/input.pynu[# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import ast import gyp.common import gyp.simple_copy import multiprocessing import os.path import re import shlex import signal import subprocess import sys import threading import traceback from gyp.common import GypError from gyp.common import OrderedSet from packaging.version import Version # A list of types that are treated as linkable. linkable_types = [ "executable", "shared_library", "loadable_module", "mac_kernel_extension", "windows_driver", ] # A list of sections that contain links to other targets. dependency_sections = ["dependencies", "export_dependent_settings"] # base_path_sections is a list of sections defined by GYP that contain # pathnames. The generators can provide more keys, the two lists are merged # into path_sections, but you should call IsPathSection instead of using either # list directly. base_path_sections = [ "destination", "files", "include_dirs", "inputs", "libraries", "outputs", "sources", ] path_sections = set() # These per-process dictionaries are used to cache build file data when loading # in parallel mode. per_process_data = {} per_process_aux_data = {} def IsPathSection(section): # If section ends in one of the '=+?!' characters, it's applied to a section # without the trailing characters. '/' is notably absent from this list, # because there's no way for a regular expression to be treated as a path. while section and section[-1:] in "=+?!": section = section[:-1] if section in path_sections: return True # Sections matching the regexp '_(dir|file|path)s?$' are also # considered PathSections. Using manual string matching since that # is much faster than the regexp and this can be called hundreds of # thousands of times so micro performance matters. if "_" in section: tail = section[-6:] if tail[-1] == "s": tail = tail[:-1] if tail[-5:] in ("_file", "_path"): return True return tail[-4:] == "_dir" return False # base_non_configuration_keys is a list of key names that belong in the target # itself and should not be propagated into its configurations. It is merged # with a list that can come from the generator to # create non_configuration_keys. base_non_configuration_keys = [ # Sections that must exist inside targets and not configurations. "actions", "configurations", "copies", "default_configuration", "dependencies", "dependencies_original", "libraries", "postbuilds", "product_dir", "product_extension", "product_name", "product_prefix", "rules", "run_as", "sources", "standalone_static_library", "suppress_wildcard", "target_name", "toolset", "toolsets", "type", # Sections that can be found inside targets or configurations, but that # should not be propagated from targets into their configurations. "variables", ] non_configuration_keys = [] # Keys that do not belong inside a configuration dictionary. invalid_configuration_keys = [ "actions", "all_dependent_settings", "configurations", "dependencies", "direct_dependent_settings", "libraries", "link_settings", "sources", "standalone_static_library", "target_name", "type", ] # Controls whether or not the generator supports multiple toolsets. multiple_toolsets = False # Paths for converting filelist paths to output paths: { # toplevel, # qualified_output_dir, # } generator_filelist_paths = None def GetIncludedBuildFiles(build_file_path, aux_data, included=None): """Return a list of all build files included into build_file_path. The returned list will contain build_file_path as well as all other files that it included, either directly or indirectly. Note that the list may contain files that were included into a conditional section that evaluated to false and was not merged into build_file_path's dict. aux_data is a dict containing a key for each build file or included build file. Those keys provide access to dicts whose "included" keys contain lists of all other files included by the build file. included should be left at its default None value by external callers. It is used for recursion. The returned list will not contain any duplicate entries. Each build file in the list will be relative to the current directory. """ if included is None: included = [] if build_file_path in included: return included included.append(build_file_path) for included_build_file in aux_data[build_file_path].get("included", []): GetIncludedBuildFiles(included_build_file, aux_data, included) return included def CheckedEval(file_contents): """Return the eval of a gyp file. The gyp file is restricted to dictionaries and lists only, and repeated keys are not allowed. Note that this is slower than eval() is. """ syntax_tree = ast.parse(file_contents) assert isinstance(syntax_tree, ast.Module) c1 = syntax_tree.body assert len(c1) == 1 c2 = c1[0] assert isinstance(c2, ast.Expr) return CheckNode(c2.value, []) def CheckNode(node, keypath): if isinstance(node, ast.Dict): dict = {} for key, value in zip(node.keys, node.values): assert isinstance(key, ast.Str) key = key.s if key in dict: raise GypError( "Key '" + key + "' repeated at level " + repr(len(keypath) + 1) + " with key path '" + ".".join(keypath) + "'" ) kp = list(keypath) # Make a copy of the list for descending this node. kp.append(key) dict[key] = CheckNode(value, kp) return dict elif isinstance(node, ast.List): children = [] for index, child in enumerate(node.elts): kp = list(keypath) # Copy list. kp.append(repr(index)) children.append(CheckNode(child, kp)) return children elif isinstance(node, ast.Str): return node.s else: raise TypeError( "Unknown AST node at key path '" + ".".join(keypath) + "': " + repr(node) ) def LoadOneBuildFile(build_file_path, data, aux_data, includes, is_target, check): if build_file_path in data: return data[build_file_path] if os.path.exists(build_file_path): build_file_contents = open(build_file_path, encoding="utf-8").read() else: raise GypError(f"{build_file_path} not found (cwd: {os.getcwd()})") build_file_data = None try: if check: build_file_data = CheckedEval(build_file_contents) else: build_file_data = eval(build_file_contents, {"__builtins__": {}}, None) except SyntaxError as e: e.filename = build_file_path raise except Exception as e: gyp.common.ExceptionAppend(e, "while reading " + build_file_path) raise if type(build_file_data) is not dict: raise GypError("%s does not evaluate to a dictionary." % build_file_path) data[build_file_path] = build_file_data aux_data[build_file_path] = {} # Scan for includes and merge them in. if "skip_includes" not in build_file_data or not build_file_data["skip_includes"]: try: if is_target: LoadBuildFileIncludesIntoDict( build_file_data, build_file_path, data, aux_data, includes, check ) else: LoadBuildFileIncludesIntoDict( build_file_data, build_file_path, data, aux_data, None, check ) except Exception as e: gyp.common.ExceptionAppend( e, "while reading includes of " + build_file_path ) raise return build_file_data def LoadBuildFileIncludesIntoDict( subdict, subdict_path, data, aux_data, includes, check ): includes_list = [] if includes is not None: includes_list.extend(includes) if "includes" in subdict: for include in subdict["includes"]: # "include" is specified relative to subdict_path, so compute the real # path to include by appending the provided "include" to the directory # in which subdict_path resides. relative_include = os.path.normpath( os.path.join(os.path.dirname(subdict_path), include) ) includes_list.append(relative_include) # Unhook the includes list, it's no longer needed. del subdict["includes"] # Merge in the included files. for include in includes_list: if "included" not in aux_data[subdict_path]: aux_data[subdict_path]["included"] = [] aux_data[subdict_path]["included"].append(include) gyp.DebugOutput(gyp.DEBUG_INCLUDES, "Loading Included File: '%s'", include) MergeDicts( subdict, LoadOneBuildFile(include, data, aux_data, None, False, check), subdict_path, include, ) # Recurse into subdictionaries. for k, v in subdict.items(): if type(v) is dict: LoadBuildFileIncludesIntoDict(v, subdict_path, data, aux_data, None, check) elif type(v) is list: LoadBuildFileIncludesIntoList(v, subdict_path, data, aux_data, check) # This recurses into lists so that it can look for dicts. def LoadBuildFileIncludesIntoList(sublist, sublist_path, data, aux_data, check): for item in sublist: if type(item) is dict: LoadBuildFileIncludesIntoDict( item, sublist_path, data, aux_data, None, check ) elif type(item) is list: LoadBuildFileIncludesIntoList(item, sublist_path, data, aux_data, check) # Processes toolsets in all the targets. This recurses into condition entries # since they can contain toolsets as well. def ProcessToolsetsInDict(data): if "targets" in data: target_list = data["targets"] new_target_list = [] for target in target_list: # If this target already has an explicit 'toolset', and no 'toolsets' # list, don't modify it further. if "toolset" in target and "toolsets" not in target: new_target_list.append(target) continue if multiple_toolsets: toolsets = target.get("toolsets", ["target"]) else: toolsets = ["target"] # Make sure this 'toolsets' definition is only processed once. if "toolsets" in target: del target["toolsets"] if len(toolsets) > 0: # Optimization: only do copies if more than one toolset is specified. for build in toolsets[1:]: new_target = gyp.simple_copy.deepcopy(target) new_target["toolset"] = build new_target_list.append(new_target) target["toolset"] = toolsets[0] new_target_list.append(target) data["targets"] = new_target_list if "conditions" in data: for condition in data["conditions"]: if type(condition) is list: for condition_dict in condition[1:]: if type(condition_dict) is dict: ProcessToolsetsInDict(condition_dict) # TODO(mark): I don't love this name. It just means that it's going to load # a build file that contains targets and is expected to provide a targets dict # that contains the targets... def LoadTargetBuildFile( build_file_path, data, aux_data, variables, includes, depth, check, load_dependencies, ): # If depth is set, predefine the DEPTH variable to be a relative path from # this build file's directory to the directory identified by depth. if depth: # TODO(dglazkov) The backslash/forward-slash replacement at the end is a # temporary measure. This should really be addressed by keeping all paths # in POSIX until actual project generation. d = gyp.common.RelativePath(depth, os.path.dirname(build_file_path)) if d == "": variables["DEPTH"] = "." else: variables["DEPTH"] = d.replace("\\", "/") # The 'target_build_files' key is only set when loading target build files in # the non-parallel code path, where LoadTargetBuildFile is called # recursively. In the parallel code path, we don't need to check whether the # |build_file_path| has already been loaded, because the 'scheduled' set in # ParallelState guarantees that we never load the same |build_file_path| # twice. if "target_build_files" in data: if build_file_path in data["target_build_files"]: # Already loaded. return False data["target_build_files"].add(build_file_path) gyp.DebugOutput( gyp.DEBUG_INCLUDES, "Loading Target Build File '%s'", build_file_path ) build_file_data = LoadOneBuildFile( build_file_path, data, aux_data, includes, True, check ) # Store DEPTH for later use in generators. build_file_data["_DEPTH"] = depth # Set up the included_files key indicating which .gyp files contributed to # this target dict. if "included_files" in build_file_data: raise GypError(build_file_path + " must not contain included_files key") included = GetIncludedBuildFiles(build_file_path, aux_data) build_file_data["included_files"] = [] for included_file in included: # included_file is relative to the current directory, but it needs to # be made relative to build_file_path's directory. included_relative = gyp.common.RelativePath( included_file, os.path.dirname(build_file_path) ) build_file_data["included_files"].append(included_relative) # Do a first round of toolsets expansion so that conditions can be defined # per toolset. ProcessToolsetsInDict(build_file_data) # Apply "pre"/"early" variable expansions and condition evaluations. ProcessVariablesAndConditionsInDict( build_file_data, PHASE_EARLY, variables, build_file_path ) # Since some toolsets might have been defined conditionally, perform # a second round of toolsets expansion now. ProcessToolsetsInDict(build_file_data) # Look at each project's target_defaults dict, and merge settings into # targets. if "target_defaults" in build_file_data: if "targets" not in build_file_data: raise GypError("Unable to find targets in build file %s" % build_file_path) index = 0 while index < len(build_file_data["targets"]): # This procedure needs to give the impression that target_defaults is # used as defaults, and the individual targets inherit from that. # The individual targets need to be merged into the defaults. Make # a deep copy of the defaults for each target, merge the target dict # as found in the input file into that copy, and then hook up the # copy with the target-specific data merged into it as the replacement # target dict. old_target_dict = build_file_data["targets"][index] new_target_dict = gyp.simple_copy.deepcopy( build_file_data["target_defaults"] ) MergeDicts( new_target_dict, old_target_dict, build_file_path, build_file_path ) build_file_data["targets"][index] = new_target_dict index += 1 # No longer needed. del build_file_data["target_defaults"] # Look for dependencies. This means that dependency resolution occurs # after "pre" conditionals and variable expansion, but before "post" - # in other words, you can't put a "dependencies" section inside a "post" # conditional within a target. dependencies = [] if "targets" in build_file_data: for target_dict in build_file_data["targets"]: if "dependencies" not in target_dict: continue for dependency in target_dict["dependencies"]: dependencies.append( gyp.common.ResolveTarget(build_file_path, dependency, None)[0] ) if load_dependencies: for dependency in dependencies: try: LoadTargetBuildFile( dependency, data, aux_data, variables, includes, depth, check, load_dependencies, ) except Exception as e: gyp.common.ExceptionAppend( e, "while loading dependencies of %s" % build_file_path ) raise else: return (build_file_path, dependencies) def CallLoadTargetBuildFile( global_flags, build_file_path, variables, includes, depth, check, generator_input_info, ): """Wrapper around LoadTargetBuildFile for parallel processing. This wrapper is used when LoadTargetBuildFile is executed in a worker process. """ try: signal.signal(signal.SIGINT, signal.SIG_IGN) # Apply globals so that the worker process behaves the same. for key, value in global_flags.items(): globals()[key] = value SetGeneratorGlobals(generator_input_info) result = LoadTargetBuildFile( build_file_path, per_process_data, per_process_aux_data, variables, includes, depth, check, False, ) if not result: return result (build_file_path, dependencies) = result # We can safely pop the build_file_data from per_process_data because it # will never be referenced by this process again, so we don't need to keep # it in the cache. build_file_data = per_process_data.pop(build_file_path) # This gets serialized and sent back to the main process via a pipe. # It's handled in LoadTargetBuildFileCallback. return (build_file_path, build_file_data, dependencies) except GypError as e: sys.stderr.write("gyp: %s\n" % e) return None except Exception as e: print("Exception:", e, file=sys.stderr) print(traceback.format_exc(), file=sys.stderr) return None class ParallelProcessingError(Exception): pass class ParallelState: """Class to keep track of state when processing input files in parallel. If build files are loaded in parallel, use this to keep track of state during farming out and processing parallel jobs. It's stored in a global so that the callback function can have access to it. """ def __init__(self): # The multiprocessing pool. self.pool = None # The condition variable used to protect this object and notify # the main loop when there might be more data to process. self.condition = None # The "data" dict that was passed to LoadTargetBuildFileParallel self.data = None # The number of parallel calls outstanding; decremented when a response # was received. self.pending = 0 # The set of all build files that have been scheduled, so we don't # schedule the same one twice. self.scheduled = set() # A list of dependency build file paths that haven't been scheduled yet. self.dependencies = [] # Flag to indicate if there was an error in a child process. self.error = False def LoadTargetBuildFileCallback(self, result): """Handle the results of running LoadTargetBuildFile in another process. """ self.condition.acquire() if not result: self.error = True self.condition.notify() self.condition.release() return (build_file_path0, build_file_data0, dependencies0) = result self.data[build_file_path0] = build_file_data0 self.data["target_build_files"].add(build_file_path0) for new_dependency in dependencies0: if new_dependency not in self.scheduled: self.scheduled.add(new_dependency) self.dependencies.append(new_dependency) self.pending -= 1 self.condition.notify() self.condition.release() def LoadTargetBuildFilesParallel( build_files, data, variables, includes, depth, check, generator_input_info ): parallel_state = ParallelState() parallel_state.condition = threading.Condition() # Make copies of the build_files argument that we can modify while working. parallel_state.dependencies = list(build_files) parallel_state.scheduled = set(build_files) parallel_state.pending = 0 parallel_state.data = data try: parallel_state.condition.acquire() while parallel_state.dependencies or parallel_state.pending: if parallel_state.error: break if not parallel_state.dependencies: parallel_state.condition.wait() continue dependency = parallel_state.dependencies.pop() parallel_state.pending += 1 global_flags = { "path_sections": globals()["path_sections"], "non_configuration_keys": globals()["non_configuration_keys"], "multiple_toolsets": globals()["multiple_toolsets"], } if not parallel_state.pool: parallel_state.pool = multiprocessing.Pool(multiprocessing.cpu_count()) parallel_state.pool.apply_async( CallLoadTargetBuildFile, args=( global_flags, dependency, variables, includes, depth, check, generator_input_info, ), callback=parallel_state.LoadTargetBuildFileCallback, ) except KeyboardInterrupt as e: parallel_state.pool.terminate() raise e parallel_state.condition.release() parallel_state.pool.close() parallel_state.pool.join() parallel_state.pool = None if parallel_state.error: sys.exit(1) # Look for the bracket that matches the first bracket seen in a # string, and return the start and end as a tuple. For example, if # the input is something like "<(foo <(bar)) blah", then it would # return (1, 13), indicating the entire string except for the leading # "<" and trailing " blah". LBRACKETS = set("{[(") BRACKETS = {"}": "{", "]": "[", ")": "("} def FindEnclosingBracketGroup(input_str): stack = [] start = -1 for index, char in enumerate(input_str): if char in LBRACKETS: stack.append(char) if start == -1: start = index elif char in BRACKETS: if not stack: return (-1, -1) if stack.pop() != BRACKETS[char]: return (-1, -1) if not stack: return (start, index + 1) return (-1, -1) def IsStrCanonicalInt(string): """Returns True if |string| is in its canonical integer form. The canonical form is such that str(int(string)) == string. """ if type(string) is str: # This function is called a lot so for maximum performance, avoid # involving regexps which would otherwise make the code much # shorter. Regexps would need twice the time of this function. if string: if string == "0": return True if string[0] == "-": string = string[1:] if not string: return False if "1" <= string[0] <= "9": return string.isdigit() return False # This matches things like "<(asdf)", "(?P<(?:(?:!?@?)|\|)?)" r"(?P[-a-zA-Z0-9_.]+)?" r"\((?P\s*\[?)" r"(?P.*?)(\]?)\))" ) # This matches the same as early_variable_re, but with '>' instead of '<'. late_variable_re = re.compile( r"(?P(?P>(?:(?:!?@?)|\|)?)" r"(?P[-a-zA-Z0-9_.]+)?" r"\((?P\s*\[?)" r"(?P.*?)(\]?)\))" ) # This matches the same as early_variable_re, but with '^' instead of '<'. latelate_variable_re = re.compile( r"(?P(?P[\^](?:(?:!?@?)|\|)?)" r"(?P[-a-zA-Z0-9_.]+)?" r"\((?P\s*\[?)" r"(?P.*?)(\]?)\))" ) # Global cache of results from running commands so they don't have to be run # more then once. cached_command_results = {} def FixupPlatformCommand(cmd): if sys.platform == "win32": if type(cmd) is list: cmd = [re.sub("^cat ", "type ", cmd[0])] + cmd[1:] else: cmd = re.sub("^cat ", "type ", cmd) return cmd PHASE_EARLY = 0 PHASE_LATE = 1 PHASE_LATELATE = 2 def ExpandVariables(input, phase, variables, build_file): # Look for the pattern that gets expanded into variables if phase == PHASE_EARLY: variable_re = early_variable_re expansion_symbol = "<" elif phase == PHASE_LATE: variable_re = late_variable_re expansion_symbol = ">" elif phase == PHASE_LATELATE: variable_re = latelate_variable_re expansion_symbol = "^" else: assert False input_str = str(input) if IsStrCanonicalInt(input_str): return int(input_str) # Do a quick scan to determine if an expensive regex search is warranted. if expansion_symbol not in input_str: return input_str # Get the entire list of matches as a list of MatchObject instances. # (using findall here would return strings instead of MatchObjects). matches = list(variable_re.finditer(input_str)) if not matches: return input_str output = input_str # Reverse the list of matches so that replacements are done right-to-left. # That ensures that earlier replacements won't mess up the string in a # way that causes later calls to find the earlier substituted text instead # of what's intended for replacement. matches.reverse() for match_group in matches: match = match_group.groupdict() gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Matches: %r", match) # match['replace'] is the substring to look for, match['type'] # is the character code for the replacement type (< > ! <| >| <@ # >@ !@), match['is_array'] contains a '[' for command # arrays, and match['content'] is the name of the variable (< >) # or command to run (!). match['command_string'] is an optional # command string. Currently, only 'pymod_do_main' is supported. # run_command is true if a ! variant is used. run_command = "!" in match["type"] command_string = match["command_string"] # file_list is true if a | variant is used. file_list = "|" in match["type"] # Capture these now so we can adjust them later. replace_start = match_group.start("replace") replace_end = match_group.end("replace") # Find the ending paren, and re-evaluate the contained string. (c_start, c_end) = FindEnclosingBracketGroup(input_str[replace_start:]) # Adjust the replacement range to match the entire command # found by FindEnclosingBracketGroup (since the variable_re # probably doesn't match the entire command if it contained # nested variables). replace_end = replace_start + c_end # Find the "real" replacement, matching the appropriate closing # paren, and adjust the replacement start and end. replacement = input_str[replace_start:replace_end] # Figure out what the contents of the variable parens are. contents_start = replace_start + c_start + 1 contents_end = replace_end - 1 contents = input_str[contents_start:contents_end] # Do filter substitution now for <|(). # Admittedly, this is different than the evaluation order in other # contexts. However, since filtration has no chance to run on <|(), # this seems like the only obvious way to give them access to filters. if file_list: processed_variables = gyp.simple_copy.deepcopy(variables) ProcessListFiltersInDict(contents, processed_variables) # Recurse to expand variables in the contents contents = ExpandVariables(contents, phase, processed_variables, build_file) else: # Recurse to expand variables in the contents contents = ExpandVariables(contents, phase, variables, build_file) # Strip off leading/trailing whitespace so that variable matches are # simpler below (and because they are rarely needed). contents = contents.strip() # expand_to_list is true if an @ variant is used. In that case, # the expansion should result in a list. Note that the caller # is to be expecting a list in return, and not all callers do # because not all are working in list context. Also, for list # expansions, there can be no other text besides the variable # expansion in the input string. expand_to_list = "@" in match["type"] and input_str == replacement if run_command or file_list: # Find the build file's directory, so commands can be run or file lists # generated relative to it. build_file_dir = os.path.dirname(build_file) if build_file_dir == "" and not file_list: # If build_file is just a leaf filename indicating a file in the # current directory, build_file_dir might be an empty string. Set # it to None to signal to subprocess.Popen that it should run the # command in the current directory. build_file_dir = None # Support <|(listfile.txt ...) which generates a file # containing items from a gyp list, generated at gyp time. # This works around actions/rules which have more inputs than will # fit on the command line. if file_list: contents_list = contents if type(contents) is list else contents.split(" ") replacement = contents_list[0] if os.path.isabs(replacement): raise GypError('| cannot handle absolute paths, got "%s"' % replacement) if not generator_filelist_paths: path = os.path.join(build_file_dir, replacement) else: if os.path.isabs(build_file_dir): toplevel = generator_filelist_paths["toplevel"] rel_build_file_dir = gyp.common.RelativePath( build_file_dir, toplevel ) else: rel_build_file_dir = build_file_dir qualified_out_dir = generator_filelist_paths["qualified_out_dir"] path = os.path.join(qualified_out_dir, rel_build_file_dir, replacement) gyp.common.EnsureDirExists(path) replacement = gyp.common.RelativePath(path, build_file_dir) f = gyp.common.WriteOnDiff(path) for i in contents_list[1:]: f.write("%s\n" % i) f.close() elif run_command: use_shell = True if match["is_array"]: contents = eval(contents) use_shell = False # Check for a cached value to avoid executing commands, or generating # file lists more than once. The cache key contains the command to be # run as well as the directory to run it from, to account for commands # that depend on their current directory. # TODO(http://code.google.com/p/gyp/issues/detail?id=111): In theory, # someone could author a set of GYP files where each time the command # is invoked it produces different output by design. When the need # arises, the syntax should be extended to support no caching off a # command's output so it is run every time. cache_key = (str(contents), build_file_dir) cached_value = cached_command_results.get(cache_key, None) if cached_value is None: gyp.DebugOutput( gyp.DEBUG_VARIABLES, "Executing command '%s' in directory '%s'", contents, build_file_dir, ) replacement = "" if command_string == "pymod_do_main": # 0: raise GypError( "Call to '%s' returned exit status %d while in %s." % (contents, result.returncode, build_file) ) replacement = result.stdout.decode("utf-8").rstrip() cached_command_results[cache_key] = replacement else: gyp.DebugOutput( gyp.DEBUG_VARIABLES, "Had cache value for command '%s' in directory '%s'", contents, build_file_dir, ) replacement = cached_value else: if contents not in variables: if contents[-1] in ["!", "/"]: # In order to allow cross-compiles (nacl) to happen more naturally, # we will allow references to >(sources/) etc. to resolve to # and empty list if undefined. This allows actions to: # 'action!': [ # '>@(_sources!)', # ], # 'action/': [ # '>@(_sources/)', # ], replacement = [] else: raise GypError( "Undefined variable " + contents + " in " + build_file ) else: replacement = variables[contents] if isinstance(replacement, bytes) and not isinstance(replacement, str): replacement = replacement.decode("utf-8") # done on Python 3 only if type(replacement) is list: for item in replacement: if isinstance(item, bytes) and not isinstance(item, str): item = item.decode("utf-8") # done on Python 3 only if not contents[-1] == "/" and type(item) not in (str, int): raise GypError( "Variable " + contents + " must expand to a string or list of strings; " + "list contains a " + item.__class__.__name__ ) # Run through the list and handle variable expansions in it. Since # the list is guaranteed not to contain dicts, this won't do anything # with conditions sections. ProcessVariablesAndConditionsInList( replacement, phase, variables, build_file ) elif type(replacement) not in (str, int): raise GypError( "Variable " + contents + " must expand to a string or list of strings; " + "found a " + replacement.__class__.__name__ ) if expand_to_list: # Expanding in list context. It's guaranteed that there's only one # replacement to do in |input_str| and that it's this replacement. See # above. if type(replacement) is list: # If it's already a list, make a copy. output = replacement[:] else: # Split it the same way sh would split arguments. output = shlex.split(str(replacement)) else: # Expanding in string context. encoded_replacement = "" if type(replacement) is list: # When expanding a list into string context, turn the list items # into a string in a way that will work with a subprocess call. # # TODO(mark): This isn't completely correct. This should # call a generator-provided function that observes the # proper list-to-argument quoting rules on a specific # platform instead of just calling the POSIX encoding # routine. encoded_replacement = gyp.common.EncodePOSIXShellList(replacement) else: encoded_replacement = replacement output = ( output[:replace_start] + str(encoded_replacement) + output[replace_end:] ) # Prepare for the next match iteration. input_str = output if output == input: gyp.DebugOutput( gyp.DEBUG_VARIABLES, "Found only identity matches on %r, avoiding infinite " "recursion.", output, ) else: # Look for more matches now that we've replaced some, to deal with # expanding local variables (variables defined in the same # variables block as this one). gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Found output %r, recursing.", output) if type(output) is list: if output and type(output[0]) is list: # Leave output alone if it's a list of lists. # We don't want such lists to be stringified. pass else: new_output = [] for item in output: new_output.append( ExpandVariables(item, phase, variables, build_file) ) output = new_output else: output = ExpandVariables(output, phase, variables, build_file) # Convert all strings that are canonically-represented integers into integers. if type(output) is list: for index, outstr in enumerate(output): if IsStrCanonicalInt(outstr): output[index] = int(outstr) elif IsStrCanonicalInt(output): output = int(output) return output # The same condition is often evaluated over and over again so it # makes sense to cache as much as possible between evaluations. cached_conditions_asts = {} def EvalCondition(condition, conditions_key, phase, variables, build_file): """Returns the dict that should be used or None if the result was that nothing should be used.""" if type(condition) is not list: raise GypError(conditions_key + " must be a list") if len(condition) < 2: # It's possible that condition[0] won't work in which case this # attempt will raise its own IndexError. That's probably fine. raise GypError( conditions_key + " " + condition[0] + " must be at least length 2, not " + str(len(condition)) ) i = 0 result = None while i < len(condition): cond_expr = condition[i] true_dict = condition[i + 1] if type(true_dict) is not dict: raise GypError( f"{conditions_key} {cond_expr} must be followed by a dictionary, not " f"{type(true_dict)}" ) if len(condition) > i + 2 and type(condition[i + 2]) is dict: false_dict = condition[i + 2] i = i + 3 if i != len(condition): raise GypError( f"{conditions_key} {cond_expr} has {len(condition) - i} " "unexpected trailing items" ) else: false_dict = None i = i + 2 if result is None: result = EvalSingleCondition( cond_expr, true_dict, false_dict, phase, variables, build_file ) return result def EvalSingleCondition(cond_expr, true_dict, false_dict, phase, variables, build_file): """Returns true_dict if cond_expr evaluates to true, and false_dict otherwise.""" # Do expansions on the condition itself. Since the condition can naturally # contain variable references without needing to resort to GYP expansion # syntax, this is of dubious value for variables, but someone might want to # use a command expansion directly inside a condition. cond_expr_expanded = ExpandVariables(cond_expr, phase, variables, build_file) if type(cond_expr_expanded) not in (str, int): raise ValueError( "Variable expansion in this context permits str and int " + "only, found " + cond_expr_expanded.__class__.__name__ ) try: if cond_expr_expanded in cached_conditions_asts: ast_code = cached_conditions_asts[cond_expr_expanded] else: ast_code = compile(cond_expr_expanded, "", "eval") cached_conditions_asts[cond_expr_expanded] = ast_code env = {"__builtins__": {}, "v": Version} if eval(ast_code, env, variables): return true_dict return false_dict except SyntaxError as e: syntax_error = SyntaxError( "%s while evaluating condition '%s' in %s " "at character %d." % (str(e.args[0]), e.text, build_file, e.offset), e.filename, e.lineno, e.offset, e.text, ) raise syntax_error except NameError as e: gyp.common.ExceptionAppend( e, f"while evaluating condition '{cond_expr_expanded}' in {build_file}", ) raise GypError(e) def ProcessConditionsInDict(the_dict, phase, variables, build_file): # Process a 'conditions' or 'target_conditions' section in the_dict, # depending on phase. # early -> conditions # late -> target_conditions # latelate -> no conditions # # Each item in a conditions list consists of cond_expr, a string expression # evaluated as the condition, and true_dict, a dict that will be merged into # the_dict if cond_expr evaluates to true. Optionally, a third item, # false_dict, may be present. false_dict is merged into the_dict if # cond_expr evaluates to false. # # Any dict merged into the_dict will be recursively processed for nested # conditionals and other expansions, also according to phase, immediately # prior to being merged. if phase == PHASE_EARLY: conditions_key = "conditions" elif phase == PHASE_LATE: conditions_key = "target_conditions" elif phase == PHASE_LATELATE: return else: assert False if conditions_key not in the_dict: return conditions_list = the_dict[conditions_key] # Unhook the conditions list, it's no longer needed. del the_dict[conditions_key] for condition in conditions_list: merge_dict = EvalCondition( condition, conditions_key, phase, variables, build_file ) if merge_dict is not None: # Expand variables and nested conditinals in the merge_dict before # merging it. ProcessVariablesAndConditionsInDict( merge_dict, phase, variables, build_file ) MergeDicts(the_dict, merge_dict, build_file, build_file) def LoadAutomaticVariablesFromDict(variables, the_dict): # Any keys with plain string values in the_dict become automatic variables. # The variable name is the key name with a "_" character prepended. for key, value in the_dict.items(): if type(value) in (str, int, list): variables["_" + key] = value def LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key): # Any keys in the_dict's "variables" dict, if it has one, becomes a # variable. The variable name is the key name in the "variables" dict. # Variables that end with the % character are set only if they are unset in # the variables dict. the_dict_key is the name of the key that accesses # the_dict in the_dict's parent dict. If the_dict's parent is not a dict # (it could be a list or it could be parentless because it is a root dict), # the_dict_key will be None. for key, value in the_dict.get("variables", {}).items(): if type(value) not in (str, int, list): continue if key.endswith("%"): variable_name = key[:-1] if variable_name in variables: # If the variable is already set, don't set it. continue if the_dict_key == "variables" and variable_name in the_dict: # If the variable is set without a % in the_dict, and the_dict is a # variables dict (making |variables| a variables sub-dict of a # variables dict), use the_dict's definition. value = the_dict[variable_name] else: variable_name = key variables[variable_name] = value def ProcessVariablesAndConditionsInDict( the_dict, phase, variables_in, build_file, the_dict_key=None ): """Handle all variable and command expansion and conditional evaluation. This function is the public entry point for all variable expansions and conditional evaluations. The variables_in dictionary will not be modified by this function. """ # Make a copy of the variables_in dict that can be modified during the # loading of automatics and the loading of the variables dict. variables = variables_in.copy() LoadAutomaticVariablesFromDict(variables, the_dict) if "variables" in the_dict: # Make sure all the local variables are added to the variables # list before we process them so that you can reference one # variable from another. They will be fully expanded by recursion # in ExpandVariables. for key, value in the_dict["variables"].items(): variables[key] = value # Handle the associated variables dict first, so that any variable # references within can be resolved prior to using them as variables. # Pass a copy of the variables dict to avoid having it be tainted. # Otherwise, it would have extra automatics added for everything that # should just be an ordinary variable in this scope. ProcessVariablesAndConditionsInDict( the_dict["variables"], phase, variables, build_file, "variables" ) LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key) for key, value in the_dict.items(): # Skip "variables", which was already processed if present. if key != "variables" and type(value) is str: expanded = ExpandVariables(value, phase, variables, build_file) if type(expanded) not in (str, int): raise ValueError( "Variable expansion in this context permits str and int " + "only, found " + expanded.__class__.__name__ + " for " + key ) the_dict[key] = expanded # Variable expansion may have resulted in changes to automatics. Reload. # TODO(mark): Optimization: only reload if no changes were made. variables = variables_in.copy() LoadAutomaticVariablesFromDict(variables, the_dict) LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key) # Process conditions in this dict. This is done after variable expansion # so that conditions may take advantage of expanded variables. For example, # if the_dict contains: # {'type': '<(library_type)', # 'conditions': [['_type=="static_library"', { ... }]]}, # _type, as used in the condition, will only be set to the value of # library_type if variable expansion is performed before condition # processing. However, condition processing should occur prior to recursion # so that variables (both automatic and "variables" dict type) may be # adjusted by conditions sections, merged into the_dict, and have the # intended impact on contained dicts. # # This arrangement means that a "conditions" section containing a "variables" # section will only have those variables effective in subdicts, not in # the_dict. The workaround is to put a "conditions" section within a # "variables" section. For example: # {'conditions': [['os=="mac"', {'variables': {'define': 'IS_MAC'}}]], # 'defines': ['<(define)'], # 'my_subdict': {'defines': ['<(define)']}}, # will not result in "IS_MAC" being appended to the "defines" list in the # current scope but would result in it being appended to the "defines" list # within "my_subdict". By comparison: # {'variables': {'conditions': [['os=="mac"', {'define': 'IS_MAC'}]]}, # 'defines': ['<(define)'], # 'my_subdict': {'defines': ['<(define)']}}, # will append "IS_MAC" to both "defines" lists. # Evaluate conditions sections, allowing variable expansions within them # as well as nested conditionals. This will process a 'conditions' or # 'target_conditions' section, perform appropriate merging and recursive # conditional and variable processing, and then remove the conditions section # from the_dict if it is present. ProcessConditionsInDict(the_dict, phase, variables, build_file) # Conditional processing may have resulted in changes to automatics or the # variables dict. Reload. variables = variables_in.copy() LoadAutomaticVariablesFromDict(variables, the_dict) LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key) # Recurse into child dicts, or process child lists which may result in # further recursion into descendant dicts. for key, value in the_dict.items(): # Skip "variables" and string values, which were already processed if # present. if key == "variables" or type(value) is str: continue if type(value) is dict: # Pass a copy of the variables dict so that subdicts can't influence # parents. ProcessVariablesAndConditionsInDict( value, phase, variables, build_file, key ) elif type(value) is list: # The list itself can't influence the variables dict, and # ProcessVariablesAndConditionsInList will make copies of the variables # dict if it needs to pass it to something that can influence it. No # copy is necessary here. ProcessVariablesAndConditionsInList(value, phase, variables, build_file) elif type(value) is not int: raise TypeError("Unknown type " + value.__class__.__name__ + " for " + key) def ProcessVariablesAndConditionsInList(the_list, phase, variables, build_file): # Iterate using an index so that new values can be assigned into the_list. index = 0 while index < len(the_list): item = the_list[index] if type(item) is dict: # Make a copy of the variables dict so that it won't influence anything # outside of its own scope. ProcessVariablesAndConditionsInDict(item, phase, variables, build_file) elif type(item) is list: ProcessVariablesAndConditionsInList(item, phase, variables, build_file) elif type(item) is str: expanded = ExpandVariables(item, phase, variables, build_file) if type(expanded) in (str, int): the_list[index] = expanded elif type(expanded) is list: the_list[index : index + 1] = expanded index += len(expanded) # index now identifies the next item to examine. Continue right now # without falling into the index increment below. continue else: raise ValueError( "Variable expansion in this context permits strings and " + "lists only, found " + expanded.__class__.__name__ + " at " + index ) elif type(item) is not int: raise TypeError( "Unknown type " + item.__class__.__name__ + " at index " + index ) index = index + 1 def BuildTargetsDict(data): """Builds a dict mapping fully-qualified target names to their target dicts. |data| is a dict mapping loaded build files by pathname relative to the current directory. Values in |data| are build file contents. For each |data| value with a "targets" key, the value of the "targets" key is taken as a list containing target dicts. Each target's fully-qualified name is constructed from the pathname of the build file (|data| key) and its "target_name" property. These fully-qualified names are used as the keys in the returned dict. These keys provide access to the target dicts, the dicts in the "targets" lists. """ targets = {} for build_file in data["target_build_files"]: for target in data[build_file].get("targets", []): target_name = gyp.common.QualifiedTarget( build_file, target["target_name"], target["toolset"] ) if target_name in targets: raise GypError("Duplicate target definitions for " + target_name) targets[target_name] = target return targets def QualifyDependencies(targets): """Make dependency links fully-qualified relative to the current directory. |targets| is a dict mapping fully-qualified target names to their target dicts. For each target in this dict, keys known to contain dependency links are examined, and any dependencies referenced will be rewritten so that they are fully-qualified and relative to the current directory. All rewritten dependencies are suitable for use as keys to |targets| or a similar dict. """ all_dependency_sections = [ dep + op for dep in dependency_sections for op in ("", "!", "/") ] for target, target_dict in targets.items(): target_build_file = gyp.common.BuildFile(target) toolset = target_dict["toolset"] for dependency_key in all_dependency_sections: dependencies = target_dict.get(dependency_key, []) for index, dep in enumerate(dependencies): dep_file, dep_target, dep_toolset = gyp.common.ResolveTarget( target_build_file, dep, toolset ) if not multiple_toolsets: # Ignore toolset specification in the dependency if it is specified. dep_toolset = toolset dependency = gyp.common.QualifiedTarget( dep_file, dep_target, dep_toolset ) dependencies[index] = dependency # Make sure anything appearing in a list other than "dependencies" also # appears in the "dependencies" list. if ( dependency_key != "dependencies" and dependency not in target_dict["dependencies"] ): raise GypError( "Found " + dependency + " in " + dependency_key + " of " + target + ", but not in dependencies" ) def ExpandWildcardDependencies(targets, data): """Expands dependencies specified as build_file:*. For each target in |targets|, examines sections containing links to other targets. If any such section contains a link of the form build_file:*, it is taken as a wildcard link, and is expanded to list each target in build_file. The |data| dict provides access to build file dicts. Any target that does not wish to be included by wildcard can provide an optional "suppress_wildcard" key in its target dict. When present and true, a wildcard dependency link will not include such targets. All dependency names, including the keys to |targets| and the values in each dependency list, must be qualified when this function is called. """ for target, target_dict in targets.items(): target_build_file = gyp.common.BuildFile(target) for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) # Loop this way instead of "for dependency in" or "for index in range" # because the dependencies list will be modified within the loop body. index = 0 while index < len(dependencies): ( dependency_build_file, dependency_target, dependency_toolset, ) = gyp.common.ParseQualifiedTarget(dependencies[index]) if dependency_target != "*" and dependency_toolset != "*": # Not a wildcard. Keep it moving. index = index + 1 continue if dependency_build_file == target_build_file: # It's an error for a target to depend on all other targets in # the same file, because a target cannot depend on itself. raise GypError( "Found wildcard in " + dependency_key + " of " + target + " referring to same build file" ) # Take the wildcard out and adjust the index so that the next # dependency in the list will be processed the next time through the # loop. del dependencies[index] index = index - 1 # Loop through the targets in the other build file, adding them to # this target's list of dependencies in place of the removed # wildcard. dependency_target_dicts = data[dependency_build_file]["targets"] for dependency_target_dict in dependency_target_dicts: if int(dependency_target_dict.get("suppress_wildcard", False)): continue dependency_target_name = dependency_target_dict["target_name"] if ( dependency_target not in {"*", dependency_target_name} ): continue dependency_target_toolset = dependency_target_dict["toolset"] if ( dependency_toolset not in {"*", dependency_target_toolset} ): continue dependency = gyp.common.QualifiedTarget( dependency_build_file, dependency_target_name, dependency_target_toolset, ) index = index + 1 dependencies.insert(index, dependency) index = index + 1 def Unify(items): """Removes duplicate elements from items, keeping the first element.""" seen = {} return [seen.setdefault(e, e) for e in items if e not in seen] def RemoveDuplicateDependencies(targets): """Makes sure every dependency appears only once in all targets's dependency lists.""" for target_name, target_dict in targets.items(): for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) if dependencies: target_dict[dependency_key] = Unify(dependencies) def Filter(items, item): """Removes item from items.""" res = {} return [res.setdefault(e, e) for e in items if e != item] def RemoveSelfDependencies(targets): """Remove self dependencies from targets that have the prune_self_dependency variable set.""" for target_name, target_dict in targets.items(): for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) if dependencies: for t in dependencies: if t == target_name and ( targets[t] .get("variables", {}) .get("prune_self_dependency", 0) ): target_dict[dependency_key] = Filter( dependencies, target_name ) def RemoveLinkDependenciesFromNoneTargets(targets): """Remove dependencies having the 'link_dependency' attribute from the 'none' targets.""" for target_name, target_dict in targets.items(): for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) if dependencies: for t in dependencies: if target_dict.get("type", None) == "none": if targets[t].get("variables", {}).get("link_dependency", 0): target_dict[dependency_key] = Filter( target_dict[dependency_key], t ) class DependencyGraphNode: """ Attributes: ref: A reference to an object that this DependencyGraphNode represents. dependencies: List of DependencyGraphNodes on which this one depends. dependents: List of DependencyGraphNodes that depend on this one. """ class CircularException(GypError): pass def __init__(self, ref): self.ref = ref self.dependencies = [] self.dependents = [] def __repr__(self): return "" % self.ref def FlattenToList(self): # flat_list is the sorted list of dependencies - actually, the list items # are the "ref" attributes of DependencyGraphNodes. Every target will # appear in flat_list after all of its dependencies, and before all of its # dependents. flat_list = OrderedSet() def ExtractNodeRef(node): """Extracts the object that the node represents from the given node.""" return node.ref # in_degree_zeros is the list of DependencyGraphNodes that have no # dependencies not in flat_list. Initially, it is a copy of the children # of this node, because when the graph was built, nodes with no # dependencies were made implicit dependents of the root node. in_degree_zeros = sorted(self.dependents[:], key=ExtractNodeRef) while in_degree_zeros: # Nodes in in_degree_zeros have no dependencies not in flat_list, so they # can be appended to flat_list. Take these nodes out of in_degree_zeros # as work progresses, so that the next node to process from the list can # always be accessed at a consistent position. node = in_degree_zeros.pop() flat_list.add(node.ref) # Look at dependents of the node just added to flat_list. Some of them # may now belong in in_degree_zeros. for node_dependent in sorted(node.dependents, key=ExtractNodeRef): is_in_degree_zero = True # TODO: We want to check through the # node_dependent.dependencies list but if it's long and we # always start at the beginning, then we get O(n^2) behaviour. for node_dependent_dependency in sorted( node_dependent.dependencies, key=ExtractNodeRef ): if node_dependent_dependency.ref not in flat_list: # The dependent one or more dependencies not in flat_list. # There will be more chances to add it to flat_list # when examining it again as a dependent of those other # dependencies, provided that there are no cycles. is_in_degree_zero = False break if is_in_degree_zero: # All of the dependent's dependencies are already in flat_list. Add # it to in_degree_zeros where it will be processed in a future # iteration of the outer loop. in_degree_zeros += [node_dependent] return list(flat_list) def FindCycles(self): """ Returns a list of cycles in the graph, where each cycle is its own list. """ results = [] visited = set() def Visit(node, path): for child in node.dependents: if child in path: results.append([child] + path[: path.index(child) + 1]) elif child not in visited: visited.add(child) Visit(child, [child] + path) visited.add(self) Visit(self, [self]) return results def DirectDependencies(self, dependencies=None): """Returns a list of just direct dependencies.""" if dependencies is None: dependencies = [] for dependency in self.dependencies: # Check for None, corresponding to the root node. if dependency.ref and dependency.ref not in dependencies: dependencies.append(dependency.ref) return dependencies def _AddImportedDependencies(self, targets, dependencies=None): """Given a list of direct dependencies, adds indirect dependencies that other dependencies have declared to export their settings. This method does not operate on self. Rather, it operates on the list of dependencies in the |dependencies| argument. For each dependency in that list, if any declares that it exports the settings of one of its own dependencies, those dependencies whose settings are "passed through" are added to the list. As new items are added to the list, they too will be processed, so it is possible to import settings through multiple levels of dependencies. This method is not terribly useful on its own, it depends on being "primed" with a list of direct dependencies such as one provided by DirectDependencies. DirectAndImportedDependencies is intended to be the public entry point. """ if dependencies is None: dependencies = [] index = 0 while index < len(dependencies): dependency = dependencies[index] dependency_dict = targets[dependency] # Add any dependencies whose settings should be imported to the list # if not already present. Newly-added items will be checked for # their own imports when the list iteration reaches them. # Rather than simply appending new items, insert them after the # dependency that exported them. This is done to more closely match # the depth-first method used by DeepDependencies. add_index = 1 for imported_dependency in dependency_dict.get( "export_dependent_settings", [] ): if imported_dependency not in dependencies: dependencies.insert(index + add_index, imported_dependency) add_index = add_index + 1 index = index + 1 return dependencies def DirectAndImportedDependencies(self, targets, dependencies=None): """Returns a list of a target's direct dependencies and all indirect dependencies that a dependency has advertised settings should be exported through the dependency for. """ dependencies = self.DirectDependencies(dependencies) return self._AddImportedDependencies(targets, dependencies) def DeepDependencies(self, dependencies=None): """Returns an OrderedSet of all of a target's dependencies, recursively.""" if dependencies is None: # Using a list to get ordered output and a set to do fast "is it # already added" checks. dependencies = OrderedSet() for dependency in self.dependencies: # Check for None, corresponding to the root node. if dependency.ref is None: continue if dependency.ref not in dependencies: dependency.DeepDependencies(dependencies) dependencies.add(dependency.ref) return dependencies def _LinkDependenciesInternal( self, targets, include_shared_libraries, dependencies=None, initial=True ): """Returns an OrderedSet of dependency targets that are linked into this target. This function has a split personality, depending on the setting of |initial|. Outside callers should always leave |initial| at its default setting. When adding a target to the list of dependencies, this function will recurse into itself with |initial| set to False, to collect dependencies that are linked into the linkable target for which the list is being built. If |include_shared_libraries| is False, the resulting dependencies will not include shared_library targets that are linked into this target. """ if dependencies is None: # Using a list to get ordered output and a set to do fast "is it # already added" checks. dependencies = OrderedSet() # Check for None, corresponding to the root node. if self.ref is None: return dependencies # It's kind of sucky that |targets| has to be passed into this function, # but that's presently the easiest way to access the target dicts so that # this function can find target types. if "target_name" not in targets[self.ref]: raise GypError("Missing 'target_name' field in target.") if "type" not in targets[self.ref]: raise GypError( "Missing 'type' field in target %s" % targets[self.ref]["target_name"] ) target_type = targets[self.ref]["type"] is_linkable = target_type in linkable_types if initial and not is_linkable: # If this is the first target being examined and it's not linkable, # return an empty list of link dependencies, because the link # dependencies are intended to apply to the target itself (initial is # True) and this target won't be linked. return dependencies # Don't traverse 'none' targets if explicitly excluded. if target_type == "none" and not targets[self.ref].get( "dependencies_traverse", True ): dependencies.add(self.ref) return dependencies # Executables, mac kernel extensions, windows drivers and loadable modules # are already fully and finally linked. Nothing else can be a link # dependency of them, there can only be dependencies in the sense that a # dependent target might run an executable or load the loadable_module. if not initial and target_type in ( "executable", "loadable_module", "mac_kernel_extension", "windows_driver", ): return dependencies # Shared libraries are already fully linked. They should only be included # in |dependencies| when adjusting static library dependencies (in order to # link against the shared_library's import lib), but should not be included # in |dependencies| when propagating link_settings. # The |include_shared_libraries| flag controls which of these two cases we # are handling. if ( not initial and target_type == "shared_library" and not include_shared_libraries ): return dependencies # The target is linkable, add it to the list of link dependencies. if self.ref not in dependencies: dependencies.add(self.ref) if initial or not is_linkable: # If this is a subsequent target and it's linkable, don't look any # further for linkable dependencies, as they'll already be linked into # this target linkable. Always look at dependencies of the initial # target, and always look at dependencies of non-linkables. for dependency in self.dependencies: dependency._LinkDependenciesInternal( targets, include_shared_libraries, dependencies, False ) return dependencies def DependenciesForLinkSettings(self, targets): """ Returns a list of dependency targets whose link_settings should be merged into this target. """ # TODO(sbaig) Currently, chrome depends on the bug that shared libraries' # link_settings are propagated. So for now, we will allow it, unless the # 'allow_sharedlib_linksettings_propagation' flag is explicitly set to # False. Once chrome is fixed, we can remove this flag. include_shared_libraries = targets[self.ref].get( "allow_sharedlib_linksettings_propagation", True ) return self._LinkDependenciesInternal(targets, include_shared_libraries) def DependenciesToLinkAgainst(self, targets): """ Returns a list of dependency targets that are linked into this target. """ return self._LinkDependenciesInternal(targets, True) def BuildDependencyList(targets): # Create a DependencyGraphNode for each target. Put it into a dict for easy # access. dependency_nodes = {} for target, spec in targets.items(): if target not in dependency_nodes: dependency_nodes[target] = DependencyGraphNode(target) # Set up the dependency links. Targets that have no dependencies are treated # as dependent on root_node. root_node = DependencyGraphNode(None) for target, spec in targets.items(): target_node = dependency_nodes[target] dependencies = spec.get("dependencies") if not dependencies: target_node.dependencies = [root_node] root_node.dependents.append(target_node) else: for dependency in dependencies: dependency_node = dependency_nodes.get(dependency) if not dependency_node: raise GypError( "Dependency '%s' not found while " "trying to load target %s" % (dependency, target) ) target_node.dependencies.append(dependency_node) dependency_node.dependents.append(target_node) flat_list = root_node.FlattenToList() # If there's anything left unvisited, there must be a circular dependency # (cycle). if len(flat_list) != len(targets): if not root_node.dependents: # If all targets have dependencies, add the first target as a dependent # of root_node so that the cycle can be discovered from root_node. target = next(iter(targets)) target_node = dependency_nodes[target] target_node.dependencies.append(root_node) root_node.dependents.append(target_node) cycles = [] for cycle in root_node.FindCycles(): paths = [node.ref for node in cycle] cycles.append("Cycle: %s" % " -> ".join(paths)) raise DependencyGraphNode.CircularException( "Cycles in dependency graph detected:\n" + "\n".join(cycles) ) return [dependency_nodes, flat_list] def VerifyNoGYPFileCircularDependencies(targets): # Create a DependencyGraphNode for each gyp file containing a target. Put # it into a dict for easy access. dependency_nodes = {} for target in targets: build_file = gyp.common.BuildFile(target) if build_file not in dependency_nodes: dependency_nodes[build_file] = DependencyGraphNode(build_file) # Set up the dependency links. for target, spec in targets.items(): build_file = gyp.common.BuildFile(target) build_file_node = dependency_nodes[build_file] target_dependencies = spec.get("dependencies", []) for dependency in target_dependencies: try: dependency_build_file = gyp.common.BuildFile(dependency) except GypError as e: gyp.common.ExceptionAppend( e, "while computing dependencies of .gyp file %s" % build_file ) raise if dependency_build_file == build_file: # A .gyp file is allowed to refer back to itself. continue dependency_node = dependency_nodes.get(dependency_build_file) if not dependency_node: raise GypError("Dependency '%s' not found" % dependency_build_file) if dependency_node not in build_file_node.dependencies: build_file_node.dependencies.append(dependency_node) dependency_node.dependents.append(build_file_node) # Files that have no dependencies are treated as dependent on root_node. root_node = DependencyGraphNode(None) for build_file_node in dependency_nodes.values(): if len(build_file_node.dependencies) == 0: build_file_node.dependencies.append(root_node) root_node.dependents.append(build_file_node) flat_list = root_node.FlattenToList() # If there's anything left unvisited, there must be a circular dependency # (cycle). if len(flat_list) != len(dependency_nodes): if not root_node.dependents: # If all files have dependencies, add the first file as a dependent # of root_node so that the cycle can be discovered from root_node. file_node = next(iter(dependency_nodes.values())) file_node.dependencies.append(root_node) root_node.dependents.append(file_node) cycles = [] for cycle in root_node.FindCycles(): paths = [node.ref for node in cycle] cycles.append("Cycle: %s" % " -> ".join(paths)) raise DependencyGraphNode.CircularException( "Cycles in .gyp file dependency graph detected:\n" + "\n".join(cycles) ) def DoDependentSettings(key, flat_list, targets, dependency_nodes): # key should be one of all_dependent_settings, direct_dependent_settings, # or link_settings. for target in flat_list: target_dict = targets[target] build_file = gyp.common.BuildFile(target) if key == "all_dependent_settings": dependencies = dependency_nodes[target].DeepDependencies() elif key == "direct_dependent_settings": dependencies = dependency_nodes[target].DirectAndImportedDependencies( targets ) elif key == "link_settings": dependencies = dependency_nodes[target].DependenciesForLinkSettings(targets) else: raise GypError( "DoDependentSettings doesn't know how to determine " "dependencies for " + key ) for dependency in dependencies: dependency_dict = targets[dependency] if key not in dependency_dict: continue dependency_build_file = gyp.common.BuildFile(dependency) MergeDicts( target_dict, dependency_dict[key], build_file, dependency_build_file ) def AdjustStaticLibraryDependencies( flat_list, targets, dependency_nodes, sort_dependencies ): # Recompute target "dependencies" properties. For each static library # target, remove "dependencies" entries referring to other static libraries, # unless the dependency has the "hard_dependency" attribute set. For each # linkable target, add a "dependencies" entry referring to all of the # target's computed list of link dependencies (including static libraries # if no such entry is already present. for target in flat_list: target_dict = targets[target] target_type = target_dict["type"] if target_type == "static_library": if "dependencies" not in target_dict: continue target_dict["dependencies_original"] = target_dict.get("dependencies", [])[ : ] # A static library should not depend on another static library unless # the dependency relationship is "hard," which should only be done when # a dependent relies on some side effect other than just the build # product, like a rule or action output. Further, if a target has a # non-hard dependency, but that dependency exports a hard dependency, # the non-hard dependency can safely be removed, but the exported hard # dependency must be added to the target to keep the same dependency # ordering. dependencies = dependency_nodes[target].DirectAndImportedDependencies( targets ) index = 0 while index < len(dependencies): dependency = dependencies[index] dependency_dict = targets[dependency] # Remove every non-hard static library dependency and remove every # non-static library dependency that isn't a direct dependency. if ( dependency_dict["type"] == "static_library" and not dependency_dict.get("hard_dependency", False) ) or ( dependency_dict["type"] != "static_library" and dependency not in target_dict["dependencies"] ): # Take the dependency out of the list, and don't increment index # because the next dependency to analyze will shift into the index # formerly occupied by the one being removed. del dependencies[index] else: index = index + 1 # Update the dependencies. If the dependencies list is empty, it's not # needed, so unhook it. if len(dependencies) > 0: target_dict["dependencies"] = dependencies else: del target_dict["dependencies"] elif target_type in linkable_types: # Get a list of dependency targets that should be linked into this # target. Add them to the dependencies list if they're not already # present. link_dependencies = dependency_nodes[target].DependenciesToLinkAgainst( targets ) for dependency in link_dependencies: if dependency == target: continue if "dependencies" not in target_dict: target_dict["dependencies"] = [] if dependency not in target_dict["dependencies"]: target_dict["dependencies"].append(dependency) # Sort the dependencies list in the order from dependents to dependencies. # e.g. If A and B depend on C and C depends on D, sort them in A, B, C, D. # Note: flat_list is already sorted in the order from dependencies to # dependents. if sort_dependencies and "dependencies" in target_dict: target_dict["dependencies"] = [ dep for dep in reversed(flat_list) if dep in target_dict["dependencies"] ] # Initialize this here to speed up MakePathRelative. exception_re = re.compile(r"""["']?[-/$<>^]""") def MakePathRelative(to_file, fro_file, item): # If item is a relative path, it's relative to the build file dict that it's # coming from. Fix it up to make it relative to the build file dict that # it's going into. # Exception: any |item| that begins with these special characters is # returned without modification. # / Used when a path is already absolute (shortcut optimization; # such paths would be returned as absolute anyway) # $ Used for build environment variables # - Used for some build environment flags (such as -lapr-1 in a # "libraries" section) # < Used for our own variable and command expansions (see ExpandVariables) # > Used for our own variable and command expansions (see ExpandVariables) # ^ Used for our own variable and command expansions (see ExpandVariables) # # "/' Used when a value is quoted. If these are present, then we # check the second character instead. # if to_file == fro_file or exception_re.match(item): return item else: # TODO(dglazkov) The backslash/forward-slash replacement at the end is a # temporary measure. This should really be addressed by keeping all paths # in POSIX until actual project generation. ret = os.path.normpath( os.path.join( gyp.common.RelativePath( os.path.dirname(fro_file), os.path.dirname(to_file) ), item, ) ).replace("\\", "/") if item.endswith("/"): ret += "/" return ret def MergeLists(to, fro, to_file, fro_file, is_paths=False, append=True): # Python documentation recommends objects which do not support hash # set this value to None. Python library objects follow this rule. def is_hashable(val): return val.__hash__ # If x is hashable, returns whether x is in s. Else returns whether x is in items. def is_in_set_or_list(x, s, items): if is_hashable(x): return x in s return x in items prepend_index = 0 # Make membership testing of hashables in |to| (in particular, strings) # faster. hashable_to_set = {x for x in to if is_hashable(x)} for item in fro: singleton = False if type(item) in (str, int): # The cheap and easy case. to_item = MakePathRelative(to_file, fro_file, item) if is_paths else item if not (type(item) is str and item.startswith("-")): # Any string that doesn't begin with a "-" is a singleton - it can # only appear once in a list, to be enforced by the list merge append # or prepend. singleton = True elif type(item) is dict: # Make a copy of the dictionary, continuing to look for paths to fix. # The other intelligent aspects of merge processing won't apply because # item is being merged into an empty dict. to_item = {} MergeDicts(to_item, item, to_file, fro_file) elif type(item) is list: # Recurse, making a copy of the list. If the list contains any # descendant dicts, path fixing will occur. Note that here, custom # values for is_paths and append are dropped; those are only to be # applied to |to| and |fro|, not sublists of |fro|. append shouldn't # matter anyway because the new |to_item| list is empty. to_item = [] MergeLists(to_item, item, to_file, fro_file) else: raise TypeError( "Attempt to merge list item of unsupported type " + item.__class__.__name__ ) if append: # If appending a singleton that's already in the list, don't append. # This ensures that the earliest occurrence of the item will stay put. if not singleton or not is_in_set_or_list(to_item, hashable_to_set, to): to.append(to_item) if is_hashable(to_item): hashable_to_set.add(to_item) else: # If prepending a singleton that's already in the list, remove the # existing instance and proceed with the prepend. This ensures that the # item appears at the earliest possible position in the list. while singleton and to_item in to: to.remove(to_item) # Don't just insert everything at index 0. That would prepend the new # items to the list in reverse order, which would be an unwelcome # surprise. to.insert(prepend_index, to_item) if is_hashable(to_item): hashable_to_set.add(to_item) prepend_index = prepend_index + 1 def MergeDicts(to, fro, to_file, fro_file): # I wanted to name the parameter "from" but it's a Python keyword... for k, v in fro.items(): # It would be nice to do "if not k in to: to[k] = v" but that wouldn't give # copy semantics. Something else may want to merge from the |fro| dict # later, and having the same dict ref pointed to twice in the tree isn't # what anyone wants considering that the dicts may subsequently be # modified. if k in to: bad_merge = False if type(v) in (str, int): if type(to[k]) not in (str, int): bad_merge = True elif not isinstance(v, type(to[k])): bad_merge = True if bad_merge: raise TypeError( "Attempt to merge dict value of type " + v.__class__.__name__ + " into incompatible type " + to[k].__class__.__name__ + " for key " + k ) if type(v) in (str, int): # Overwrite the existing value, if any. Cheap and easy. is_path = IsPathSection(k) if is_path: to[k] = MakePathRelative(to_file, fro_file, v) else: to[k] = v elif type(v) is dict: # Recurse, guaranteeing copies will be made of objects that require it. if k not in to: to[k] = {} MergeDicts(to[k], v, to_file, fro_file) elif type(v) is list: # Lists in dicts can be merged with different policies, depending on # how the key in the "from" dict (k, the from-key) is written. # # If the from-key has ...the to-list will have this action # this character appended:... applied when receiving the from-list: # = replace # + prepend # ? set, only if to-list does not yet exist # (none) append # # This logic is list-specific, but since it relies on the associated # dict key, it's checked in this dict-oriented function. ext = k[-1] append = True if ext == "=": list_base = k[:-1] lists_incompatible = [list_base, list_base + "?"] to[list_base] = [] elif ext == "+": list_base = k[:-1] lists_incompatible = [list_base + "=", list_base + "?"] append = False elif ext == "?": list_base = k[:-1] lists_incompatible = [list_base, list_base + "=", list_base + "+"] else: list_base = k lists_incompatible = [list_base + "=", list_base + "?"] # Some combinations of merge policies appearing together are meaningless. # It's stupid to replace and append simultaneously, for example. Append # and prepend are the only policies that can coexist. for list_incompatible in lists_incompatible: if list_incompatible in fro: raise GypError( "Incompatible list policies " + k + " and " + list_incompatible ) if list_base in to: if ext == "?": # If the key ends in "?", the list will only be merged if it doesn't # already exist. continue elif type(to[list_base]) is not list: # This may not have been checked above if merging in a list with an # extension character. raise TypeError( "Attempt to merge dict value of type " + v.__class__.__name__ + " into incompatible type " + to[list_base].__class__.__name__ + " for key " + list_base + "(" + k + ")" ) else: to[list_base] = [] # Call MergeLists, which will make copies of objects that require it. # MergeLists can recurse back into MergeDicts, although this will be # to make copies of dicts (with paths fixed), there will be no # subsequent dict "merging" once entering a list because lists are # always replaced, appended to, or prepended to. is_paths = IsPathSection(list_base) MergeLists(to[list_base], v, to_file, fro_file, is_paths, append) else: raise TypeError( "Attempt to merge dict value of unsupported type " + v.__class__.__name__ + " for key " + k ) def MergeConfigWithInheritance( new_configuration_dict, build_file, target_dict, configuration, visited ): # Skip if previously visited. if configuration in visited: return # Look at this configuration. configuration_dict = target_dict["configurations"][configuration] # Merge in parents. for parent in configuration_dict.get("inherit_from", []): MergeConfigWithInheritance( new_configuration_dict, build_file, target_dict, parent, visited + [configuration], ) # Merge it into the new config. MergeDicts(new_configuration_dict, configuration_dict, build_file, build_file) # Drop abstract. if "abstract" in new_configuration_dict: del new_configuration_dict["abstract"] def SetUpConfigurations(target, target_dict): # key_suffixes is a list of key suffixes that might appear on key names. # These suffixes are handled in conditional evaluations (for =, +, and ?) # and rules/exclude processing (for ! and /). Keys with these suffixes # should be treated the same as keys without. key_suffixes = ["=", "+", "?", "!", "/"] build_file = gyp.common.BuildFile(target) # Provide a single configuration by default if none exists. # TODO(mark): Signal an error if default_configurations exists but # configurations does not. if "configurations" not in target_dict: target_dict["configurations"] = {"Default": {}} if "default_configuration" not in target_dict: concrete = [ i for (i, config) in target_dict["configurations"].items() if not config.get("abstract") ] target_dict["default_configuration"] = sorted(concrete)[0] merged_configurations = {} configs = target_dict["configurations"] for (configuration, old_configuration_dict) in configs.items(): # Skip abstract configurations (saves work only). if old_configuration_dict.get("abstract"): continue # Configurations inherit (most) settings from the enclosing target scope. # Get the inheritance relationship right by making a copy of the target # dict. new_configuration_dict = {} for (key, target_val) in target_dict.items(): key_ext = key[-1:] key_base = key[:-1] if key_ext in key_suffixes else key if key_base not in non_configuration_keys: new_configuration_dict[key] = gyp.simple_copy.deepcopy(target_val) # Merge in configuration (with all its parents first). MergeConfigWithInheritance( new_configuration_dict, build_file, target_dict, configuration, [] ) merged_configurations[configuration] = new_configuration_dict # Put the new configurations back into the target dict as a configuration. for configuration in merged_configurations: target_dict["configurations"][configuration] = merged_configurations[ configuration ] # Now drop all the abstract ones. configs = target_dict["configurations"] target_dict["configurations"] = { k: v for k, v in configs.items() if not v.get("abstract") } # Now that all of the target's configurations have been built, go through # the target dict's keys and remove everything that's been moved into a # "configurations" section. delete_keys = [] for key in target_dict: key_ext = key[-1:] key_base = key[:-1] if key_ext in key_suffixes else key if key_base not in non_configuration_keys: delete_keys.append(key) for key in delete_keys: del target_dict[key] # Check the configurations to see if they contain invalid keys. for configuration in target_dict["configurations"]: configuration_dict = target_dict["configurations"][configuration] for key in configuration_dict: if key in invalid_configuration_keys: raise GypError( "%s not allowed in the %s configuration, found in " "target %s" % (key, configuration, target) ) def ProcessListFiltersInDict(name, the_dict): """Process regular expression and exclusion-based filters on lists. An exclusion list is in a dict key named with a trailing "!", like "sources!". Every item in such a list is removed from the associated main list, which in this example, would be "sources". Removed items are placed into a "sources_excluded" list in the dict. Regular expression (regex) filters are contained in dict keys named with a trailing "/", such as "sources/" to operate on the "sources" list. Regex filters in a dict take the form: 'sources/': [ ['exclude', '_(linux|mac|win)\\.cc$'], ['include', '_mac\\.cc$'] ], The first filter says to exclude all files ending in _linux.cc, _mac.cc, and _win.cc. The second filter then includes all files ending in _mac.cc that are now or were once in the "sources" list. Items matching an "exclude" filter are subject to the same processing as would occur if they were listed by name in an exclusion list (ending in "!"). Items matching an "include" filter are brought back into the main list if previously excluded by an exclusion list or exclusion regex filter. Subsequent matching "exclude" patterns can still cause items to be excluded after matching an "include". """ # Look through the dictionary for any lists whose keys end in "!" or "/". # These are lists that will be treated as exclude lists and regular # expression-based exclude/include lists. Collect the lists that are # needed first, looking for the lists that they operate on, and assemble # then into |lists|. This is done in a separate loop up front, because # the _included and _excluded keys need to be added to the_dict, and that # can't be done while iterating through it. lists = [] del_lists = [] for key, value in the_dict.items(): operation = key[-1] if operation not in {"!", "/"}: continue if type(value) is not list: raise ValueError( name + " key " + key + " must be list, not " + value.__class__.__name__ ) list_key = key[:-1] if list_key not in the_dict: # This happens when there's a list like "sources!" but no corresponding # "sources" list. Since there's nothing for it to operate on, queue up # the "sources!" list for deletion now. del_lists.append(key) continue if type(the_dict[list_key]) is not list: value = the_dict[list_key] raise ValueError( name + " key " + list_key + " must be list, not " + value.__class__.__name__ + " when applying " + {"!": "exclusion", "/": "regex"}[operation] ) if list_key not in lists: lists.append(list_key) # Delete the lists that are known to be unneeded at this point. for del_list in del_lists: del the_dict[del_list] for list_key in lists: the_list = the_dict[list_key] # Initialize the list_actions list, which is parallel to the_list. Each # item in list_actions identifies whether the corresponding item in # the_list should be excluded, unconditionally preserved (included), or # whether no exclusion or inclusion has been applied. Items for which # no exclusion or inclusion has been applied (yet) have value -1, items # excluded have value 0, and items included have value 1. Includes and # excludes override previous actions. All items in list_actions are # initialized to -1 because no excludes or includes have been processed # yet. list_actions = list((-1,) * len(the_list)) exclude_key = list_key + "!" if exclude_key in the_dict: for exclude_item in the_dict[exclude_key]: for index, list_item in enumerate(the_list): if exclude_item == list_item: # This item matches the exclude_item, so set its action to 0 # (exclude). list_actions[index] = 0 # The "whatever!" list is no longer needed, dump it. del the_dict[exclude_key] regex_key = list_key + "/" if regex_key in the_dict: for regex_item in the_dict[regex_key]: [action, pattern] = regex_item pattern_re = re.compile(pattern) if action == "exclude": # This item matches an exclude regex, set its value to 0 (exclude). action_value = 0 elif action == "include": # This item matches an include regex, set its value to 1 (include). action_value = 1 else: # This is an action that doesn't make any sense. raise ValueError( "Unrecognized action " + action + " in " + name + " key " + regex_key ) for index, list_item in enumerate(the_list): if list_actions[index] == action_value: # Even if the regex matches, nothing will change so continue # (regex searches are expensive). continue if pattern_re.search(list_item): # Regular expression match. list_actions[index] = action_value # The "whatever/" list is no longer needed, dump it. del the_dict[regex_key] # Add excluded items to the excluded list. # # Note that exclude_key ("sources!") is different from excluded_key # ("sources_excluded"). The exclude_key list is input and it was already # processed and deleted; the excluded_key list is output and it's about # to be created. excluded_key = list_key + "_excluded" if excluded_key in the_dict: raise GypError( name + " key " + excluded_key + " must not be present prior " " to applying exclusion/regex filters for " + list_key ) excluded_list = [] # Go backwards through the list_actions list so that as items are deleted, # the indices of items that haven't been seen yet don't shift. That means # that things need to be prepended to excluded_list to maintain them in the # same order that they existed in the_list. for index in range(len(list_actions) - 1, -1, -1): if list_actions[index] == 0: # Dump anything with action 0 (exclude). Keep anything with action 1 # (include) or -1 (no include or exclude seen for the item). excluded_list.insert(0, the_list[index]) del the_list[index] # If anything was excluded, put the excluded list into the_dict at # excluded_key. if len(excluded_list) > 0: the_dict[excluded_key] = excluded_list # Now recurse into subdicts and lists that may contain dicts. for key, value in the_dict.items(): if type(value) is dict: ProcessListFiltersInDict(key, value) elif type(value) is list: ProcessListFiltersInList(key, value) def ProcessListFiltersInList(name, the_list): for item in the_list: if type(item) is dict: ProcessListFiltersInDict(name, item) elif type(item) is list: ProcessListFiltersInList(name, item) def ValidateTargetType(target, target_dict): """Ensures the 'type' field on the target is one of the known types. Arguments: target: string, name of target. target_dict: dict, target spec. Raises an exception on error. """ VALID_TARGET_TYPES = ( "executable", "loadable_module", "static_library", "shared_library", "mac_kernel_extension", "none", "windows_driver", ) target_type = target_dict.get("type", None) if target_type not in VALID_TARGET_TYPES: raise GypError( "Target %s has an invalid target type '%s'. " "Must be one of %s." % (target, target_type, "/".join(VALID_TARGET_TYPES)) ) if ( target_dict.get("standalone_static_library", 0) and not target_type == "static_library" ): raise GypError( "Target %s has type %s but standalone_static_library flag is" " only valid for static_library type." % (target, target_type) ) def ValidateRulesInTarget(target, target_dict, extra_sources_for_rules): """Ensures that the rules sections in target_dict are valid and consistent, and determines which sources they apply to. Arguments: target: string, name of target. target_dict: dict, target spec containing "rules" and "sources" lists. extra_sources_for_rules: a list of keys to scan for rule matches in addition to 'sources'. """ # Dicts to map between values found in rules' 'rule_name' and 'extension' # keys and the rule dicts themselves. rule_names = {} rule_extensions = {} rules = target_dict.get("rules", []) for rule in rules: # Make sure that there's no conflict among rule names and extensions. rule_name = rule["rule_name"] if rule_name in rule_names: raise GypError( f"rule {rule_name} exists in duplicate, target {target}" ) rule_names[rule_name] = rule rule_extension = rule["extension"] if rule_extension.startswith("."): rule_extension = rule_extension[1:] if rule_extension in rule_extensions: raise GypError( ( "extension %s associated with multiple rules, " + "target %s rules %s and %s" ) % ( rule_extension, target, rule_extensions[rule_extension]["rule_name"], rule_name, ) ) rule_extensions[rule_extension] = rule # Make sure rule_sources isn't already there. It's going to be # created below if needed. if "rule_sources" in rule: raise GypError( "rule_sources must not exist in input, target %s rule %s" % (target, rule_name) ) rule_sources = [] source_keys = ["sources"] source_keys.extend(extra_sources_for_rules) for source_key in source_keys: for source in target_dict.get(source_key, []): (source_root, source_extension) = os.path.splitext(source) if source_extension.startswith("."): source_extension = source_extension[1:] if source_extension == rule_extension: rule_sources.append(source) if len(rule_sources) > 0: rule["rule_sources"] = rule_sources def ValidateRunAsInTarget(target, target_dict, build_file): target_name = target_dict.get("target_name") run_as = target_dict.get("run_as") if not run_as: return if type(run_as) is not dict: raise GypError( "The 'run_as' in target %s from file %s should be a " "dictionary." % (target_name, build_file) ) action = run_as.get("action") if not action: raise GypError( "The 'run_as' in target %s from file %s must have an " "'action' section." % (target_name, build_file) ) if type(action) is not list: raise GypError( "The 'action' for 'run_as' in target %s from file %s " "must be a list." % (target_name, build_file) ) working_directory = run_as.get("working_directory") if working_directory and type(working_directory) is not str: raise GypError( "The 'working_directory' for 'run_as' in target %s " "in file %s should be a string." % (target_name, build_file) ) environment = run_as.get("environment") if environment and type(environment) is not dict: raise GypError( "The 'environment' for 'run_as' in target %s " "in file %s should be a dictionary." % (target_name, build_file) ) def ValidateActionsInTarget(target, target_dict, build_file): """Validates the inputs to the actions in a target.""" target_name = target_dict.get("target_name") actions = target_dict.get("actions", []) for action in actions: action_name = action.get("action_name") if not action_name: raise GypError( "Anonymous action in target %s. " "An action must have an 'action_name' field." % target_name ) inputs = action.get("inputs", None) if inputs is None: raise GypError("Action in target %s has no inputs." % target_name) action_command = action.get("action") if action_command and not action_command[0]: raise GypError("Empty action as command in target %s." % target_name) def TurnIntIntoStrInDict(the_dict): """Given dict the_dict, recursively converts all integers into strings. """ # Use items instead of iteritems because there's no need to try to look at # reinserted keys and their associated values. for k, v in the_dict.items(): if type(v) is int: v = str(v) the_dict[k] = v elif type(v) is dict: TurnIntIntoStrInDict(v) elif type(v) is list: TurnIntIntoStrInList(v) if type(k) is int: del the_dict[k] the_dict[str(k)] = v def TurnIntIntoStrInList(the_list): """Given list the_list, recursively converts all integers into strings. """ for index, item in enumerate(the_list): if type(item) is int: the_list[index] = str(item) elif type(item) is dict: TurnIntIntoStrInDict(item) elif type(item) is list: TurnIntIntoStrInList(item) def PruneUnwantedTargets(targets, flat_list, dependency_nodes, root_targets, data): """Return only the targets that are deep dependencies of |root_targets|.""" qualified_root_targets = [] for target in root_targets: target = target.strip() qualified_targets = gyp.common.FindQualifiedTargets(target, flat_list) if not qualified_targets: raise GypError("Could not find target %s" % target) qualified_root_targets.extend(qualified_targets) wanted_targets = {} for target in qualified_root_targets: wanted_targets[target] = targets[target] for dependency in dependency_nodes[target].DeepDependencies(): wanted_targets[dependency] = targets[dependency] wanted_flat_list = [t for t in flat_list if t in wanted_targets] # Prune unwanted targets from each build_file's data dict. for build_file in data["target_build_files"]: if "targets" not in data[build_file]: continue new_targets = [] for target in data[build_file]["targets"]: qualified_name = gyp.common.QualifiedTarget( build_file, target["target_name"], target["toolset"] ) if qualified_name in wanted_targets: new_targets.append(target) data[build_file]["targets"] = new_targets return wanted_targets, wanted_flat_list def VerifyNoCollidingTargets(targets): """Verify that no two targets in the same directory share the same name. Arguments: targets: A list of targets in the form 'path/to/file.gyp:target_name'. """ # Keep a dict going from 'subdirectory:target_name' to 'foo.gyp'. used = {} for target in targets: # Separate out 'path/to/file.gyp, 'target_name' from # 'path/to/file.gyp:target_name'. path, name = target.rsplit(":", 1) # Separate out 'path/to', 'file.gyp' from 'path/to/file.gyp'. subdir, gyp = os.path.split(path) # Use '.' for the current directory '', so that the error messages make # more sense. if not subdir: subdir = "." # Prepare a key like 'path/to:target_name'. key = subdir + ":" + name if key in used: # Complain if this target is already used. raise GypError( 'Duplicate target name "%s" in directory "%s" used both ' 'in "%s" and "%s".' % (name, subdir, gyp, used[key]) ) used[key] = gyp def SetGeneratorGlobals(generator_input_info): # Set up path_sections and non_configuration_keys with the default data plus # the generator-specific data. global path_sections path_sections = set(base_path_sections) path_sections.update(generator_input_info["path_sections"]) global non_configuration_keys non_configuration_keys = base_non_configuration_keys[:] non_configuration_keys.extend(generator_input_info["non_configuration_keys"]) global multiple_toolsets multiple_toolsets = generator_input_info["generator_supports_multiple_toolsets"] global generator_filelist_paths generator_filelist_paths = generator_input_info["generator_filelist_paths"] def Load( build_files, variables, includes, depth, generator_input_info, check, circular_check, parallel, root_targets, ): SetGeneratorGlobals(generator_input_info) # A generator can have other lists (in addition to sources) be processed # for rules. extra_sources_for_rules = generator_input_info["extra_sources_for_rules"] # Load build files. This loads every target-containing build file into # the |data| dictionary such that the keys to |data| are build file names, # and the values are the entire build file contents after "early" or "pre" # processing has been done and includes have been resolved. # NOTE: data contains both "target" files (.gyp) and "includes" (.gypi), as # well as meta-data (e.g. 'included_files' key). 'target_build_files' keeps # track of the keys corresponding to "target" files. data = {"target_build_files": set()} # Normalize paths everywhere. This is important because paths will be # used as keys to the data dict and for references between input files. build_files = set(map(os.path.normpath, build_files)) if parallel: LoadTargetBuildFilesParallel( build_files, data, variables, includes, depth, check, generator_input_info ) else: aux_data = {} for build_file in build_files: try: LoadTargetBuildFile( build_file, data, aux_data, variables, includes, depth, check, True ) except Exception as e: gyp.common.ExceptionAppend(e, "while trying to load %s" % build_file) raise # Build a dict to access each target's subdict by qualified name. targets = BuildTargetsDict(data) # Fully qualify all dependency links. QualifyDependencies(targets) # Remove self-dependencies from targets that have 'prune_self_dependencies' # set to 1. RemoveSelfDependencies(targets) # Expand dependencies specified as build_file:*. ExpandWildcardDependencies(targets, data) # Remove all dependencies marked as 'link_dependency' from the targets of # type 'none'. RemoveLinkDependenciesFromNoneTargets(targets) # Apply exclude (!) and regex (/) list filters only for dependency_sections. for target_name, target_dict in targets.items(): tmp_dict = {} for key_base in dependency_sections: for op in ("", "!", "/"): key = key_base + op if key in target_dict: tmp_dict[key] = target_dict[key] del target_dict[key] ProcessListFiltersInDict(target_name, tmp_dict) # Write the results back to |target_dict|. for key in tmp_dict: target_dict[key] = tmp_dict[key] # Make sure every dependency appears at most once. RemoveDuplicateDependencies(targets) if circular_check: # Make sure that any targets in a.gyp don't contain dependencies in other # .gyp files that further depend on a.gyp. VerifyNoGYPFileCircularDependencies(targets) [dependency_nodes, flat_list] = BuildDependencyList(targets) if root_targets: # Remove, from |targets| and |flat_list|, the targets that are not deep # dependencies of the targets specified in |root_targets|. targets, flat_list = PruneUnwantedTargets( targets, flat_list, dependency_nodes, root_targets, data ) # Check that no two targets in the same directory have the same name. VerifyNoCollidingTargets(flat_list) # Handle dependent settings of various types. for settings_type in [ "all_dependent_settings", "direct_dependent_settings", "link_settings", ]: DoDependentSettings(settings_type, flat_list, targets, dependency_nodes) # Take out the dependent settings now that they've been published to all # of the targets that require them. for target in flat_list: if settings_type in targets[target]: del targets[target][settings_type] # Make sure static libraries don't declare dependencies on other static # libraries, but that linkables depend on all unlinked static libraries # that they need so that their link steps will be correct. gii = generator_input_info if gii["generator_wants_static_library_dependencies_adjusted"]: AdjustStaticLibraryDependencies( flat_list, targets, dependency_nodes, gii["generator_wants_sorted_dependencies"], ) # Apply "post"/"late"/"target" variable expansions and condition evaluations. for target in flat_list: target_dict = targets[target] build_file = gyp.common.BuildFile(target) ProcessVariablesAndConditionsInDict( target_dict, PHASE_LATE, variables, build_file ) # Move everything that can go into a "configurations" section into one. for target in flat_list: target_dict = targets[target] SetUpConfigurations(target, target_dict) # Apply exclude (!) and regex (/) list filters. for target in flat_list: target_dict = targets[target] ProcessListFiltersInDict(target, target_dict) # Apply "latelate" variable expansions and condition evaluations. for target in flat_list: target_dict = targets[target] build_file = gyp.common.BuildFile(target) ProcessVariablesAndConditionsInDict( target_dict, PHASE_LATELATE, variables, build_file ) # Make sure that the rules make sense, and build up rule_sources lists as # needed. Not all generators will need to use the rule_sources lists, but # some may, and it seems best to build the list in a common spot. # Also validate actions and run_as elements in targets. for target in flat_list: target_dict = targets[target] build_file = gyp.common.BuildFile(target) ValidateTargetType(target, target_dict) ValidateRulesInTarget(target, target_dict, extra_sources_for_rules) ValidateRunAsInTarget(target, target_dict, build_file) ValidateActionsInTarget(target, target_dict, build_file) # Generators might not expect ints. Turn them into strs. TurnIntIntoStrInDict(data) # TODO(mark): Return |data| for now because the generator needs a list of # build files that came in. In the future, maybe it should just accept # a list, and not the whole data dict. return [flat_list, targets, data] PK ~\.brrr%node-gyp/gyp/pylib/gyp/common_test.pynu[#!/usr/bin/env python3 # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Unit tests for the common.py file.""" import gyp.common import unittest import sys class TestTopologicallySorted(unittest.TestCase): def test_Valid(self): """Test that sorting works on a valid graph with one possible order.""" graph = { "a": ["b", "c"], "b": [], "c": ["d"], "d": ["b"], } def GetEdge(node): return tuple(graph[node]) self.assertEqual( gyp.common.TopologicallySorted(graph.keys(), GetEdge), ["a", "c", "d", "b"] ) def test_Cycle(self): """Test that an exception is thrown on a cyclic graph.""" graph = { "a": ["b"], "b": ["c"], "c": ["d"], "d": ["a"], } def GetEdge(node): return tuple(graph[node]) self.assertRaises( gyp.common.CycleError, gyp.common.TopologicallySorted, graph.keys(), GetEdge ) class TestGetFlavor(unittest.TestCase): """Test that gyp.common.GetFlavor works as intended""" original_platform = "" def setUp(self): self.original_platform = sys.platform def tearDown(self): sys.platform = self.original_platform def assertFlavor(self, expected, argument, param): sys.platform = argument self.assertEqual(expected, gyp.common.GetFlavor(param)) def test_platform_default(self): self.assertFlavor("freebsd", "freebsd9", {}) self.assertFlavor("freebsd", "freebsd10", {}) self.assertFlavor("openbsd", "openbsd5", {}) self.assertFlavor("solaris", "sunos5", {}) self.assertFlavor("solaris", "sunos", {}) self.assertFlavor("linux", "linux2", {}) self.assertFlavor("linux", "linux3", {}) self.assertFlavor("linux", "linux", {}) def test_param(self): self.assertFlavor("foobar", "linux2", {"flavor": "foobar"}) if __name__ == "__main__": unittest.main() PK ~\kM\/\/%node-gyp/gyp/pylib/gyp/xcode_ninja.pynu[# Copyright (c) 2014 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Xcode-ninja wrapper project file generator. This updates the data structures passed to the Xcode gyp generator to build with ninja instead. The Xcode project itself is transformed into a list of executable targets, each with a build step to build with ninja, and a target with every source and resource file. This appears to sidestep some of the major performance headaches experienced using complex projects and large number of targets within Xcode. """ import errno import gyp.generator.ninja import os import re import xml.sax.saxutils def _WriteWorkspace(main_gyp, sources_gyp, params): """ Create a workspace to wrap main and sources gyp paths. """ (build_file_root, build_file_ext) = os.path.splitext(main_gyp) workspace_path = build_file_root + ".xcworkspace" options = params["options"] if options.generator_output: workspace_path = os.path.join(options.generator_output, workspace_path) try: os.makedirs(workspace_path) except OSError as e: if e.errno != errno.EEXIST: raise output_string = ( '\n' + '\n' ) for gyp_name in [main_gyp, sources_gyp]: name = os.path.splitext(os.path.basename(gyp_name))[0] + ".xcodeproj" name = xml.sax.saxutils.quoteattr("group:" + name) output_string += " \n" % name output_string += "\n" workspace_file = os.path.join(workspace_path, "contents.xcworkspacedata") try: with open(workspace_file) as input_file: input_string = input_file.read() if input_string == output_string: return except OSError: # Ignore errors if the file doesn't exist. pass with open(workspace_file, "w") as output_file: output_file.write(output_string) def _TargetFromSpec(old_spec, params): """ Create fake target for xcode-ninja wrapper. """ # Determine ninja top level build dir (e.g. /path/to/out). ninja_toplevel = None jobs = 0 if params: options = params["options"] ninja_toplevel = os.path.join( options.toplevel_dir, gyp.generator.ninja.ComputeOutputDir(params) ) jobs = params.get("generator_flags", {}).get("xcode_ninja_jobs", 0) target_name = old_spec.get("target_name") product_name = old_spec.get("product_name", target_name) product_extension = old_spec.get("product_extension") ninja_target = {} ninja_target["target_name"] = target_name ninja_target["product_name"] = product_name if product_extension: ninja_target["product_extension"] = product_extension ninja_target["toolset"] = old_spec.get("toolset") ninja_target["default_configuration"] = old_spec.get("default_configuration") ninja_target["configurations"] = {} # Tell Xcode to look in |ninja_toplevel| for build products. new_xcode_settings = {} if ninja_toplevel: new_xcode_settings["CONFIGURATION_BUILD_DIR"] = ( "%s/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)" % ninja_toplevel ) if "configurations" in old_spec: for config in old_spec["configurations"]: old_xcode_settings = old_spec["configurations"][config].get( "xcode_settings", {} ) if "IPHONEOS_DEPLOYMENT_TARGET" in old_xcode_settings: new_xcode_settings["CODE_SIGNING_REQUIRED"] = "NO" new_xcode_settings["IPHONEOS_DEPLOYMENT_TARGET"] = old_xcode_settings[ "IPHONEOS_DEPLOYMENT_TARGET" ] for key in ["BUNDLE_LOADER", "TEST_HOST"]: if key in old_xcode_settings: new_xcode_settings[key] = old_xcode_settings[key] ninja_target["configurations"][config] = {} ninja_target["configurations"][config][ "xcode_settings" ] = new_xcode_settings ninja_target["mac_bundle"] = old_spec.get("mac_bundle", 0) ninja_target["mac_xctest_bundle"] = old_spec.get("mac_xctest_bundle", 0) ninja_target["ios_app_extension"] = old_spec.get("ios_app_extension", 0) ninja_target["ios_watchkit_extension"] = old_spec.get("ios_watchkit_extension", 0) ninja_target["ios_watchkit_app"] = old_spec.get("ios_watchkit_app", 0) ninja_target["type"] = old_spec["type"] if ninja_toplevel: ninja_target["actions"] = [ { "action_name": "Compile and copy %s via ninja" % target_name, "inputs": [], "outputs": [], "action": [ "env", "PATH=%s" % os.environ["PATH"], "ninja", "-C", new_xcode_settings["CONFIGURATION_BUILD_DIR"], target_name, ], "message": "Compile and copy %s via ninja" % target_name, }, ] if jobs > 0: ninja_target["actions"][0]["action"].extend(("-j", jobs)) return ninja_target def IsValidTargetForWrapper(target_extras, executable_target_pattern, spec): """Limit targets for Xcode wrapper. Xcode sometimes performs poorly with too many targets, so only include proper executable targets, with filters to customize. Arguments: target_extras: Regular expression to always add, matching any target. executable_target_pattern: Regular expression limiting executable targets. spec: Specifications for target. """ target_name = spec.get("target_name") # Always include targets matching target_extras. if target_extras is not None and re.search(target_extras, target_name): return True # Otherwise just show executable targets and xc_tests. if int(spec.get("mac_xctest_bundle", 0)) != 0 or ( spec.get("type", "") == "executable" and spec.get("product_extension", "") != "bundle" ): # If there is a filter and the target does not match, exclude the target. if executable_target_pattern is not None: if not re.search(executable_target_pattern, target_name): return False return True return False def CreateWrapper(target_list, target_dicts, data, params): """Initialize targets for the ninja wrapper. This sets up the necessary variables in the targets to generate Xcode projects that use ninja as an external builder. Arguments: target_list: List of target pairs: 'base/base.gyp:base'. target_dicts: Dict of target properties keyed on target pair. data: Dict of flattened build files keyed on gyp path. params: Dict of global options for gyp. """ orig_gyp = params["build_files"][0] for gyp_name, gyp_dict in data.items(): if gyp_name == orig_gyp: depth = gyp_dict["_DEPTH"] # Check for custom main gyp name, otherwise use the default CHROMIUM_GYP_FILE # and prepend .ninja before the .gyp extension. generator_flags = params.get("generator_flags", {}) main_gyp = generator_flags.get("xcode_ninja_main_gyp", None) if main_gyp is None: (build_file_root, build_file_ext) = os.path.splitext(orig_gyp) main_gyp = build_file_root + ".ninja" + build_file_ext # Create new |target_list|, |target_dicts| and |data| data structures. new_target_list = [] new_target_dicts = {} new_data = {} # Set base keys needed for |data|. new_data[main_gyp] = {} new_data[main_gyp]["included_files"] = [] new_data[main_gyp]["targets"] = [] new_data[main_gyp]["xcode_settings"] = data[orig_gyp].get("xcode_settings", {}) # Normally the xcode-ninja generator includes only valid executable targets. # If |xcode_ninja_executable_target_pattern| is set, that list is reduced to # executable targets that match the pattern. (Default all) executable_target_pattern = generator_flags.get( "xcode_ninja_executable_target_pattern", None ) # For including other non-executable targets, add the matching target name # to the |xcode_ninja_target_pattern| regular expression. (Default none) target_extras = generator_flags.get("xcode_ninja_target_pattern", None) for old_qualified_target in target_list: spec = target_dicts[old_qualified_target] if IsValidTargetForWrapper(target_extras, executable_target_pattern, spec): # Add to new_target_list. target_name = spec.get("target_name") new_target_name = f"{main_gyp}:{target_name}#target" new_target_list.append(new_target_name) # Add to new_target_dicts. new_target_dicts[new_target_name] = _TargetFromSpec(spec, params) # Add to new_data. for old_target in data[old_qualified_target.split(":")[0]]["targets"]: if old_target["target_name"] == target_name: new_data_target = {} new_data_target["target_name"] = old_target["target_name"] new_data_target["toolset"] = old_target["toolset"] new_data[main_gyp]["targets"].append(new_data_target) # Create sources target. sources_target_name = "sources_for_indexing" sources_target = _TargetFromSpec( { "target_name": sources_target_name, "toolset": "target", "default_configuration": "Default", "mac_bundle": "0", "type": "executable", }, None, ) # Tell Xcode to look everywhere for headers. sources_target["configurations"] = {"Default": {"include_dirs": [depth]}} # Put excluded files into the sources target so they can be opened in Xcode. skip_excluded_files = not generator_flags.get( "xcode_ninja_list_excluded_files", True ) sources = [] for target, target_dict in target_dicts.items(): base = os.path.dirname(target) files = target_dict.get("sources", []) + target_dict.get( "mac_bundle_resources", [] ) if not skip_excluded_files: files.extend( target_dict.get("sources_excluded", []) + target_dict.get("mac_bundle_resources_excluded", []) ) for action in target_dict.get("actions", []): files.extend(action.get("inputs", [])) if not skip_excluded_files: files.extend(action.get("inputs_excluded", [])) # Remove files starting with $. These are mostly intermediate files for the # build system. files = [file for file in files if not file.startswith("$")] # Make sources relative to root build file. relative_path = os.path.dirname(main_gyp) sources += [ os.path.relpath(os.path.join(base, file), relative_path) for file in files ] sources_target["sources"] = sorted(set(sources)) # Put sources_to_index in it's own gyp. sources_gyp = os.path.join(os.path.dirname(main_gyp), sources_target_name + ".gyp") fully_qualified_target_name = f"{sources_gyp}:{sources_target_name}#target" # Add to new_target_list, new_target_dicts and new_data. new_target_list.append(fully_qualified_target_name) new_target_dicts[fully_qualified_target_name] = sources_target new_data_target = {} new_data_target["target_name"] = sources_target["target_name"] new_data_target["_DEPTH"] = depth new_data_target["toolset"] = "target" new_data[sources_gyp] = {} new_data[sources_gyp]["targets"] = [] new_data[sources_gyp]["included_files"] = [] new_data[sources_gyp]["xcode_settings"] = data[orig_gyp].get("xcode_settings", {}) new_data[sources_gyp]["targets"].append(new_data_target) # Write workspace to file. _WriteWorkspace(main_gyp, sources_gyp, params) return (new_target_list, new_target_dicts, new_data) PK ~\)SS%node-gyp/gyp/pylib/gyp/MSVSProject.pynu[# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Visual Studio project reader/writer.""" import gyp.easy_xml as easy_xml # ------------------------------------------------------------------------------ class Tool: """Visual Studio tool.""" def __init__(self, name, attrs=None): """Initializes the tool. Args: name: Tool name. attrs: Dict of tool attributes; may be None. """ self._attrs = attrs or {} self._attrs["Name"] = name def _GetSpecification(self): """Creates an element for the tool. Returns: A new xml.dom.Element for the tool. """ return ["Tool", self._attrs] class Filter: """Visual Studio filter - that is, a virtual folder.""" def __init__(self, name, contents=None): """Initializes the folder. Args: name: Filter (folder) name. contents: List of filenames and/or Filter objects contained. """ self.name = name self.contents = list(contents or []) # ------------------------------------------------------------------------------ class Writer: """Visual Studio XML project writer.""" def __init__(self, project_path, version, name, guid=None, platforms=None): """Initializes the project. Args: project_path: Path to the project file. version: Format version to emit. name: Name of the project. guid: GUID to use for project, if not None. platforms: Array of string, the supported platforms. If null, ['Win32'] """ self.project_path = project_path self.version = version self.name = name self.guid = guid # Default to Win32 for platforms. if not platforms: platforms = ["Win32"] # Initialize the specifications of the various sections. self.platform_section = ["Platforms"] for platform in platforms: self.platform_section.append(["Platform", {"Name": platform}]) self.tool_files_section = ["ToolFiles"] self.configurations_section = ["Configurations"] self.files_section = ["Files"] # Keep a dict keyed on filename to speed up access. self.files_dict = {} def AddToolFile(self, path): """Adds a tool file to the project. Args: path: Relative path from project to tool file. """ self.tool_files_section.append(["ToolFile", {"RelativePath": path}]) def _GetSpecForConfiguration(self, config_type, config_name, attrs, tools): """Returns the specification for a configuration. Args: config_type: Type of configuration node. config_name: Configuration name. attrs: Dict of configuration attributes; may be None. tools: List of tools (strings or Tool objects); may be None. Returns: """ # Handle defaults if not attrs: attrs = {} if not tools: tools = [] # Add configuration node and its attributes node_attrs = attrs.copy() node_attrs["Name"] = config_name specification = [config_type, node_attrs] # Add tool nodes and their attributes if tools: for t in tools: if isinstance(t, Tool): specification.append(t._GetSpecification()) else: specification.append(Tool(t)._GetSpecification()) return specification def AddConfig(self, name, attrs=None, tools=None): """Adds a configuration to the project. Args: name: Configuration name. attrs: Dict of configuration attributes; may be None. tools: List of tools (strings or Tool objects); may be None. """ spec = self._GetSpecForConfiguration("Configuration", name, attrs, tools) self.configurations_section.append(spec) def _AddFilesToNode(self, parent, files): """Adds files and/or filters to the parent node. Args: parent: Destination node files: A list of Filter objects and/or relative paths to files. Will call itself recursively, if the files list contains Filter objects. """ for f in files: if isinstance(f, Filter): node = ["Filter", {"Name": f.name}] self._AddFilesToNode(node, f.contents) else: node = ["File", {"RelativePath": f}] self.files_dict[f] = node parent.append(node) def AddFiles(self, files): """Adds files to the project. Args: files: A list of Filter objects and/or relative paths to files. This makes a copy of the file/filter tree at the time of this call. If you later add files to a Filter object which was passed into a previous call to AddFiles(), it will not be reflected in this project. """ self._AddFilesToNode(self.files_section, files) # TODO(rspangler) This also doesn't handle adding files to an existing # filter. That is, it doesn't merge the trees. def AddFileConfig(self, path, config, attrs=None, tools=None): """Adds a configuration to a file. Args: path: Relative path to the file. config: Name of configuration to add. attrs: Dict of configuration attributes; may be None. tools: List of tools (strings or Tool objects); may be None. Raises: ValueError: Relative path does not match any file added via AddFiles(). """ # Find the file node with the right relative path parent = self.files_dict.get(path) if not parent: raise ValueError('AddFileConfig: file "%s" not in project.' % path) # Add the config to the file node spec = self._GetSpecForConfiguration("FileConfiguration", config, attrs, tools) parent.append(spec) def WriteIfChanged(self): """Writes the project file.""" # First create XML content definition content = [ "VisualStudioProject", { "ProjectType": "Visual C++", "Version": self.version.ProjectVersion(), "Name": self.name, "ProjectGUID": self.guid, "RootNamespace": self.name, "Keyword": "Win32Proj", }, self.platform_section, self.tool_files_section, self.configurations_section, ["References"], # empty section self.files_section, ["Globals"], # empty section ] easy_xml.WriteXmlIfChanged(content, self.project_path, encoding="Windows-1252") PK ~\:dۅ4v4v"node-gyp/gyp/pylib/gyp/mac_tool.pynu[#!/usr/bin/env python3 # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Utility functions to perform Xcode-style build steps. These functions are executed via gyp-mac-tool when using the Makefile generator. """ import fcntl import fnmatch import glob import json import os import plistlib import re import shutil import struct import subprocess import sys import tempfile def main(args): executor = MacTool() exit_code = executor.Dispatch(args) if exit_code is not None: sys.exit(exit_code) class MacTool: """This class performs all the Mac tooling steps. The methods can either be executed directly, or dispatched from an argument list.""" def Dispatch(self, args): """Dispatches a string command to a method.""" if len(args) < 1: raise Exception("Not enough arguments") method = "Exec%s" % self._CommandifyName(args[0]) return getattr(self, method)(*args[1:]) def _CommandifyName(self, name_string): """Transforms a tool name like copy-info-plist to CopyInfoPlist""" return name_string.title().replace("-", "") def ExecCopyBundleResource(self, source, dest, convert_to_binary): """Copies a resource file to the bundle/Resources directory, performing any necessary compilation on each resource.""" convert_to_binary = convert_to_binary == "True" extension = os.path.splitext(source)[1].lower() if os.path.isdir(source): # Copy tree. # TODO(thakis): This copies file attributes like mtime, while the # single-file branch below doesn't. This should probably be changed to # be consistent with the single-file branch. if os.path.exists(dest): shutil.rmtree(dest) shutil.copytree(source, dest) elif extension == ".xib": return self._CopyXIBFile(source, dest) elif extension == ".storyboard": return self._CopyXIBFile(source, dest) elif extension == ".strings" and not convert_to_binary: self._CopyStringsFile(source, dest) else: if os.path.exists(dest): os.unlink(dest) shutil.copy(source, dest) if convert_to_binary and extension in (".plist", ".strings"): self._ConvertToBinary(dest) def _CopyXIBFile(self, source, dest): """Compiles a XIB file with ibtool into a binary plist in the bundle.""" # ibtool sometimes crashes with relative paths. See crbug.com/314728. base = os.path.dirname(os.path.realpath(__file__)) if os.path.relpath(source): source = os.path.join(base, source) if os.path.relpath(dest): dest = os.path.join(base, dest) args = ["xcrun", "ibtool", "--errors", "--warnings", "--notices"] if os.environ["XCODE_VERSION_ACTUAL"] > "0700": args.extend(["--auto-activate-custom-fonts"]) if "IPHONEOS_DEPLOYMENT_TARGET" in os.environ: args.extend( [ "--target-device", "iphone", "--target-device", "ipad", "--minimum-deployment-target", os.environ["IPHONEOS_DEPLOYMENT_TARGET"], ] ) else: args.extend( [ "--target-device", "mac", "--minimum-deployment-target", os.environ["MACOSX_DEPLOYMENT_TARGET"], ] ) args.extend( ["--output-format", "human-readable-text", "--compile", dest, source] ) ibtool_section_re = re.compile(r"/\*.*\*/") ibtool_re = re.compile(r".*note:.*is clipping its content") try: stdout = subprocess.check_output(args) except subprocess.CalledProcessError as e: print(e.output) raise current_section_header = None for line in stdout.splitlines(): if ibtool_section_re.match(line): current_section_header = line elif not ibtool_re.match(line): if current_section_header: print(current_section_header) current_section_header = None print(line) return 0 def _ConvertToBinary(self, dest): subprocess.check_call( ["xcrun", "plutil", "-convert", "binary1", "-o", dest, dest] ) def _CopyStringsFile(self, source, dest): """Copies a .strings file using iconv to reconvert the input into UTF-16.""" input_code = self._DetectInputEncoding(source) or "UTF-8" # Xcode's CpyCopyStringsFile / builtin-copyStrings seems to call # CFPropertyListCreateFromXMLData() behind the scenes; at least it prints # CFPropertyListCreateFromXMLData(): Old-style plist parser: missing # semicolon in dictionary. # on invalid files. Do the same kind of validation. import CoreFoundation with open(source, "rb") as in_file: s = in_file.read() d = CoreFoundation.CFDataCreate(None, s, len(s)) _, error = CoreFoundation.CFPropertyListCreateFromXMLData(None, d, 0, None) if error: return with open(dest, "wb") as fp: fp.write(s.decode(input_code).encode("UTF-16")) def _DetectInputEncoding(self, file_name): """Reads the first few bytes from file_name and tries to guess the text encoding. Returns None as a guess if it can't detect it.""" with open(file_name, "rb") as fp: try: header = fp.read(3) except Exception: return None if header.startswith(b"\xFE\xFF"): return "UTF-16" elif header.startswith(b"\xFF\xFE"): return "UTF-16" elif header.startswith(b"\xEF\xBB\xBF"): return "UTF-8" else: return None def ExecCopyInfoPlist(self, source, dest, convert_to_binary, *keys): """Copies the |source| Info.plist to the destination directory |dest|.""" # Read the source Info.plist into memory. with open(source) as fd: lines = fd.read() # Insert synthesized key/value pairs (e.g. BuildMachineOSBuild). plist = plistlib.readPlistFromString(lines) if keys: plist.update(json.loads(keys[0])) lines = plistlib.writePlistToString(plist) # Go through all the environment variables and replace them as variables in # the file. IDENT_RE = re.compile(r"[_/\s]") for key in os.environ: if key.startswith("_"): continue evar = "${%s}" % key evalue = os.environ[key] lines = lines.replace(lines, evar, evalue) # Xcode supports various suffices on environment variables, which are # all undocumented. :rfc1034identifier is used in the standard project # template these days, and :identifier was used earlier. They are used to # convert non-url characters into things that look like valid urls -- # except that the replacement character for :identifier, '_' isn't valid # in a URL either -- oops, hence :rfc1034identifier was born. evar = "${%s:identifier}" % key evalue = IDENT_RE.sub("_", os.environ[key]) lines = lines.replace(lines, evar, evalue) evar = "${%s:rfc1034identifier}" % key evalue = IDENT_RE.sub("-", os.environ[key]) lines = lines.replace(lines, evar, evalue) # Remove any keys with values that haven't been replaced. lines = lines.splitlines() for i in range(len(lines)): if lines[i].strip().startswith("${"): lines[i] = None lines[i - 1] = None lines = "\n".join(line for line in lines if line is not None) # Write out the file with variables replaced. with open(dest, "w") as fd: fd.write(lines) # Now write out PkgInfo file now that the Info.plist file has been # "compiled". self._WritePkgInfo(dest) if convert_to_binary == "True": self._ConvertToBinary(dest) def _WritePkgInfo(self, info_plist): """This writes the PkgInfo file from the data stored in Info.plist.""" plist = plistlib.readPlist(info_plist) if not plist: return # Only create PkgInfo for executable types. package_type = plist["CFBundlePackageType"] if package_type != "APPL": return # The format of PkgInfo is eight characters, representing the bundle type # and bundle signature, each four characters. If that is missing, four # '?' characters are used instead. signature_code = plist.get("CFBundleSignature", "????") if len(signature_code) != 4: # Wrong length resets everything, too. signature_code = "?" * 4 dest = os.path.join(os.path.dirname(info_plist), "PkgInfo") with open(dest, "w") as fp: fp.write(f"{package_type}{signature_code}") def ExecFlock(self, lockfile, *cmd_list): """Emulates the most basic behavior of Linux's flock(1).""" # Rely on exception handling to report errors. fd = os.open(lockfile, os.O_RDONLY | os.O_NOCTTY | os.O_CREAT, 0o666) fcntl.flock(fd, fcntl.LOCK_EX) return subprocess.call(cmd_list) def ExecFilterLibtool(self, *cmd_list): """Calls libtool and filters out '/path/to/libtool: file: foo.o has no symbols'.""" libtool_re = re.compile( r"^.*libtool: (?:for architecture: \S* )?" r"file: .* has no symbols$" ) libtool_re5 = re.compile( r"^.*libtool: warning for library: " + r".* the table of contents is empty " + r"\(no object file members in the library define global symbols\)$" ) env = os.environ.copy() # Ref: # http://www.opensource.apple.com/source/cctools/cctools-809/misc/libtool.c # The problem with this flag is that it resets the file mtime on the file to # epoch=0, e.g. 1970-1-1 or 1969-12-31 depending on timezone. env["ZERO_AR_DATE"] = "1" libtoolout = subprocess.Popen(cmd_list, stderr=subprocess.PIPE, env=env) err = libtoolout.communicate()[1].decode("utf-8") for line in err.splitlines(): if not libtool_re.match(line) and not libtool_re5.match(line): print(line, file=sys.stderr) # Unconditionally touch the output .a file on the command line if present # and the command succeeded. A bit hacky. if not libtoolout.returncode: for i in range(len(cmd_list) - 1): if cmd_list[i] == "-o" and cmd_list[i + 1].endswith(".a"): os.utime(cmd_list[i + 1], None) break return libtoolout.returncode def ExecPackageIosFramework(self, framework): # Find the name of the binary based on the part before the ".framework". binary = os.path.basename(framework).split(".")[0] module_path = os.path.join(framework, "Modules") if not os.path.exists(module_path): os.mkdir(module_path) module_template = ( "framework module %s {\n" ' umbrella header "%s.h"\n' "\n" " export *\n" " module * { export * }\n" "}\n" % (binary, binary) ) with open(os.path.join(module_path, "module.modulemap"), "w") as module_file: module_file.write(module_template) def ExecPackageFramework(self, framework, version): """Takes a path to Something.framework and the Current version of that and sets up all the symlinks.""" # Find the name of the binary based on the part before the ".framework". binary = os.path.basename(framework).split(".")[0] CURRENT = "Current" RESOURCES = "Resources" VERSIONS = "Versions" if not os.path.exists(os.path.join(framework, VERSIONS, version, binary)): # Binary-less frameworks don't seem to contain symlinks (see e.g. # chromium's out/Debug/org.chromium.Chromium.manifest/ bundle). return # Move into the framework directory to set the symlinks correctly. pwd = os.getcwd() os.chdir(framework) # Set up the Current version. self._Relink(version, os.path.join(VERSIONS, CURRENT)) # Set up the root symlinks. self._Relink(os.path.join(VERSIONS, CURRENT, binary), binary) self._Relink(os.path.join(VERSIONS, CURRENT, RESOURCES), RESOURCES) # Back to where we were before! os.chdir(pwd) def _Relink(self, dest, link): """Creates a symlink to |dest| named |link|. If |link| already exists, it is overwritten.""" if os.path.lexists(link): os.remove(link) os.symlink(dest, link) def ExecCompileIosFrameworkHeaderMap(self, out, framework, *all_headers): framework_name = os.path.basename(framework).split(".")[0] all_headers = [os.path.abspath(header) for header in all_headers] filelist = {} for header in all_headers: filename = os.path.basename(header) filelist[filename] = header filelist[os.path.join(framework_name, filename)] = header WriteHmap(out, filelist) def ExecCopyIosFrameworkHeaders(self, framework, *copy_headers): header_path = os.path.join(framework, "Headers") if not os.path.exists(header_path): os.makedirs(header_path) for header in copy_headers: shutil.copy(header, os.path.join(header_path, os.path.basename(header))) def ExecCompileXcassets(self, keys, *inputs): """Compiles multiple .xcassets files into a single .car file. This invokes 'actool' to compile all the inputs .xcassets files. The |keys| arguments is a json-encoded dictionary of extra arguments to pass to 'actool' when the asset catalogs contains an application icon or a launch image. Note that 'actool' does not create the Assets.car file if the asset catalogs does not contains imageset. """ command_line = [ "xcrun", "actool", "--output-format", "human-readable-text", "--compress-pngs", "--notices", "--warnings", "--errors", ] is_iphone_target = "IPHONEOS_DEPLOYMENT_TARGET" in os.environ if is_iphone_target: platform = os.environ["CONFIGURATION"].split("-")[-1] if platform not in ("iphoneos", "iphonesimulator"): platform = "iphonesimulator" command_line.extend( [ "--platform", platform, "--target-device", "iphone", "--target-device", "ipad", "--minimum-deployment-target", os.environ["IPHONEOS_DEPLOYMENT_TARGET"], "--compile", os.path.abspath(os.environ["CONTENTS_FOLDER_PATH"]), ] ) else: command_line.extend( [ "--platform", "macosx", "--target-device", "mac", "--minimum-deployment-target", os.environ["MACOSX_DEPLOYMENT_TARGET"], "--compile", os.path.abspath(os.environ["UNLOCALIZED_RESOURCES_FOLDER_PATH"]), ] ) if keys: keys = json.loads(keys) for key, value in keys.items(): arg_name = "--" + key if isinstance(value, bool): if value: command_line.append(arg_name) elif isinstance(value, list): for v in value: command_line.append(arg_name) command_line.append(str(v)) else: command_line.append(arg_name) command_line.append(str(value)) # Note: actool crashes if inputs path are relative, so use os.path.abspath # to get absolute path name for inputs. command_line.extend(map(os.path.abspath, inputs)) subprocess.check_call(command_line) def ExecMergeInfoPlist(self, output, *inputs): """Merge multiple .plist files into a single .plist file.""" merged_plist = {} for path in inputs: plist = self._LoadPlistMaybeBinary(path) self._MergePlist(merged_plist, plist) plistlib.writePlist(merged_plist, output) def ExecCodeSignBundle(self, key, entitlements, provisioning, path, preserve): """Code sign a bundle. This function tries to code sign an iOS bundle, following the same algorithm as Xcode: 1. pick the provisioning profile that best match the bundle identifier, and copy it into the bundle as embedded.mobileprovision, 2. copy Entitlements.plist from user or SDK next to the bundle, 3. code sign the bundle. """ substitutions, overrides = self._InstallProvisioningProfile( provisioning, self._GetCFBundleIdentifier() ) entitlements_path = self._InstallEntitlements( entitlements, substitutions, overrides ) args = ["codesign", "--force", "--sign", key] if preserve == "True": args.extend(["--deep", "--preserve-metadata=identifier,entitlements"]) else: args.extend(["--entitlements", entitlements_path]) args.extend(["--timestamp=none", path]) subprocess.check_call(args) def _InstallProvisioningProfile(self, profile, bundle_identifier): """Installs embedded.mobileprovision into the bundle. Args: profile: string, optional, short name of the .mobileprovision file to use, if empty or the file is missing, the best file installed will be used bundle_identifier: string, value of CFBundleIdentifier from Info.plist Returns: A tuple containing two dictionary: variables substitutions and values to overrides when generating the entitlements file. """ source_path, provisioning_data, team_id = self._FindProvisioningProfile( profile, bundle_identifier ) target_path = os.path.join( os.environ["BUILT_PRODUCTS_DIR"], os.environ["CONTENTS_FOLDER_PATH"], "embedded.mobileprovision", ) shutil.copy2(source_path, target_path) substitutions = self._GetSubstitutions(bundle_identifier, team_id + ".") return substitutions, provisioning_data["Entitlements"] def _FindProvisioningProfile(self, profile, bundle_identifier): """Finds the .mobileprovision file to use for signing the bundle. Checks all the installed provisioning profiles (or if the user specified the PROVISIONING_PROFILE variable, only consult it) and select the most specific that correspond to the bundle identifier. Args: profile: string, optional, short name of the .mobileprovision file to use, if empty or the file is missing, the best file installed will be used bundle_identifier: string, value of CFBundleIdentifier from Info.plist Returns: A tuple of the path to the selected provisioning profile, the data of the embedded plist in the provisioning profile and the team identifier to use for code signing. Raises: SystemExit: if no .mobileprovision can be used to sign the bundle. """ profiles_dir = os.path.join( os.environ["HOME"], "Library", "MobileDevice", "Provisioning Profiles" ) if not os.path.isdir(profiles_dir): print( "cannot find mobile provisioning for %s" % (bundle_identifier), file=sys.stderr, ) sys.exit(1) provisioning_profiles = None if profile: profile_path = os.path.join(profiles_dir, profile + ".mobileprovision") if os.path.exists(profile_path): provisioning_profiles = [profile_path] if not provisioning_profiles: provisioning_profiles = glob.glob( os.path.join(profiles_dir, "*.mobileprovision") ) valid_provisioning_profiles = {} for profile_path in provisioning_profiles: profile_data = self._LoadProvisioningProfile(profile_path) app_id_pattern = profile_data.get("Entitlements", {}).get( "application-identifier", "" ) for team_identifier in profile_data.get("TeamIdentifier", []): app_id = f"{team_identifier}.{bundle_identifier}" if fnmatch.fnmatch(app_id, app_id_pattern): valid_provisioning_profiles[app_id_pattern] = ( profile_path, profile_data, team_identifier, ) if not valid_provisioning_profiles: print( "cannot find mobile provisioning for %s" % (bundle_identifier), file=sys.stderr, ) sys.exit(1) # If the user has multiple provisioning profiles installed that can be # used for ${bundle_identifier}, pick the most specific one (ie. the # provisioning profile whose pattern is the longest). selected_key = max(valid_provisioning_profiles, key=lambda v: len(v)) return valid_provisioning_profiles[selected_key] def _LoadProvisioningProfile(self, profile_path): """Extracts the plist embedded in a provisioning profile. Args: profile_path: string, path to the .mobileprovision file Returns: Content of the plist embedded in the provisioning profile as a dictionary. """ with tempfile.NamedTemporaryFile() as temp: subprocess.check_call( ["security", "cms", "-D", "-i", profile_path, "-o", temp.name] ) return self._LoadPlistMaybeBinary(temp.name) def _MergePlist(self, merged_plist, plist): """Merge |plist| into |merged_plist|.""" for key, value in plist.items(): if isinstance(value, dict): merged_value = merged_plist.get(key, {}) if isinstance(merged_value, dict): self._MergePlist(merged_value, value) merged_plist[key] = merged_value else: merged_plist[key] = value else: merged_plist[key] = value def _LoadPlistMaybeBinary(self, plist_path): """Loads into a memory a plist possibly encoded in binary format. This is a wrapper around plistlib.readPlist that tries to convert the plist to the XML format if it can't be parsed (assuming that it is in the binary format). Args: plist_path: string, path to a plist file, in XML or binary format Returns: Content of the plist as a dictionary. """ try: # First, try to read the file using plistlib that only supports XML, # and if an exception is raised, convert a temporary copy to XML and # load that copy. return plistlib.readPlist(plist_path) except Exception: pass with tempfile.NamedTemporaryFile() as temp: shutil.copy2(plist_path, temp.name) subprocess.check_call(["plutil", "-convert", "xml1", temp.name]) return plistlib.readPlist(temp.name) def _GetSubstitutions(self, bundle_identifier, app_identifier_prefix): """Constructs a dictionary of variable substitutions for Entitlements.plist. Args: bundle_identifier: string, value of CFBundleIdentifier from Info.plist app_identifier_prefix: string, value for AppIdentifierPrefix Returns: Dictionary of substitutions to apply when generating Entitlements.plist. """ return { "CFBundleIdentifier": bundle_identifier, "AppIdentifierPrefix": app_identifier_prefix, } def _GetCFBundleIdentifier(self): """Extracts CFBundleIdentifier value from Info.plist in the bundle. Returns: Value of CFBundleIdentifier in the Info.plist located in the bundle. """ info_plist_path = os.path.join( os.environ["TARGET_BUILD_DIR"], os.environ["INFOPLIST_PATH"] ) info_plist_data = self._LoadPlistMaybeBinary(info_plist_path) return info_plist_data["CFBundleIdentifier"] def _InstallEntitlements(self, entitlements, substitutions, overrides): """Generates and install the ${BundleName}.xcent entitlements file. Expands variables "$(variable)" pattern in the source entitlements file, add extra entitlements defined in the .mobileprovision file and the copy the generated plist to "${BundlePath}.xcent". Args: entitlements: string, optional, path to the Entitlements.plist template to use, defaults to "${SDKROOT}/Entitlements.plist" substitutions: dictionary, variable substitutions overrides: dictionary, values to add to the entitlements Returns: Path to the generated entitlements file. """ source_path = entitlements target_path = os.path.join( os.environ["BUILT_PRODUCTS_DIR"], os.environ["PRODUCT_NAME"] + ".xcent" ) if not source_path: source_path = os.path.join(os.environ["SDKROOT"], "Entitlements.plist") shutil.copy2(source_path, target_path) data = self._LoadPlistMaybeBinary(target_path) data = self._ExpandVariables(data, substitutions) if overrides: for key in overrides: if key not in data: data[key] = overrides[key] plistlib.writePlist(data, target_path) return target_path def _ExpandVariables(self, data, substitutions): """Expands variables "$(variable)" in data. Args: data: object, can be either string, list or dictionary substitutions: dictionary, variable substitutions to perform Returns: Copy of data where each references to "$(variable)" has been replaced by the corresponding value found in substitutions, or left intact if the key was not found. """ if isinstance(data, str): for key, value in substitutions.items(): data = data.replace("$(%s)" % key, value) return data if isinstance(data, list): return [self._ExpandVariables(v, substitutions) for v in data] if isinstance(data, dict): return {k: self._ExpandVariables(data[k], substitutions) for k in data} return data def NextGreaterPowerOf2(x): return 2 ** (x).bit_length() def WriteHmap(output_name, filelist): """Generates a header map based on |filelist|. Per Mark Mentovai: A header map is structured essentially as a hash table, keyed by names used in #includes, and providing pathnames to the actual files. The implementation below and the comment above comes from inspecting: http://www.opensource.apple.com/source/distcc/distcc-2503/distcc_dist/include_server/headermap.py?txt while also looking at the implementation in clang in: https://llvm.org/svn/llvm-project/cfe/trunk/lib/Lex/HeaderMap.cpp """ magic = 1751998832 version = 1 _reserved = 0 count = len(filelist) capacity = NextGreaterPowerOf2(count) strings_offset = 24 + (12 * capacity) max_value_length = max(len(value) for value in filelist.values()) out = open(output_name, "wb") out.write( struct.pack( ", | redirection # = assignment # {, } brace expansion (bash) # ~ tilde expansion # It also matches the empty string, because "" (or '') is the only way to # represent an empty string literal argument to a POSIX shell. # # This does not match the characters in _escape, because those need to be # backslash-escaped regardless of whether they appear in a double-quoted # string. _quote = re.compile("[\t\n #$%&'()*;<=>?[{|}~]|^$") # _escape is a pattern that should match any character that needs to be # escaped with a backslash, whether or not the argument matched the _quote # pattern. _escape is used with re.sub to backslash anything in _escape's # first match group, hence the (parentheses) in the regular expression. # # _escape matches the following characters appearing anywhere in an argument: # " to prevent POSIX shells from interpreting this character for quoting # \ to prevent POSIX shells from interpreting this character for escaping # ` to prevent POSIX shells from interpreting this character for command # substitution # Missing from this list is $, because the desired behavior of # EncodePOSIXShellArgument is to permit parameter (variable) expansion. # # Also missing from this list is !, which bash will interpret as the history # expansion character when history is enabled. bash does not enable history # by default in non-interactive shells, so this is not thought to be a problem. # ! was omitted from this list because bash interprets "\!" as a literal string # including the backslash character (avoiding history expansion but retaining # the backslash), which would not be correct for argument encoding. Handling # this case properly would also be problematic because bash allows the history # character to be changed with the histchars shell variable. Fortunately, # as history is not enabled in non-interactive shells and # EncodePOSIXShellArgument is only expected to encode for non-interactive # shells, there is no room for error here by ignoring !. _escape = re.compile(r'(["\\`])') def EncodePOSIXShellArgument(argument): """Encodes |argument| suitably for consumption by POSIX shells. argument may be quoted and escaped as necessary to ensure that POSIX shells treat the returned value as a literal representing the argument passed to this function. Parameter (variable) expansions beginning with $ are allowed to remain intact without escaping the $, to allow the argument to contain references to variables to be expanded by the shell. """ if not isinstance(argument, str): argument = str(argument) quote = '"' if _quote.search(argument) else "" encoded = quote + re.sub(_escape, r"\\\1", argument) + quote return encoded def EncodePOSIXShellList(list): """Encodes |list| suitably for consumption by POSIX shells. Returns EncodePOSIXShellArgument for each item in list, and joins them together using the space character as an argument separator. """ encoded_arguments = [] for argument in list: encoded_arguments.append(EncodePOSIXShellArgument(argument)) return " ".join(encoded_arguments) def DeepDependencyTargets(target_dicts, roots): """Returns the recursive list of target dependencies.""" dependencies = set() pending = set(roots) while pending: # Pluck out one. r = pending.pop() # Skip if visited already. if r in dependencies: continue # Add it. dependencies.add(r) # Add its children. spec = target_dicts[r] pending.update(set(spec.get("dependencies", []))) pending.update(set(spec.get("dependencies_original", []))) return list(dependencies - set(roots)) def BuildFileTargets(target_list, build_file): """From a target_list, returns the subset from the specified build_file. """ return [p for p in target_list if BuildFile(p) == build_file] def AllTargets(target_list, target_dicts, build_file): """Returns all targets (direct and dependencies) for the specified build_file. """ bftargets = BuildFileTargets(target_list, build_file) deptargets = DeepDependencyTargets(target_dicts, bftargets) return bftargets + deptargets def WriteOnDiff(filename): """Write to a file only if the new contents differ. Arguments: filename: name of the file to potentially write to. Returns: A file like object which will write to temporary file and only overwrite the target if it differs (on close). """ class Writer: """Wrapper around file which only covers the target if it differs.""" def __init__(self): # On Cygwin remove the "dir" argument # `C:` prefixed paths are treated as relative, # consequently ending up with current dir "/cygdrive/c/..." # being prefixed to those, which was # obviously a non-existent path, # for example: "/cygdrive/c//C:\". # For more details see: # https://docs.python.org/2/library/tempfile.html#tempfile.mkstemp base_temp_dir = "" if IsCygwin() else os.path.dirname(filename) # Pick temporary file. tmp_fd, self.tmp_path = tempfile.mkstemp( suffix=".tmp", prefix=os.path.split(filename)[1] + ".gyp.", dir=base_temp_dir, ) try: self.tmp_file = os.fdopen(tmp_fd, "wb") except Exception: # Don't leave turds behind. os.unlink(self.tmp_path) raise def __getattr__(self, attrname): # Delegate everything else to self.tmp_file return getattr(self.tmp_file, attrname) def close(self): try: # Close tmp file. self.tmp_file.close() # Determine if different. same = False try: same = filecmp.cmp(self.tmp_path, filename, False) except OSError as e: if e.errno != errno.ENOENT: raise if same: # The new file is identical to the old one, just get rid of the new # one. os.unlink(self.tmp_path) else: # The new file is different from the old one, # or there is no old one. # Rename the new file to the permanent name. # # tempfile.mkstemp uses an overly restrictive mode, resulting in a # file that can only be read by the owner, regardless of the umask. # There's no reason to not respect the umask here, # which means that an extra hoop is required # to fetch it and reset the new file's mode. # # No way to get the umask without setting a new one? Set a safe one # and then set it back to the old value. umask = os.umask(0o77) os.umask(umask) os.chmod(self.tmp_path, 0o666 & ~umask) if sys.platform == "win32" and os.path.exists(filename): # NOTE: on windows (but not cygwin) rename will not replace an # existing file, so it must be preceded with a remove. # Sadly there is no way to make the switch atomic. os.remove(filename) os.rename(self.tmp_path, filename) except Exception: # Don't leave turds behind. os.unlink(self.tmp_path) raise def write(self, s): self.tmp_file.write(s.encode("utf-8")) return Writer() def EnsureDirExists(path): """Make sure the directory for |path| exists.""" try: os.makedirs(os.path.dirname(path)) except OSError: pass def GetFlavor(params): """Returns |params.flavor| if it's set, the system's default flavor else.""" flavors = { "cygwin": "win", "win32": "win", "darwin": "mac", } if "flavor" in params: return params["flavor"] if sys.platform in flavors: return flavors[sys.platform] if sys.platform.startswith("sunos"): return "solaris" if sys.platform.startswith(("dragonfly", "freebsd")): return "freebsd" if sys.platform.startswith("openbsd"): return "openbsd" if sys.platform.startswith("netbsd"): return "netbsd" if sys.platform.startswith("aix"): return "aix" if sys.platform.startswith(("os390", "zos")): return "zos" if sys.platform == "os400": return "os400" return "linux" def CopyTool(flavor, out_path, generator_flags={}): """Finds (flock|mac|win)_tool.gyp in the gyp directory and copies it to |out_path|.""" # aix and solaris just need flock emulation. mac and win use more complicated # support scripts. prefix = { "aix": "flock", "os400": "flock", "solaris": "flock", "mac": "mac", "ios": "mac", "win": "win", }.get(flavor, None) if not prefix: return # Slurp input file. source_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), "%s_tool.py" % prefix ) with open(source_path) as source_file: source = source_file.readlines() # Set custom header flags. header = "# Generated by gyp. Do not edit.\n" mac_toolchain_dir = generator_flags.get("mac_toolchain_dir", None) if flavor == "mac" and mac_toolchain_dir: header += "import os;\nos.environ['DEVELOPER_DIR']='%s'\n" % mac_toolchain_dir # Add header and write it out. tool_path = os.path.join(out_path, "gyp-%s-tool" % prefix) with open(tool_path, "w") as tool_file: tool_file.write("".join([source[0], header] + source[1:])) # Make file executable. os.chmod(tool_path, 0o755) # From Alex Martelli, # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560 # ASPN: Python Cookbook: Remove duplicates from a sequence # First comment, dated 2001/10/13. # (Also in the printed Python Cookbook.) def uniquer(seq, idfun=lambda x: x): seen = {} result = [] for item in seq: marker = idfun(item) if marker in seen: continue seen[marker] = 1 result.append(item) return result # Based on http://code.activestate.com/recipes/576694/. class OrderedSet(MutableSet): def __init__(self, iterable=None): self.end = end = [] end += [None, end, end] # sentinel node for doubly linked list self.map = {} # key --> [key, prev, next] if iterable is not None: self |= iterable def __len__(self): return len(self.map) def __contains__(self, key): return key in self.map def add(self, key): if key not in self.map: end = self.end curr = end[1] curr[2] = end[1] = self.map[key] = [key, curr, end] def discard(self, key): if key in self.map: key, prev_item, next_item = self.map.pop(key) prev_item[2] = next_item next_item[1] = prev_item def __iter__(self): end = self.end curr = end[2] while curr is not end: yield curr[0] curr = curr[2] def __reversed__(self): end = self.end curr = end[1] while curr is not end: yield curr[0] curr = curr[1] # The second argument is an addition that causes a pylint warning. def pop(self, last=True): # pylint: disable=W0221 if not self: raise KeyError("set is empty") key = self.end[1][0] if last else self.end[2][0] self.discard(key) return key def __repr__(self): if not self: return f"{self.__class__.__name__}()" return f"{self.__class__.__name__}({list(self)!r})" def __eq__(self, other): if isinstance(other, OrderedSet): return len(self) == len(other) and list(self) == list(other) return set(self) == set(other) # Extensions to the recipe. def update(self, iterable): for i in iterable: if i not in self: self.add(i) class CycleError(Exception): """An exception raised when an unexpected cycle is detected.""" def __init__(self, nodes): self.nodes = nodes def __str__(self): return "CycleError: cycle involving: " + str(self.nodes) def TopologicallySorted(graph, get_edges): r"""Topologically sort based on a user provided edge definition. Args: graph: A list of node names. get_edges: A function mapping from node name to a hashable collection of node names which this node has outgoing edges to. Returns: A list containing all of the node in graph in topological order. It is assumed that calling get_edges once for each node and caching is cheaper than repeatedly calling get_edges. Raises: CycleError in the event of a cycle. Example: graph = {'a': '$(b) $(c)', 'b': 'hi', 'c': '$(b)'} def GetEdges(node): return re.findall(r'\$\(([^))]\)', graph[node]) print TopologicallySorted(graph.keys(), GetEdges) ==> ['a', 'c', b'] """ get_edges = memoize(get_edges) visited = set() visiting = set() ordered_nodes = [] def Visit(node): if node in visiting: raise CycleError(visiting) if node in visited: return visited.add(node) visiting.add(node) for neighbor in get_edges(node): Visit(neighbor) visiting.remove(node) ordered_nodes.insert(0, node) for node in sorted(graph): Visit(node) return ordered_nodes def CrossCompileRequested(): # TODO: figure out how to not build extra host objects in the # non-cross-compile case when this is enabled, and enable unconditionally. return ( os.environ.get("GYP_CROSSCOMPILE") or os.environ.get("AR_host") or os.environ.get("CC_host") or os.environ.get("CXX_host") or os.environ.get("AR_target") or os.environ.get("CC_target") or os.environ.get("CXX_target") ) def IsCygwin(): try: out = subprocess.Popen( "uname", stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) stdout = out.communicate()[0].decode("utf-8") return "CYGWIN" in str(stdout) except Exception: return False PK ~\N&node-gyp/gyp/pylib/gyp/MSVSToolFile.pynu[# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Visual Studio project reader/writer.""" import gyp.easy_xml as easy_xml class Writer: """Visual Studio XML tool file writer.""" def __init__(self, tool_file_path, name): """Initializes the tool file. Args: tool_file_path: Path to the tool file. name: Name of the tool file. """ self.tool_file_path = tool_file_path self.name = name self.rules_section = ["Rules"] def AddCustomBuildRule( self, name, cmd, description, additional_dependencies, outputs, extensions ): """Adds a rule to the tool file. Args: name: Name of the rule. description: Description of the rule. cmd: Command line of the rule. additional_dependencies: other files which may trigger the rule. outputs: outputs of the rule. extensions: extensions handled by the rule. """ rule = [ "CustomBuildRule", { "Name": name, "ExecutionDescription": description, "CommandLine": cmd, "Outputs": ";".join(outputs), "FileExtensions": ";".join(extensions), "AdditionalDependencies": ";".join(additional_dependencies), }, ] self.rules_section.append(rule) def WriteIfChanged(self): """Writes the tool file.""" content = [ "VisualStudioToolFile", {"Version": "8.00", "Name": self.name}, self.rules_section, ] easy_xml.WriteXmlIfChanged( content, self.tool_file_path, encoding="Windows-1252" ) PK ~\R;;"node-gyp/gyp/pylib/gyp/win_tool.pynu[#!/usr/bin/env python3 # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Utility functions for Windows builds. These functions are executed via gyp-win-tool when using the ninja generator. """ import os import re import shutil import subprocess import stat import string import sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # A regex matching an argument corresponding to the output filename passed to # link.exe. _LINK_EXE_OUT_ARG = re.compile("/OUT:(?P.+)$", re.IGNORECASE) def main(args): executor = WinTool() exit_code = executor.Dispatch(args) if exit_code is not None: sys.exit(exit_code) class WinTool: """This class performs all the Windows tooling steps. The methods can either be executed directly, or dispatched from an argument list.""" def _UseSeparateMspdbsrv(self, env, args): """Allows to use a unique instance of mspdbsrv.exe per linker instead of a shared one.""" if len(args) < 1: raise Exception("Not enough arguments") if args[0] != "link.exe": return # Use the output filename passed to the linker to generate an endpoint name # for mspdbsrv.exe. endpoint_name = None for arg in args: m = _LINK_EXE_OUT_ARG.match(arg) if m: endpoint_name = re.sub( r"\W+", "", "%s_%d" % (m.group("out"), os.getpid()) ) break if endpoint_name is None: return # Adds the appropriate environment variable. This will be read by link.exe # to know which instance of mspdbsrv.exe it should connect to (if it's # not set then the default endpoint is used). env["_MSPDBSRV_ENDPOINT_"] = endpoint_name def Dispatch(self, args): """Dispatches a string command to a method.""" if len(args) < 1: raise Exception("Not enough arguments") method = "Exec%s" % self._CommandifyName(args[0]) return getattr(self, method)(*args[1:]) def _CommandifyName(self, name_string): """Transforms a tool name like recursive-mirror to RecursiveMirror.""" return name_string.title().replace("-", "") def _GetEnv(self, arch): """Gets the saved environment from a file for a given architecture.""" # The environment is saved as an "environment block" (see CreateProcess # and msvs_emulation for details). We convert to a dict here. # Drop last 2 NULs, one for list terminator, one for trailing vs. separator. pairs = open(arch).read()[:-2].split("\0") kvs = [item.split("=", 1) for item in pairs] return dict(kvs) def ExecStamp(self, path): """Simple stamp command.""" open(path, "w").close() def ExecRecursiveMirror(self, source, dest): """Emulation of rm -rf out && cp -af in out.""" if os.path.exists(dest): if os.path.isdir(dest): def _on_error(fn, path, excinfo): # The operation failed, possibly because the file is set to # read-only. If that's why, make it writable and try the op again. if not os.access(path, os.W_OK): os.chmod(path, stat.S_IWRITE) fn(path) shutil.rmtree(dest, onerror=_on_error) else: if not os.access(dest, os.W_OK): # Attempt to make the file writable before deleting it. os.chmod(dest, stat.S_IWRITE) os.unlink(dest) if os.path.isdir(source): shutil.copytree(source, dest) else: shutil.copy2(source, dest) def ExecLinkWrapper(self, arch, use_separate_mspdbsrv, *args): """Filter diagnostic output from link that looks like: ' Creating library ui.dll.lib and object ui.dll.exp' This happens when there are exports from the dll or exe. """ env = self._GetEnv(arch) if use_separate_mspdbsrv == "True": self._UseSeparateMspdbsrv(env, args) if sys.platform == "win32": args = list(args) # *args is a tuple by default, which is read-only. args[0] = args[0].replace("/", "\\") # https://docs.python.org/2/library/subprocess.html: # "On Unix with shell=True [...] if args is a sequence, the first item # specifies the command string, and any additional items will be treated as # additional arguments to the shell itself. That is to say, Popen does the # equivalent of: # Popen(['/bin/sh', '-c', args[0], args[1], ...])" # For that reason, since going through the shell doesn't seem necessary on # non-Windows don't do that there. link = subprocess.Popen( args, shell=sys.platform == "win32", env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) out = link.communicate()[0].decode("utf-8") for line in out.splitlines(): if ( not line.startswith(" Creating library ") and not line.startswith("Generating code") and not line.startswith("Finished generating code") ): print(line) return link.returncode def ExecLinkWithManifests( self, arch, embed_manifest, out, ldcmd, resname, mt, rc, intermediate_manifest, *manifests ): """A wrapper for handling creating a manifest resource and then executing a link command.""" # The 'normal' way to do manifests is to have link generate a manifest # based on gathering dependencies from the object files, then merge that # manifest with other manifests supplied as sources, convert the merged # manifest to a resource, and then *relink*, including the compiled # version of the manifest resource. This breaks incremental linking, and # is generally overly complicated. Instead, we merge all the manifests # provided (along with one that includes what would normally be in the # linker-generated one, see msvs_emulation.py), and include that into the # first and only link. We still tell link to generate a manifest, but we # only use that to assert that our simpler process did not miss anything. variables = { "python": sys.executable, "arch": arch, "out": out, "ldcmd": ldcmd, "resname": resname, "mt": mt, "rc": rc, "intermediate_manifest": intermediate_manifest, "manifests": " ".join(manifests), } add_to_ld = "" if manifests: subprocess.check_call( "%(python)s gyp-win-tool manifest-wrapper %(arch)s %(mt)s -nologo " "-manifest %(manifests)s -out:%(out)s.manifest" % variables ) if embed_manifest == "True": subprocess.check_call( "%(python)s gyp-win-tool manifest-to-rc %(arch)s %(out)s.manifest" " %(out)s.manifest.rc %(resname)s" % variables ) subprocess.check_call( "%(python)s gyp-win-tool rc-wrapper %(arch)s %(rc)s " "%(out)s.manifest.rc" % variables ) add_to_ld = " %(out)s.manifest.res" % variables subprocess.check_call(ldcmd + add_to_ld) # Run mt.exe on the theoretically complete manifest we generated, merging # it with the one the linker generated to confirm that the linker # generated one does not add anything. This is strictly unnecessary for # correctness, it's only to verify that e.g. /MANIFESTDEPENDENCY was not # used in a #pragma comment. if manifests: # Merge the intermediate one with ours to .assert.manifest, then check # that .assert.manifest is identical to ours. subprocess.check_call( "%(python)s gyp-win-tool manifest-wrapper %(arch)s %(mt)s -nologo " "-manifest %(out)s.manifest %(intermediate_manifest)s " "-out:%(out)s.assert.manifest" % variables ) assert_manifest = "%(out)s.assert.manifest" % variables our_manifest = "%(out)s.manifest" % variables # Load and normalize the manifests. mt.exe sometimes removes whitespace, # and sometimes doesn't unfortunately. with open(our_manifest) as our_f, open(assert_manifest) as assert_f: translator = str.maketrans("", "", string.whitespace) our_data = our_f.read().translate(translator) assert_data = assert_f.read().translate(translator) if our_data != assert_data: os.unlink(out) def dump(filename): print(filename, file=sys.stderr) print("-----", file=sys.stderr) with open(filename) as f: print(f.read(), file=sys.stderr) print("-----", file=sys.stderr) dump(intermediate_manifest) dump(our_manifest) dump(assert_manifest) sys.stderr.write( 'Linker generated manifest "%s" added to final manifest "%s" ' '(result in "%s"). ' "Were /MANIFEST switches used in #pragma statements? " % (intermediate_manifest, our_manifest, assert_manifest) ) return 1 def ExecManifestWrapper(self, arch, *args): """Run manifest tool with environment set. Strip out undesirable warning (some XML blocks are recognized by the OS loader, but not the manifest tool).""" env = self._GetEnv(arch) popen = subprocess.Popen( args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) out = popen.communicate()[0].decode("utf-8") for line in out.splitlines(): if line and "manifest authoring warning 81010002" not in line: print(line) return popen.returncode def ExecManifestToRc(self, arch, *args): """Creates a resource file pointing a SxS assembly manifest. |args| is tuple containing path to resource file, path to manifest file and resource name which can be "1" (for executables) or "2" (for DLLs).""" manifest_path, resource_path, resource_name = args with open(resource_path, "w") as output: output.write( '#include \n%s RT_MANIFEST "%s"' % (resource_name, os.path.abspath(manifest_path).replace("\\", "/")) ) def ExecMidlWrapper(self, arch, outdir, tlb, h, dlldata, iid, proxy, idl, *flags): """Filter noisy filenames output from MIDL compile step that isn't quietable via command line flags. """ args = ( ["midl", "/nologo"] + list(flags) + [ "/out", outdir, "/tlb", tlb, "/h", h, "/dlldata", dlldata, "/iid", iid, "/proxy", proxy, idl, ] ) env = self._GetEnv(arch) popen = subprocess.Popen( args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) out = popen.communicate()[0].decode("utf-8") # Filter junk out of stdout, and write filtered versions. Output we want # to filter is pairs of lines that look like this: # Processing C:\Program Files (x86)\Microsoft SDKs\...\include\objidl.idl # objidl.idl lines = out.splitlines() prefixes = ("Processing ", "64 bit Processing ") processing = {os.path.basename(x) for x in lines if x.startswith(prefixes)} for line in lines: if not line.startswith(prefixes) and line not in processing: print(line) return popen.returncode def ExecAsmWrapper(self, arch, *args): """Filter logo banner from invocations of asm.exe.""" env = self._GetEnv(arch) popen = subprocess.Popen( args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) out = popen.communicate()[0].decode("utf-8") for line in out.splitlines(): if ( not line.startswith("Copyright (C) Microsoft Corporation") and not line.startswith("Microsoft (R) Macro Assembler") and not line.startswith(" Assembling: ") and line ): print(line) return popen.returncode def ExecRcWrapper(self, arch, *args): """Filter logo banner from invocations of rc.exe. Older versions of RC don't support the /nologo flag.""" env = self._GetEnv(arch) popen = subprocess.Popen( args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) out = popen.communicate()[0].decode("utf-8") for line in out.splitlines(): if ( not line.startswith("Microsoft (R) Windows (R) Resource Compiler") and not line.startswith("Copyright (C) Microsoft Corporation") and line ): print(line) return popen.returncode def ExecActionWrapper(self, arch, rspfile, *dir): """Runs an action command line from a response file using the environment for |arch|. If |dir| is supplied, use that as the working directory.""" env = self._GetEnv(arch) # TODO(scottmg): This is a temporary hack to get some specific variables # through to actions that are set after gyp-time. http://crbug.com/333738. for k, v in os.environ.items(): if k not in env: env[k] = v args = open(rspfile).read() dir = dir[0] if dir else None return subprocess.call(args, shell=True, env=env, cwd=dir) def ExecClCompile(self, project_dir, selected_files): """Executed by msvs-ninja projects when the 'ClCompile' target is used to build selected C/C++ files.""" project_dir = os.path.relpath(project_dir, BASE_DIR) selected_files = selected_files.split(";") ninja_targets = [ os.path.join(project_dir, filename) + "^^" for filename in selected_files ] cmd = ["ninja.exe"] cmd.extend(ninja_targets) return subprocess.call(cmd, shell=True, cwd=BASE_DIR) if __name__ == "__main__": sys.exit(main(sys.argv[1:])) PK ~\lMM%node-gyp/gyp/pylib/gyp/MSVSVersion.pynu[# Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Handle version information related to Visual Stuio.""" import errno import os import re import subprocess import sys import glob def JoinPath(*args): return os.path.normpath(os.path.join(*args)) class VisualStudioVersion: """Information regarding a version of Visual Studio.""" def __init__( self, short_name, description, solution_version, project_version, flat_sln, uses_vcxproj, path, sdk_based, default_toolset=None, compatible_sdks=None, ): self.short_name = short_name self.description = description self.solution_version = solution_version self.project_version = project_version self.flat_sln = flat_sln self.uses_vcxproj = uses_vcxproj self.path = path self.sdk_based = sdk_based self.default_toolset = default_toolset compatible_sdks = compatible_sdks or [] compatible_sdks.sort(key=lambda v: float(v.replace("v", "")), reverse=True) self.compatible_sdks = compatible_sdks def ShortName(self): return self.short_name def Description(self): """Get the full description of the version.""" return self.description def SolutionVersion(self): """Get the version number of the sln files.""" return self.solution_version def ProjectVersion(self): """Get the version number of the vcproj or vcxproj files.""" return self.project_version def FlatSolution(self): return self.flat_sln def UsesVcxproj(self): """Returns true if this version uses a vcxproj file.""" return self.uses_vcxproj def ProjectExtension(self): """Returns the file extension for the project.""" return self.uses_vcxproj and ".vcxproj" or ".vcproj" def Path(self): """Returns the path to Visual Studio installation.""" return self.path def ToolPath(self, tool): """Returns the path to a given compiler tool. """ return os.path.normpath(os.path.join(self.path, "VC/bin", tool)) def DefaultToolset(self): """Returns the msbuild toolset version that will be used in the absence of a user override.""" return self.default_toolset def _SetupScriptInternal(self, target_arch): """Returns a command (with arguments) to be used to set up the environment.""" assert target_arch in ("x86", "x64"), "target_arch not supported" # If WindowsSDKDir is set and SetEnv.Cmd exists then we are using the # depot_tools build tools and should run SetEnv.Cmd to set up the # environment. The check for WindowsSDKDir alone is not sufficient because # this is set by running vcvarsall.bat. sdk_dir = os.environ.get("WindowsSDKDir", "") setup_path = JoinPath(sdk_dir, "Bin", "SetEnv.Cmd") if self.sdk_based and sdk_dir and os.path.exists(setup_path): return [setup_path, "/" + target_arch] is_host_arch_x64 = ( os.environ.get("PROCESSOR_ARCHITECTURE") == "AMD64" or os.environ.get("PROCESSOR_ARCHITEW6432") == "AMD64" ) # For VS2017 (and newer) it's fairly easy if self.short_name >= "2017": script_path = JoinPath( self.path, "VC", "Auxiliary", "Build", "vcvarsall.bat" ) # Always use a native executable, cross-compiling if necessary. host_arch = "amd64" if is_host_arch_x64 else "x86" msvc_target_arch = "amd64" if target_arch == "x64" else "x86" arg = host_arch if host_arch != msvc_target_arch: arg += "_" + msvc_target_arch return [script_path, arg] # We try to find the best version of the env setup batch. vcvarsall = JoinPath(self.path, "VC", "vcvarsall.bat") if target_arch == "x86": if ( self.short_name >= "2013" and self.short_name[-1] != "e" and is_host_arch_x64 ): # VS2013 and later, non-Express have a x64-x86 cross that we want # to prefer. return [vcvarsall, "amd64_x86"] else: # Otherwise, the standard x86 compiler. We don't use VC/vcvarsall.bat # for x86 because vcvarsall calls vcvars32, which it can only find if # VS??COMNTOOLS is set, which isn't guaranteed. return [JoinPath(self.path, "Common7", "Tools", "vsvars32.bat")] elif target_arch == "x64": arg = "x86_amd64" # Use the 64-on-64 compiler if we're not using an express edition and # we're running on a 64bit OS. if self.short_name[-1] != "e" and is_host_arch_x64: arg = "amd64" return [vcvarsall, arg] def SetupScript(self, target_arch): script_data = self._SetupScriptInternal(target_arch) script_path = script_data[0] if not os.path.exists(script_path): raise Exception( "%s is missing - make sure VC++ tools are installed." % script_path ) return script_data def _RegistryQueryBase(sysdir, key, value): """Use reg.exe to read a particular key. While ideally we might use the win32 module, we would like gyp to be python neutral, so for instance cygwin python lacks this module. Arguments: sysdir: The system subdirectory to attempt to launch reg.exe from. key: The registry key to read from. value: The particular value to read. Return: stdout from reg.exe, or None for failure. """ # Skip if not on Windows or Python Win32 setup issue if sys.platform not in ("win32", "cygwin"): return None # Setup params to pass to and attempt to launch reg.exe cmd = [os.path.join(os.environ.get("WINDIR", ""), sysdir, "reg.exe"), "query", key] if value: cmd.extend(["/v", value]) p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Obtain the stdout from reg.exe, reading to the end so p.returncode is valid # Note that the error text may be in [1] in some cases text = p.communicate()[0].decode("utf-8") # Check return code from reg.exe; officially 0==success and 1==error if p.returncode: return None return text def _RegistryQuery(key, value=None): r"""Use reg.exe to read a particular key through _RegistryQueryBase. First tries to launch from %WinDir%\Sysnative to avoid WoW64 redirection. If that fails, it falls back to System32. Sysnative is available on Vista and up and available on Windows Server 2003 and XP through KB patch 942589. Note that Sysnative will always fail if using 64-bit python due to it being a virtual directory and System32 will work correctly in the first place. KB 942589 - http://support.microsoft.com/kb/942589/en-us. Arguments: key: The registry key. value: The particular registry value to read (optional). Return: stdout from reg.exe, or None for failure. """ text = None try: text = _RegistryQueryBase("Sysnative", key, value) except OSError as e: if e.errno == errno.ENOENT: text = _RegistryQueryBase("System32", key, value) else: raise return text def _RegistryGetValueUsingWinReg(key, value): """Use the _winreg module to obtain the value of a registry key. Args: key: The registry key. value: The particular registry value to read. Return: contents of the registry key's value, or None on failure. Throws ImportError if winreg is unavailable. """ from winreg import HKEY_LOCAL_MACHINE, OpenKey, QueryValueEx try: root, subkey = key.split("\\", 1) assert root == "HKLM" # Only need HKLM for now. with OpenKey(HKEY_LOCAL_MACHINE, subkey) as hkey: return QueryValueEx(hkey, value)[0] except OSError: return None def _RegistryGetValue(key, value): """Use _winreg or reg.exe to obtain the value of a registry key. Using _winreg is preferable because it solves an issue on some corporate environments where access to reg.exe is locked down. However, we still need to fallback to reg.exe for the case where the _winreg module is not available (for example in cygwin python). Args: key: The registry key. value: The particular registry value to read. Return: contents of the registry key's value, or None on failure. """ try: return _RegistryGetValueUsingWinReg(key, value) except ImportError: pass # Fallback to reg.exe if we fail to import _winreg. text = _RegistryQuery(key, value) if not text: return None # Extract value. match = re.search(r"REG_\w+\s+([^\r]+)\r\n", text) if not match: return None return match.group(1) def _CreateVersion(name, path, sdk_based=False): """Sets up MSVS project generation. Setup is based off the GYP_MSVS_VERSION environment variable or whatever is autodetected if GYP_MSVS_VERSION is not explicitly specified. If a version is passed in that doesn't match a value in versions python will throw a error. """ if path: path = os.path.normpath(path) versions = { "2022": VisualStudioVersion( "2022", "Visual Studio 2022", solution_version="12.00", project_version="17.0", flat_sln=False, uses_vcxproj=True, path=path, sdk_based=sdk_based, default_toolset="v143", compatible_sdks=["v8.1", "v10.0"], ), "2019": VisualStudioVersion( "2019", "Visual Studio 2019", solution_version="12.00", project_version="16.0", flat_sln=False, uses_vcxproj=True, path=path, sdk_based=sdk_based, default_toolset="v142", compatible_sdks=["v8.1", "v10.0"], ), "2017": VisualStudioVersion( "2017", "Visual Studio 2017", solution_version="12.00", project_version="15.0", flat_sln=False, uses_vcxproj=True, path=path, sdk_based=sdk_based, default_toolset="v141", compatible_sdks=["v8.1", "v10.0"], ), "2015": VisualStudioVersion( "2015", "Visual Studio 2015", solution_version="12.00", project_version="14.0", flat_sln=False, uses_vcxproj=True, path=path, sdk_based=sdk_based, default_toolset="v140", ), "2013": VisualStudioVersion( "2013", "Visual Studio 2013", solution_version="13.00", project_version="12.0", flat_sln=False, uses_vcxproj=True, path=path, sdk_based=sdk_based, default_toolset="v120", ), "2013e": VisualStudioVersion( "2013e", "Visual Studio 2013", solution_version="13.00", project_version="12.0", flat_sln=True, uses_vcxproj=True, path=path, sdk_based=sdk_based, default_toolset="v120", ), "2012": VisualStudioVersion( "2012", "Visual Studio 2012", solution_version="12.00", project_version="4.0", flat_sln=False, uses_vcxproj=True, path=path, sdk_based=sdk_based, default_toolset="v110", ), "2012e": VisualStudioVersion( "2012e", "Visual Studio 2012", solution_version="12.00", project_version="4.0", flat_sln=True, uses_vcxproj=True, path=path, sdk_based=sdk_based, default_toolset="v110", ), "2010": VisualStudioVersion( "2010", "Visual Studio 2010", solution_version="11.00", project_version="4.0", flat_sln=False, uses_vcxproj=True, path=path, sdk_based=sdk_based, ), "2010e": VisualStudioVersion( "2010e", "Visual C++ Express 2010", solution_version="11.00", project_version="4.0", flat_sln=True, uses_vcxproj=True, path=path, sdk_based=sdk_based, ), "2008": VisualStudioVersion( "2008", "Visual Studio 2008", solution_version="10.00", project_version="9.00", flat_sln=False, uses_vcxproj=False, path=path, sdk_based=sdk_based, ), "2008e": VisualStudioVersion( "2008e", "Visual Studio 2008", solution_version="10.00", project_version="9.00", flat_sln=True, uses_vcxproj=False, path=path, sdk_based=sdk_based, ), "2005": VisualStudioVersion( "2005", "Visual Studio 2005", solution_version="9.00", project_version="8.00", flat_sln=False, uses_vcxproj=False, path=path, sdk_based=sdk_based, ), "2005e": VisualStudioVersion( "2005e", "Visual Studio 2005", solution_version="9.00", project_version="8.00", flat_sln=True, uses_vcxproj=False, path=path, sdk_based=sdk_based, ), } return versions[str(name)] def _ConvertToCygpath(path): """Convert to cygwin path if we are using cygwin.""" if sys.platform == "cygwin": p = subprocess.Popen(["cygpath", path], stdout=subprocess.PIPE) path = p.communicate()[0].decode("utf-8").strip() return path def _DetectVisualStudioVersions(versions_to_check, force_express): """Collect the list of installed visual studio versions. Returns: A list of visual studio versions installed in descending order of usage preference. Base this on the registry and a quick check if devenv.exe exists. Possibilities are: 2005(e) - Visual Studio 2005 (8) 2008(e) - Visual Studio 2008 (9) 2010(e) - Visual Studio 2010 (10) 2012(e) - Visual Studio 2012 (11) 2013(e) - Visual Studio 2013 (12) 2015 - Visual Studio 2015 (14) 2017 - Visual Studio 2017 (15) 2019 - Visual Studio 2019 (16) 2022 - Visual Studio 2022 (17) Where (e) is e for express editions of MSVS and blank otherwise. """ version_to_year = { "8.0": "2005", "9.0": "2008", "10.0": "2010", "11.0": "2012", "12.0": "2013", "14.0": "2015", "15.0": "2017", "16.0": "2019", "17.0": "2022", } versions = [] for version in versions_to_check: # Old method of searching for which VS version is installed # We don't use the 2010-encouraged-way because we also want to get the # path to the binaries, which it doesn't offer. keys = [ r"HKLM\Software\Microsoft\VisualStudio\%s" % version, r"HKLM\Software\Wow6432Node\Microsoft\VisualStudio\%s" % version, r"HKLM\Software\Microsoft\VCExpress\%s" % version, r"HKLM\Software\Wow6432Node\Microsoft\VCExpress\%s" % version, ] for index in range(len(keys)): path = _RegistryGetValue(keys[index], "InstallDir") if not path: continue path = _ConvertToCygpath(path) # Check for full. full_path = os.path.join(path, "devenv.exe") express_path = os.path.join(path, "*express.exe") if not force_express and os.path.exists(full_path): # Add this one. versions.append( _CreateVersion( version_to_year[version], os.path.join(path, "..", "..") ) ) # Check for express. elif glob.glob(express_path): # Add this one. versions.append( _CreateVersion( version_to_year[version] + "e", os.path.join(path, "..", "..") ) ) # The old method above does not work when only SDK is installed. keys = [ r"HKLM\Software\Microsoft\VisualStudio\SxS\VC7", r"HKLM\Software\Wow6432Node\Microsoft\VisualStudio\SxS\VC7", r"HKLM\Software\Microsoft\VisualStudio\SxS\VS7", r"HKLM\Software\Wow6432Node\Microsoft\VisualStudio\SxS\VS7", ] for index in range(len(keys)): path = _RegistryGetValue(keys[index], version) if not path: continue path = _ConvertToCygpath(path) if version == "15.0": if os.path.exists(path): versions.append(_CreateVersion("2017", path)) elif version != "14.0": # There is no Express edition for 2015. versions.append( _CreateVersion( version_to_year[version] + "e", os.path.join(path, ".."), sdk_based=True, ) ) return versions def SelectVisualStudioVersion(version="auto", allow_fallback=True): """Select which version of Visual Studio projects to generate. Arguments: version: Hook to allow caller to force a particular version (vs auto). Returns: An object representing a visual studio project format version. """ # In auto mode, check environment variable for override. if version == "auto": version = os.environ.get("GYP_MSVS_VERSION", "auto") version_map = { "auto": ("17.0", "16.0", "15.0", "14.0", "12.0", "10.0", "9.0", "8.0", "11.0"), "2005": ("8.0",), "2005e": ("8.0",), "2008": ("9.0",), "2008e": ("9.0",), "2010": ("10.0",), "2010e": ("10.0",), "2012": ("11.0",), "2012e": ("11.0",), "2013": ("12.0",), "2013e": ("12.0",), "2015": ("14.0",), "2017": ("15.0",), "2019": ("16.0",), "2022": ("17.0",), } override_path = os.environ.get("GYP_MSVS_OVERRIDE_PATH") if override_path: msvs_version = os.environ.get("GYP_MSVS_VERSION") if not msvs_version: raise ValueError( "GYP_MSVS_OVERRIDE_PATH requires GYP_MSVS_VERSION to be " "set to a particular version (e.g. 2010e)." ) return _CreateVersion(msvs_version, override_path, sdk_based=True) version = str(version) versions = _DetectVisualStudioVersions(version_map[version], "e" in version) if not versions: if not allow_fallback: raise ValueError("Could not locate Visual Studio installation.") if version == "auto": # Default to 2005 if we couldn't find anything return _CreateVersion("2005", None) else: return _CreateVersion(version, None) return versions[0] PK ~\>xKy11"node-gyp/gyp/pylib/gyp/easy_xml.pynu[# Copyright (c) 2011 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import sys import re import os import locale from functools import reduce def XmlToString(content, encoding="utf-8", pretty=False): """ Writes the XML content to disk, touching the file only if it has changed. Visual Studio files have a lot of pre-defined structures. This function makes it easy to represent these structures as Python data structures, instead of having to create a lot of function calls. Each XML element of the content is represented as a list composed of: 1. The name of the element, a string, 2. The attributes of the element, a dictionary (optional), and 3+. The content of the element, if any. Strings are simple text nodes and lists are child elements. Example 1: becomes ['test'] Example 2: This is it! becomes ['myelement', {'a':'value1', 'b':'value2'}, ['childtype', 'This is'], ['childtype', 'it!'], ] Args: content: The structured content to be converted. encoding: The encoding to report on the first XML line. pretty: True if we want pretty printing with indents and new lines. Returns: The XML content as a string. """ # We create a huge list of all the elements of the file. xml_parts = ['' % encoding] if pretty: xml_parts.append("\n") _ConstructContentList(xml_parts, content, pretty) # Convert it to a string return "".join(xml_parts) def _ConstructContentList(xml_parts, specification, pretty, level=0): """ Appends the XML parts corresponding to the specification. Args: xml_parts: A list of XML parts to be appended to. specification: The specification of the element. See EasyXml docs. pretty: True if we want pretty printing with indents and new lines. level: Indentation level. """ # The first item in a specification is the name of the element. if pretty: indentation = " " * level new_line = "\n" else: indentation = "" new_line = "" name = specification[0] if not isinstance(name, str): raise Exception( "The first item of an EasyXml specification should be " "a string. Specification was " + str(specification) ) xml_parts.append(indentation + "<" + name) # Optionally in second position is a dictionary of the attributes. rest = specification[1:] if rest and isinstance(rest[0], dict): for at, val in sorted(rest[0].items()): xml_parts.append(f' {at}="{_XmlEscape(val, attr=True)}"') rest = rest[1:] if rest: xml_parts.append(">") all_strings = reduce(lambda x, y: x and isinstance(y, str), rest, True) multi_line = not all_strings if multi_line and new_line: xml_parts.append(new_line) for child_spec in rest: # If it's a string, append a text node. # Otherwise recurse over that child definition if isinstance(child_spec, str): xml_parts.append(_XmlEscape(child_spec)) else: _ConstructContentList(xml_parts, child_spec, pretty, level + 1) if multi_line and indentation: xml_parts.append(indentation) xml_parts.append(f"{new_line}") else: xml_parts.append("/>%s" % new_line) def WriteXmlIfChanged(content, path, encoding="utf-8", pretty=False, win32=(sys.platform == "win32")): """ Writes the XML content to disk, touching the file only if it has changed. Args: content: The structured content to be written. path: Location of the file. encoding: The encoding to report on the first line of the XML file. pretty: True if we want pretty printing with indents and new lines. """ xml_string = XmlToString(content, encoding, pretty) if win32 and os.linesep != "\r\n": xml_string = xml_string.replace("\n", "\r\n") try: # getdefaultlocale() was removed in Python 3.11 default_encoding = locale.getdefaultlocale()[1] except AttributeError: default_encoding = locale.getencoding() if default_encoding and default_encoding.upper() != encoding.upper(): xml_string = xml_string.encode(encoding) # Get the old content try: with open(path) as file: existing = file.read() except OSError: existing = None # It has changed, write it if existing != xml_string: with open(path, "wb") as file: file.write(xml_string) _xml_escape_map = { '"': """, "'": "'", "<": "<", ">": ">", "&": "&", "\n": " ", "\r": " ", } _xml_escape_re = re.compile("(%s)" % "|".join(map(re.escape, _xml_escape_map.keys()))) def _XmlEscape(value, attr=False): """ Escape a string for inclusion in XML.""" def replace(match): m = match.string[match.start() : match.end()] # don't replace single quotes in attrs if attr and m == "'": return m return _xml_escape_map[m] return _xml_escape_re.sub(replace, value) PK ~\2!node-gyp/gyp/pylib/gyp/xml_fix.pynu[# Copyright (c) 2011 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Applies a fix to CR LF TAB handling in xml.dom. Fixes this: http://code.google.com/p/chromium/issues/detail?id=76293 Working around this: http://bugs.python.org/issue5752 TODO(bradnelson): Consider dropping this when we drop XP support. """ import xml.dom.minidom def _Replacement_write_data(writer, data, is_attrib=False): """Writes datachars to writer.""" data = data.replace("&", "&").replace("<", "<") data = data.replace('"', """).replace(">", ">") if is_attrib: data = data.replace("\r", " ").replace("\n", " ").replace("\t", " ") writer.write(data) def _Replacement_writexml(self, writer, indent="", addindent="", newl=""): # indent = current indentation # addindent = indentation to add to higher levels # newl = newline string writer.write(indent + "<" + self.tagName) attrs = self._get_attributes() a_names = sorted(attrs.keys()) for a_name in a_names: writer.write(' %s="' % a_name) _Replacement_write_data(writer, attrs[a_name].value, is_attrib=True) writer.write('"') if self.childNodes: writer.write(">%s" % newl) for node in self.childNodes: node.writexml(writer, indent + addindent, addindent, newl) writer.write(f"{indent}{newl}") else: writer.write("/>%s" % newl) class XmlFix: """Object to manage temporary patching of xml.dom.minidom.""" def __init__(self): # Preserve current xml.dom.minidom functions. self.write_data = xml.dom.minidom._write_data self.writexml = xml.dom.minidom.Element.writexml # Inject replacement versions of a function and a method. xml.dom.minidom._write_data = _Replacement_write_data xml.dom.minidom.Element.writexml = _Replacement_writexml def Cleanup(self): if self.write_data: xml.dom.minidom._write_data = self.write_data xml.dom.minidom.Element.writexml = self.writexml self.write_data = None def __del__(self): self.Cleanup() PK ~\"T  %node-gyp/gyp/pylib/gyp/simple_copy.pynu[# Copyright 2014 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """A clone of the default copy.deepcopy that doesn't handle cyclic structures or complex types except for dicts and lists. This is because gyp copies so large structure that small copy overhead ends up taking seconds in a project the size of Chromium.""" class Error(Exception): pass __all__ = ["Error", "deepcopy"] def deepcopy(x): """Deep copy operation on gyp objects such as strings, ints, dicts and lists. More than twice as fast as copy.deepcopy but much less generic.""" try: return _deepcopy_dispatch[type(x)](x) except KeyError: raise Error( "Unsupported type %s for deepcopy. Use copy.deepcopy " + "or expand simple_copy support." % type(x) ) _deepcopy_dispatch = d = {} def _deepcopy_atomic(x): return x types = bool, float, int, str, type, type(None) for x in types: d[x] = _deepcopy_atomic def _deepcopy_list(x): return [deepcopy(a) for a in x] d[list] = _deepcopy_list def _deepcopy_dict(x): y = {} for key, value in x.items(): y[deepcopy(key)] = deepcopy(value) return y d[dict] = _deepcopy_dict del d PK ~\04a a $node-gyp/gyp/pylib/gyp/input_test.pynu[#!/usr/bin/env python3 # Copyright 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Unit tests for the input.py file.""" import gyp.input import unittest class TestFindCycles(unittest.TestCase): def setUp(self): self.nodes = {} for x in ("a", "b", "c", "d", "e"): self.nodes[x] = gyp.input.DependencyGraphNode(x) def _create_dependency(self, dependent, dependency): dependent.dependencies.append(dependency) dependency.dependents.append(dependent) def test_no_cycle_empty_graph(self): for label, node in self.nodes.items(): self.assertEqual([], node.FindCycles()) def test_no_cycle_line(self): self._create_dependency(self.nodes["a"], self.nodes["b"]) self._create_dependency(self.nodes["b"], self.nodes["c"]) self._create_dependency(self.nodes["c"], self.nodes["d"]) for label, node in self.nodes.items(): self.assertEqual([], node.FindCycles()) def test_no_cycle_dag(self): self._create_dependency(self.nodes["a"], self.nodes["b"]) self._create_dependency(self.nodes["a"], self.nodes["c"]) self._create_dependency(self.nodes["b"], self.nodes["c"]) for label, node in self.nodes.items(): self.assertEqual([], node.FindCycles()) def test_cycle_self_reference(self): self._create_dependency(self.nodes["a"], self.nodes["a"]) self.assertEqual( [[self.nodes["a"], self.nodes["a"]]], self.nodes["a"].FindCycles() ) def test_cycle_two_nodes(self): self._create_dependency(self.nodes["a"], self.nodes["b"]) self._create_dependency(self.nodes["b"], self.nodes["a"]) self.assertEqual( [[self.nodes["a"], self.nodes["b"], self.nodes["a"]]], self.nodes["a"].FindCycles(), ) self.assertEqual( [[self.nodes["b"], self.nodes["a"], self.nodes["b"]]], self.nodes["b"].FindCycles(), ) def test_two_cycles(self): self._create_dependency(self.nodes["a"], self.nodes["b"]) self._create_dependency(self.nodes["b"], self.nodes["a"]) self._create_dependency(self.nodes["b"], self.nodes["c"]) self._create_dependency(self.nodes["c"], self.nodes["b"]) cycles = self.nodes["a"].FindCycles() self.assertTrue([self.nodes["a"], self.nodes["b"], self.nodes["a"]] in cycles) self.assertTrue([self.nodes["b"], self.nodes["c"], self.nodes["b"]] in cycles) self.assertEqual(2, len(cycles)) def test_big_cycle(self): self._create_dependency(self.nodes["a"], self.nodes["b"]) self._create_dependency(self.nodes["b"], self.nodes["c"]) self._create_dependency(self.nodes["c"], self.nodes["d"]) self._create_dependency(self.nodes["d"], self.nodes["e"]) self._create_dependency(self.nodes["e"], self.nodes["a"]) self.assertEqual( [ [ self.nodes["a"], self.nodes["b"], self.nodes["c"], self.nodes["d"], self.nodes["e"], self.nodes["a"], ] ], self.nodes["a"].FindCycles(), ) if __name__ == "__main__": unittest.main() PK ~\fF^F^"node-gyp/gyp/pylib/gyp/__init__.pynu[#!/usr/bin/env python3 # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import copy import gyp.input import argparse import os.path import re import shlex import sys import traceback from gyp.common import GypError # Default debug modes for GYP debug = {} # List of "official" debug modes, but you can use anything you like. DEBUG_GENERAL = "general" DEBUG_VARIABLES = "variables" DEBUG_INCLUDES = "includes" def DebugOutput(mode, message, *args): if "all" in gyp.debug or mode in gyp.debug: ctx = ("unknown", 0, "unknown") try: f = traceback.extract_stack(limit=2) if f: ctx = f[0][:3] except Exception: pass if args: message %= args print( "%s:%s:%d:%s %s" % (mode.upper(), os.path.basename(ctx[0]), ctx[1], ctx[2], message) ) def FindBuildFiles(): extension = ".gyp" files = os.listdir(os.getcwd()) build_files = [] for file in files: if file.endswith(extension): build_files.append(file) return build_files def Load( build_files, format, default_variables={}, includes=[], depth=".", params=None, check=False, circular_check=True, ): """ Loads one or more specified build files. default_variables and includes will be copied before use. Returns the generator for the specified format and the data returned by loading the specified build files. """ if params is None: params = {} if "-" in format: format, params["flavor"] = format.split("-", 1) default_variables = copy.copy(default_variables) # Default variables provided by this program and its modules should be # named WITH_CAPITAL_LETTERS to provide a distinct "best practice" namespace, # avoiding collisions with user and automatic variables. default_variables["GENERATOR"] = format default_variables["GENERATOR_FLAVOR"] = params.get("flavor", "") # Format can be a custom python file, or by default the name of a module # within gyp.generator. if format.endswith(".py"): generator_name = os.path.splitext(format)[0] path, generator_name = os.path.split(generator_name) # Make sure the path to the custom generator is in sys.path # Don't worry about removing it once we are done. Keeping the path # to each generator that is used in sys.path is likely harmless and # arguably a good idea. path = os.path.abspath(path) if path not in sys.path: sys.path.insert(0, path) else: generator_name = "gyp.generator." + format # These parameters are passed in order (as opposed to by key) # because ActivePython cannot handle key parameters to __import__. generator = __import__(generator_name, globals(), locals(), generator_name) for (key, val) in generator.generator_default_variables.items(): default_variables.setdefault(key, val) output_dir = params["options"].generator_output or params["options"].toplevel_dir if default_variables["GENERATOR"] == "ninja": default_variables.setdefault( "PRODUCT_DIR_ABS", os.path.join( output_dir, "out", default_variables.get("build_type", "default") ), ) else: default_variables.setdefault( "PRODUCT_DIR_ABS", os.path.join(output_dir, default_variables["CONFIGURATION_NAME"]), ) # Give the generator the opportunity to set additional variables based on # the params it will receive in the output phase. if getattr(generator, "CalculateVariables", None): generator.CalculateVariables(default_variables, params) # Give the generator the opportunity to set generator_input_info based on # the params it will receive in the output phase. if getattr(generator, "CalculateGeneratorInputInfo", None): generator.CalculateGeneratorInputInfo(params) # Fetch the generator specific info that gets fed to input, we use getattr # so we can default things and the generators only have to provide what # they need. generator_input_info = { "non_configuration_keys": getattr( generator, "generator_additional_non_configuration_keys", [] ), "path_sections": getattr(generator, "generator_additional_path_sections", []), "extra_sources_for_rules": getattr( generator, "generator_extra_sources_for_rules", [] ), "generator_supports_multiple_toolsets": getattr( generator, "generator_supports_multiple_toolsets", False ), "generator_wants_static_library_dependencies_adjusted": getattr( generator, "generator_wants_static_library_dependencies_adjusted", True ), "generator_wants_sorted_dependencies": getattr( generator, "generator_wants_sorted_dependencies", False ), "generator_filelist_paths": getattr( generator, "generator_filelist_paths", None ), } # Process the input specific to this generator. result = gyp.input.Load( build_files, default_variables, includes[:], depth, generator_input_info, check, circular_check, params["parallel"], params["root_targets"], ) return [generator] + result def NameValueListToDict(name_value_list): """ Takes an array of strings of the form 'NAME=VALUE' and creates a dictionary of the pairs. If a string is simply NAME, then the value in the dictionary is set to True. If VALUE can be converted to an integer, it is. """ result = {} for item in name_value_list: tokens = item.split("=", 1) if len(tokens) == 2: # If we can make it an int, use that, otherwise, use the string. try: token_value = int(tokens[1]) except ValueError: token_value = tokens[1] # Set the variable to the supplied value. result[tokens[0]] = token_value else: # No value supplied, treat it as a boolean and set it. result[tokens[0]] = True return result def ShlexEnv(env_name): flags = os.environ.get(env_name, []) if flags: flags = shlex.split(flags) return flags def FormatOpt(opt, value): if opt.startswith("--"): return f"{opt}={value}" return opt + value def RegenerateAppendFlag(flag, values, predicate, env_name, options): """Regenerate a list of command line flags, for an option of action='append'. The |env_name|, if given, is checked in the environment and used to generate an initial list of options, then the options that were specified on the command line (given in |values|) are appended. This matches the handling of environment variables and command line flags where command line flags override the environment, while not requiring the environment to be set when the flags are used again. """ flags = [] if options.use_environment and env_name: for flag_value in ShlexEnv(env_name): value = FormatOpt(flag, predicate(flag_value)) if value in flags: flags.remove(value) flags.append(value) if values: for flag_value in values: flags.append(FormatOpt(flag, predicate(flag_value))) return flags def RegenerateFlags(options): """Given a parsed options object, and taking the environment variables into account, returns a list of flags that should regenerate an equivalent options object (even in the absence of the environment variables.) Any path options will be normalized relative to depth. The format flag is not included, as it is assumed the calling generator will set that as appropriate. """ def FixPath(path): path = gyp.common.FixIfRelativePath(path, options.depth) if not path: return os.path.curdir return path def Noop(value): return value # We always want to ignore the environment when regenerating, to avoid # duplicate or changed flags in the environment at the time of regeneration. flags = ["--ignore-environment"] for name, metadata in options._regeneration_metadata.items(): opt = metadata["opt"] value = getattr(options, name) value_predicate = metadata["type"] == "path" and FixPath or Noop action = metadata["action"] env_name = metadata["env_name"] if action == "append": flags.extend( RegenerateAppendFlag(opt, value, value_predicate, env_name, options) ) elif action in ("store", None): # None is a synonym for 'store'. if value: flags.append(FormatOpt(opt, value_predicate(value))) elif options.use_environment and env_name and os.environ.get(env_name): flags.append(FormatOpt(opt, value_predicate(os.environ.get(env_name)))) elif action in ("store_true", "store_false"): if (action == "store_true" and value) or ( action == "store_false" and not value ): flags.append(opt) elif options.use_environment and env_name: print( "Warning: environment regeneration unimplemented " "for %s flag %r env_name %r" % (action, opt, env_name), file=sys.stderr, ) else: print( "Warning: regeneration unimplemented for action %r " "flag %r" % (action, opt), file=sys.stderr, ) return flags class RegeneratableOptionParser(argparse.ArgumentParser): def __init__(self, usage): self.__regeneratable_options = {} argparse.ArgumentParser.__init__(self, usage=usage) def add_argument(self, *args, **kw): """Add an option to the parser. This accepts the same arguments as ArgumentParser.add_argument, plus the following: regenerate: can be set to False to prevent this option from being included in regeneration. env_name: name of environment variable that additional values for this option come from. type: adds type='path', to tell the regenerator that the values of this option need to be made relative to options.depth """ env_name = kw.pop("env_name", None) if "dest" in kw and kw.pop("regenerate", True): dest = kw["dest"] # The path type is needed for regenerating, for optparse we can just treat # it as a string. type = kw.get("type") if type == "path": kw["type"] = str self.__regeneratable_options[dest] = { "action": kw.get("action"), "type": type, "env_name": env_name, "opt": args[0], } argparse.ArgumentParser.add_argument(self, *args, **kw) def parse_args(self, *args): values, args = argparse.ArgumentParser.parse_known_args(self, *args) values._regeneration_metadata = self.__regeneratable_options return values, args def gyp_main(args): my_name = os.path.basename(sys.argv[0]) usage = "usage: %(prog)s [options ...] [build_file ...]" parser = RegeneratableOptionParser(usage=usage.replace("%s", "%(prog)s")) parser.add_argument( "--build", dest="configs", action="append", help="configuration for build after project generation", ) parser.add_argument( "--check", dest="check", action="store_true", help="check format of gyp files" ) parser.add_argument( "--config-dir", dest="config_dir", action="store", env_name="GYP_CONFIG_DIR", default=None, help="The location for configuration files like " "include.gypi.", ) parser.add_argument( "-d", "--debug", dest="debug", metavar="DEBUGMODE", action="append", default=[], help="turn on a debugging " 'mode for debugging GYP. Supported modes are "variables", ' '"includes" and "general" or "all" for all of them.', ) parser.add_argument( "-D", dest="defines", action="append", metavar="VAR=VAL", env_name="GYP_DEFINES", help="sets variable VAR to value VAL", ) parser.add_argument( "--depth", dest="depth", metavar="PATH", type="path", help="set DEPTH gyp variable to a relative path to PATH", ) parser.add_argument( "-f", "--format", dest="formats", action="append", env_name="GYP_GENERATORS", regenerate=False, help="output formats to generate", ) parser.add_argument( "-G", dest="generator_flags", action="append", default=[], metavar="FLAG=VAL", env_name="GYP_GENERATOR_FLAGS", help="sets generator flag FLAG to VAL", ) parser.add_argument( "--generator-output", dest="generator_output", action="store", default=None, metavar="DIR", type="path", env_name="GYP_GENERATOR_OUTPUT", help="puts generated build files under DIR", ) parser.add_argument( "--ignore-environment", dest="use_environment", action="store_false", default=True, regenerate=False, help="do not read options from environment variables", ) parser.add_argument( "-I", "--include", dest="includes", action="append", metavar="INCLUDE", type="path", help="files to include in all loaded .gyp files", ) # --no-circular-check disables the check for circular relationships between # .gyp files. These relationships should not exist, but they've only been # observed to be harmful with the Xcode generator. Chromium's .gyp files # currently have some circular relationships on non-Mac platforms, so this # option allows the strict behavior to be used on Macs and the lenient # behavior to be used elsewhere. # TODO(mark): Remove this option when http://crbug.com/35878 is fixed. parser.add_argument( "--no-circular-check", dest="circular_check", action="store_false", default=True, regenerate=False, help="don't check for circular relationships between files", ) parser.add_argument( "--no-parallel", action="store_true", default=False, help="Disable multiprocessing", ) parser.add_argument( "-S", "--suffix", dest="suffix", default="", help="suffix to add to generated files", ) parser.add_argument( "--toplevel-dir", dest="toplevel_dir", action="store", default=None, metavar="DIR", type="path", help="directory to use as the root of the source tree", ) parser.add_argument( "-R", "--root-target", dest="root_targets", action="append", metavar="TARGET", help="include only TARGET and its deep dependencies", ) parser.add_argument( "-V", "--version", dest="version", action="store_true", help="Show the version and exit.", ) options, build_files_arg = parser.parse_args(args) if options.version: import pkg_resources print(f"v{pkg_resources.get_distribution('gyp-next').version}") return 0 build_files = build_files_arg # Set up the configuration directory (defaults to ~/.gyp) if not options.config_dir: home = None home_dot_gyp = None if options.use_environment: home_dot_gyp = os.environ.get("GYP_CONFIG_DIR", None) if home_dot_gyp: home_dot_gyp = os.path.expanduser(home_dot_gyp) if not home_dot_gyp: home_vars = ["HOME"] if sys.platform in ("cygwin", "win32"): home_vars.append("USERPROFILE") for home_var in home_vars: home = os.getenv(home_var) if home: home_dot_gyp = os.path.join(home, ".gyp") if not os.path.exists(home_dot_gyp): home_dot_gyp = None else: break else: home_dot_gyp = os.path.expanduser(options.config_dir) if home_dot_gyp and not os.path.exists(home_dot_gyp): home_dot_gyp = None if not options.formats: # If no format was given on the command line, then check the env variable. generate_formats = [] if options.use_environment: generate_formats = os.environ.get("GYP_GENERATORS", []) if generate_formats: generate_formats = re.split(r"[\s,]", generate_formats) if generate_formats: options.formats = generate_formats else: # Nothing in the variable, default based on platform. if sys.platform == "darwin": options.formats = ["xcode"] elif sys.platform in ("win32", "cygwin"): options.formats = ["msvs"] else: options.formats = ["make"] if not options.generator_output and options.use_environment: g_o = os.environ.get("GYP_GENERATOR_OUTPUT") if g_o: options.generator_output = g_o options.parallel = not options.no_parallel for mode in options.debug: gyp.debug[mode] = 1 # Do an extra check to avoid work when we're not debugging. if DEBUG_GENERAL in gyp.debug: DebugOutput(DEBUG_GENERAL, "running with these options:") for option, value in sorted(options.__dict__.items()): if option[0] == "_": continue if isinstance(value, str): DebugOutput(DEBUG_GENERAL, " %s: '%s'", option, value) else: DebugOutput(DEBUG_GENERAL, " %s: %s", option, value) if not build_files: build_files = FindBuildFiles() if not build_files: raise GypError((usage + "\n\n%s: error: no build_file") % (my_name, my_name)) # TODO(mark): Chromium-specific hack! # For Chromium, the gyp "depth" variable should always be a relative path # to Chromium's top-level "src" directory. If no depth variable was set # on the command line, try to find a "src" directory by looking at the # absolute path to each build file's directory. The first "src" component # found will be treated as though it were the path used for --depth. if not options.depth: for build_file in build_files: build_file_dir = os.path.abspath(os.path.dirname(build_file)) build_file_dir_components = build_file_dir.split(os.path.sep) components_len = len(build_file_dir_components) for index in range(components_len - 1, -1, -1): if build_file_dir_components[index] == "src": options.depth = os.path.sep.join(build_file_dir_components) break del build_file_dir_components[index] # If the inner loop found something, break without advancing to another # build file. if options.depth: break if not options.depth: raise GypError( "Could not automatically locate src directory. This is" "a temporary Chromium feature that will be removed. Use" "--depth as a workaround." ) # If toplevel-dir is not set, we assume that depth is the root of our source # tree. if not options.toplevel_dir: options.toplevel_dir = options.depth # -D on the command line sets variable defaults - D isn't just for define, # it's for default. Perhaps there should be a way to force (-F?) a # variable's value so that it can't be overridden by anything else. cmdline_default_variables = {} defines = [] if options.use_environment: defines += ShlexEnv("GYP_DEFINES") if options.defines: defines += options.defines cmdline_default_variables = NameValueListToDict(defines) if DEBUG_GENERAL in gyp.debug: DebugOutput( DEBUG_GENERAL, "cmdline_default_variables: %s", cmdline_default_variables ) # Set up includes. includes = [] # If ~/.gyp/include.gypi exists, it'll be forcibly included into every # .gyp file that's loaded, before anything else is included. if home_dot_gyp: default_include = os.path.join(home_dot_gyp, "include.gypi") if os.path.exists(default_include): print("Using overrides found in " + default_include) includes.append(default_include) # Command-line --include files come after the default include. if options.includes: includes.extend(options.includes) # Generator flags should be prefixed with the target generator since they # are global across all generator runs. gen_flags = [] if options.use_environment: gen_flags += ShlexEnv("GYP_GENERATOR_FLAGS") if options.generator_flags: gen_flags += options.generator_flags generator_flags = NameValueListToDict(gen_flags) if DEBUG_GENERAL in gyp.debug: DebugOutput(DEBUG_GENERAL, "generator_flags: %s", generator_flags) # Generate all requested formats (use a set in case we got one format request # twice) for format in set(options.formats): params = { "options": options, "build_files": build_files, "generator_flags": generator_flags, "cwd": os.getcwd(), "build_files_arg": build_files_arg, "gyp_binary": sys.argv[0], "home_dot_gyp": home_dot_gyp, "parallel": options.parallel, "root_targets": options.root_targets, "target_arch": cmdline_default_variables.get("target_arch", ""), } # Start with the default variables from the command line. [generator, flat_list, targets, data] = Load( build_files, format, cmdline_default_variables, includes, options.depth, params, options.check, options.circular_check, ) # TODO(mark): Pass |data| for now because the generator needs a list of # build files that came in. In the future, maybe it should just accept # a list, and not the whole data dict. # NOTE: flat_list is the flattened dependency graph specifying the order # that targets may be built. Build systems that operate serially or that # need to have dependencies defined before dependents reference them should # generate targets in the order specified in flat_list. generator.GenerateOutput(flat_list, targets, data, params) if options.configs: valid_configs = targets[flat_list[0]]["configurations"] for conf in options.configs: if conf not in valid_configs: raise GypError("Invalid config specified via --build: %s" % conf) generator.PerformBuild(data, options.configs, params) # Done return 0 def main(args): try: return gyp_main(args) except GypError as e: sys.stderr.write("gyp: %s\n" % e) return 1 # NOTE: setuptools generated console_scripts calls function with no arguments def script_main(): return main(sys.argv[1:]) if __name__ == "__main__": sys.exit(script_main()) PK ~\~)22!node-gyp/gyp/pylib/gyp/MSVSNew.pynu[# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """New implementation of Visual Studio project generation.""" import hashlib import os import random from operator import attrgetter import gyp.common def cmp(x, y): return (x > y) - (x < y) # Initialize random number generator random.seed() # GUIDs for project types ENTRY_TYPE_GUIDS = { "project": "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "folder": "{2150E333-8FDC-42A3-9474-1A3956D46DE8}", } # ------------------------------------------------------------------------------ # Helper functions def MakeGuid(name, seed="msvs_new"): """Returns a GUID for the specified target name. Args: name: Target name. seed: Seed for MD5 hash. Returns: A GUID-line string calculated from the name and seed. This generates something which looks like a GUID, but depends only on the name and seed. This means the same name/seed will always generate the same GUID, so that projects and solutions which refer to each other can explicitly determine the GUID to refer to explicitly. It also means that the GUID will not change when the project for a target is rebuilt. """ # Calculate a MD5 signature for the seed and name. d = hashlib.md5((str(seed) + str(name)).encode("utf-8")).hexdigest().upper() # Convert most of the signature to GUID form (discard the rest) guid = ( "{" + d[:8] + "-" + d[8:12] + "-" + d[12:16] + "-" + d[16:20] + "-" + d[20:32] + "}" ) return guid # ------------------------------------------------------------------------------ class MSVSSolutionEntry: def __cmp__(self, other): # Sort by name then guid (so things are in order on vs2008). return cmp((self.name, self.get_guid()), (other.name, other.get_guid())) class MSVSFolder(MSVSSolutionEntry): """Folder in a Visual Studio project or solution.""" def __init__(self, path, name=None, entries=None, guid=None, items=None): """Initializes the folder. Args: path: Full path to the folder. name: Name of the folder. entries: List of folder entries to nest inside this folder. May contain Folder or Project objects. May be None, if the folder is empty. guid: GUID to use for folder, if not None. items: List of solution items to include in the folder project. May be None, if the folder does not directly contain items. """ if name: self.name = name else: # Use last layer. self.name = os.path.basename(path) self.path = path self.guid = guid # Copy passed lists (or set to empty lists) self.entries = sorted(entries or [], key=attrgetter("path")) self.items = list(items or []) self.entry_type_guid = ENTRY_TYPE_GUIDS["folder"] def get_guid(self): if self.guid is None: # Use consistent guids for folders (so things don't regenerate). self.guid = MakeGuid(self.path, seed="msvs_folder") return self.guid # ------------------------------------------------------------------------------ class MSVSProject(MSVSSolutionEntry): """Visual Studio project.""" def __init__( self, path, name=None, dependencies=None, guid=None, spec=None, build_file=None, config_platform_overrides=None, fixpath_prefix=None, ): """Initializes the project. Args: path: Absolute path to the project file. name: Name of project. If None, the name will be the same as the base name of the project file. dependencies: List of other Project objects this project is dependent upon, if not None. guid: GUID to use for project, if not None. spec: Dictionary specifying how to build this project. build_file: Filename of the .gyp file that the vcproj file comes from. config_platform_overrides: optional dict of configuration platforms to used in place of the default for this target. fixpath_prefix: the path used to adjust the behavior of _fixpath """ self.path = path self.guid = guid self.spec = spec self.build_file = build_file # Use project filename if name not specified self.name = name or os.path.splitext(os.path.basename(path))[0] # Copy passed lists (or set to empty lists) self.dependencies = list(dependencies or []) self.entry_type_guid = ENTRY_TYPE_GUIDS["project"] if config_platform_overrides: self.config_platform_overrides = config_platform_overrides else: self.config_platform_overrides = {} self.fixpath_prefix = fixpath_prefix self.msbuild_toolset = None def set_dependencies(self, dependencies): self.dependencies = list(dependencies or []) def get_guid(self): if self.guid is None: # Set GUID from path # TODO(rspangler): This is fragile. # 1. We can't just use the project filename sans path, since there could # be multiple projects with the same base name (for example, # foo/unittest.vcproj and bar/unittest.vcproj). # 2. The path needs to be relative to $SOURCE_ROOT, so that the project # GUID is the same whether it's included from base/base.sln or # foo/bar/baz/baz.sln. # 3. The GUID needs to be the same each time this builder is invoked, so # that we don't need to rebuild the solution when the project changes. # 4. We should be able to handle pre-built project files by reading the # GUID from the files. self.guid = MakeGuid(self.name) return self.guid def set_msbuild_toolset(self, msbuild_toolset): self.msbuild_toolset = msbuild_toolset # ------------------------------------------------------------------------------ class MSVSSolution: """Visual Studio solution.""" def __init__( self, path, version, entries=None, variants=None, websiteProperties=True ): """Initializes the solution. Args: path: Path to solution file. version: Format version to emit. entries: List of entries in solution. May contain Folder or Project objects. May be None, if the folder is empty. variants: List of build variant strings. If none, a default list will be used. websiteProperties: Flag to decide if the website properties section is generated. """ self.path = path self.websiteProperties = websiteProperties self.version = version # Copy passed lists (or set to empty lists) self.entries = list(entries or []) if variants: # Copy passed list self.variants = variants[:] else: # Use default self.variants = ["Debug|Win32", "Release|Win32"] # TODO(rspangler): Need to be able to handle a mapping of solution config # to project config. Should we be able to handle variants being a dict, # or add a separate variant_map variable? If it's a dict, we can't # guarantee the order of variants since dict keys aren't ordered. # TODO(rspangler): Automatically write to disk for now; should delay until # node-evaluation time. self.Write() def Write(self, writer=gyp.common.WriteOnDiff): """Writes the solution file to disk. Raises: IndexError: An entry appears multiple times. """ # Walk the entry tree and collect all the folders and projects. all_entries = set() entries_to_check = self.entries[:] while entries_to_check: e = entries_to_check.pop(0) # If this entry has been visited, nothing to do. if e in all_entries: continue all_entries.add(e) # If this is a folder, check its entries too. if isinstance(e, MSVSFolder): entries_to_check += e.entries all_entries = sorted(all_entries, key=attrgetter("path")) # Open file and print header f = writer(self.path) f.write( "Microsoft Visual Studio Solution File, " "Format Version %s\r\n" % self.version.SolutionVersion() ) f.write("# %s\r\n" % self.version.Description()) # Project entries sln_root = os.path.split(self.path)[0] for e in all_entries: relative_path = gyp.common.RelativePath(e.path, sln_root) # msbuild does not accept an empty folder_name. # use '.' in case relative_path is empty. folder_name = relative_path.replace("/", "\\") or "." f.write( 'Project("%s") = "%s", "%s", "%s"\r\n' % ( e.entry_type_guid, # Entry type GUID e.name, # Folder name folder_name, # Folder name (again) e.get_guid(), # Entry GUID ) ) # TODO(rspangler): Need a way to configure this stuff if self.websiteProperties: f.write( "\tProjectSection(WebsiteProperties) = preProject\r\n" '\t\tDebug.AspNetCompiler.Debug = "True"\r\n' '\t\tRelease.AspNetCompiler.Debug = "False"\r\n' "\tEndProjectSection\r\n" ) if isinstance(e, MSVSFolder) and e.items: f.write("\tProjectSection(SolutionItems) = preProject\r\n") for i in e.items: f.write(f"\t\t{i} = {i}\r\n") f.write("\tEndProjectSection\r\n") if isinstance(e, MSVSProject) and e.dependencies: f.write("\tProjectSection(ProjectDependencies) = postProject\r\n") for d in e.dependencies: f.write(f"\t\t{d.get_guid()} = {d.get_guid()}\r\n") f.write("\tEndProjectSection\r\n") f.write("EndProject\r\n") # Global section f.write("Global\r\n") # Configurations (variants) f.write("\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\r\n") for v in self.variants: f.write(f"\t\t{v} = {v}\r\n") f.write("\tEndGlobalSection\r\n") # Sort config guids for easier diffing of solution changes. config_guids = [] config_guids_overrides = {} for e in all_entries: if isinstance(e, MSVSProject): config_guids.append(e.get_guid()) config_guids_overrides[e.get_guid()] = e.config_platform_overrides config_guids.sort() f.write("\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\r\n") for g in config_guids: for v in self.variants: nv = config_guids_overrides[g].get(v, v) # Pick which project configuration to build for this solution # configuration. f.write( "\t\t%s.%s.ActiveCfg = %s\r\n" % ( g, # Project GUID v, # Solution build configuration nv, # Project build config for that solution config ) ) # Enable project in this solution configuration. f.write( "\t\t%s.%s.Build.0 = %s\r\n" % ( g, # Project GUID v, # Solution build configuration nv, # Project build config for that solution config ) ) f.write("\tEndGlobalSection\r\n") # TODO(rspangler): Should be able to configure this stuff too (though I've # never seen this be any different) f.write("\tGlobalSection(SolutionProperties) = preSolution\r\n") f.write("\t\tHideSolutionNode = FALSE\r\n") f.write("\tEndGlobalSection\r\n") # Folder mappings # Omit this section if there are no folders if any(e.entries for e in all_entries if isinstance(e, MSVSFolder)): f.write("\tGlobalSection(NestedProjects) = preSolution\r\n") for e in all_entries: if not isinstance(e, MSVSFolder): continue # Does not apply to projects, only folders for subentry in e.entries: f.write(f"\t\t{subentry.get_guid()} = {e.get_guid()}\r\n") f.write("\tEndGlobalSection\r\n") f.write("EndGlobal\r\n") f.close() PK ~\cKK)node-gyp/gyp/pylib/gyp/generator/ninja.pynu[# Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import collections import copy import hashlib import json import multiprocessing import os.path import re import signal import subprocess import sys import gyp import gyp.common import gyp.msvs_emulation import gyp.MSVSUtil as MSVSUtil import gyp.xcode_emulation from io import StringIO from gyp.common import GetEnvironFallback import gyp.ninja_syntax as ninja_syntax generator_default_variables = { "EXECUTABLE_PREFIX": "", "EXECUTABLE_SUFFIX": "", "STATIC_LIB_PREFIX": "lib", "STATIC_LIB_SUFFIX": ".a", "SHARED_LIB_PREFIX": "lib", # Gyp expects the following variables to be expandable by the build # system to the appropriate locations. Ninja prefers paths to be # known at gyp time. To resolve this, introduce special # variables starting with $! and $| (which begin with a $ so gyp knows it # should be treated specially, but is otherwise an invalid # ninja/shell variable) that are passed to gyp here but expanded # before writing out into the target .ninja files; see # ExpandSpecial. # $! is used for variables that represent a path and that can only appear at # the start of a string, while $| is used for variables that can appear # anywhere in a string. "INTERMEDIATE_DIR": "$!INTERMEDIATE_DIR", "SHARED_INTERMEDIATE_DIR": "$!PRODUCT_DIR/gen", "PRODUCT_DIR": "$!PRODUCT_DIR", "CONFIGURATION_NAME": "$|CONFIGURATION_NAME", # Special variables that may be used by gyp 'rule' targets. # We generate definitions for these variables on the fly when processing a # rule. "RULE_INPUT_ROOT": "${root}", "RULE_INPUT_DIRNAME": "${dirname}", "RULE_INPUT_PATH": "${source}", "RULE_INPUT_EXT": "${ext}", "RULE_INPUT_NAME": "${name}", } # Placates pylint. generator_additional_non_configuration_keys = [] generator_additional_path_sections = [] generator_extra_sources_for_rules = [] generator_filelist_paths = None generator_supports_multiple_toolsets = gyp.common.CrossCompileRequested() def StripPrefix(arg, prefix): if arg.startswith(prefix): return arg[len(prefix) :] return arg def QuoteShellArgument(arg, flavor): """Quote a string such that it will be interpreted as a single argument by the shell.""" # Rather than attempting to enumerate the bad shell characters, just # allow common OK ones and quote anything else. if re.match(r"^[a-zA-Z0-9_=.\\/-]+$", arg): return arg # No quoting necessary. if flavor == "win": return gyp.msvs_emulation.QuoteForRspFile(arg) return "'" + arg.replace("'", "'" + '"\'"' + "'") + "'" def Define(d, flavor): """Takes a preprocessor define and returns a -D parameter that's ninja- and shell-escaped.""" if flavor == "win": # cl.exe replaces literal # characters with = in preprocessor definitions for # some reason. Octal-encode to work around that. d = d.replace("#", "\\%03o" % ord("#")) return QuoteShellArgument(ninja_syntax.escape("-D" + d), flavor) def AddArch(output, arch): """Adds an arch string to an output path.""" output, extension = os.path.splitext(output) return f"{output}.{arch}{extension}" class Target: """Target represents the paths used within a single gyp target. Conceptually, building a single target A is a series of steps: 1) actions/rules/copies generates source/resources/etc. 2) compiles generates .o files 3) link generates a binary (library/executable) 4) bundle merges the above in a mac bundle (Any of these steps can be optional.) From a build ordering perspective, a dependent target B could just depend on the last output of this series of steps. But some dependent commands sometimes need to reach inside the box. For example, when linking B it needs to get the path to the static library generated by A. This object stores those paths. To keep things simple, member variables only store concrete paths to single files, while methods compute derived values like "the last output of the target". """ def __init__(self, type): # Gyp type ("static_library", etc.) of this target. self.type = type # File representing whether any input dependencies necessary for # dependent actions have completed. self.preaction_stamp = None # File representing whether any input dependencies necessary for # dependent compiles have completed. self.precompile_stamp = None # File representing the completion of actions/rules/copies, if any. self.actions_stamp = None # Path to the output of the link step, if any. self.binary = None # Path to the file representing the completion of building the bundle, # if any. self.bundle = None # On Windows, incremental linking requires linking against all the .objs # that compose a .lib (rather than the .lib itself). That list is stored # here. In this case, we also need to save the compile_deps for the target, # so that the target that directly depends on the .objs can also depend # on those. self.component_objs = None self.compile_deps = None # Windows only. The import .lib is the output of a build step, but # because dependents only link against the lib (not both the lib and the # dll) we keep track of the import library here. self.import_lib = None # Track if this target contains any C++ files, to decide if gcc or g++ # should be used for linking. self.uses_cpp = False def Linkable(self): """Return true if this is a target that can be linked against.""" return self.type in ("static_library", "shared_library") def UsesToc(self, flavor): """Return true if the target should produce a restat rule based on a TOC file.""" # For bundles, the .TOC should be produced for the binary, not for # FinalOutput(). But the naive approach would put the TOC file into the # bundle, so don't do this for bundles for now. if flavor == "win" or self.bundle: return False return self.type in ("shared_library", "loadable_module") def PreActionInput(self, flavor): """Return the path, if any, that should be used as a dependency of any dependent action step.""" if self.UsesToc(flavor): return self.FinalOutput() + ".TOC" return self.FinalOutput() or self.preaction_stamp def PreCompileInput(self): """Return the path, if any, that should be used as a dependency of any dependent compile step.""" return self.actions_stamp or self.precompile_stamp def FinalOutput(self): """Return the last output of the target, which depends on all prior steps.""" return self.bundle or self.binary or self.actions_stamp # A small discourse on paths as used within the Ninja build: # All files we produce (both at gyp and at build time) appear in the # build directory (e.g. out/Debug). # # Paths within a given .gyp file are always relative to the directory # containing the .gyp file. Call these "gyp paths". This includes # sources as well as the starting directory a given gyp rule/action # expects to be run from. We call the path from the source root to # the gyp file the "base directory" within the per-.gyp-file # NinjaWriter code. # # All paths as written into the .ninja files are relative to the build # directory. Call these paths "ninja paths". # # We translate between these two notions of paths with two helper # functions: # # - GypPathToNinja translates a gyp path (i.e. relative to the .gyp file) # into the equivalent ninja path. # # - GypPathToUniqueOutput translates a gyp path into a ninja path to write # an output file; the result can be namespaced such that it is unique # to the input file name as well as the output target name. class NinjaWriter: def __init__( self, hash_for_rules, target_outputs, base_dir, build_dir, output_file, toplevel_build, output_file_name, flavor, toplevel_dir=None, ): """ base_dir: path from source root to directory containing this gyp file, by gyp semantics, all input paths are relative to this build_dir: path from source root to build output toplevel_dir: path to the toplevel directory """ self.hash_for_rules = hash_for_rules self.target_outputs = target_outputs self.base_dir = base_dir self.build_dir = build_dir self.ninja = ninja_syntax.Writer(output_file) self.toplevel_build = toplevel_build self.output_file_name = output_file_name self.flavor = flavor self.abs_build_dir = None if toplevel_dir is not None: self.abs_build_dir = os.path.abspath(os.path.join(toplevel_dir, build_dir)) self.obj_ext = ".obj" if flavor == "win" else ".o" if flavor == "win": # See docstring of msvs_emulation.GenerateEnvironmentFiles(). self.win_env = {} for arch in ("x86", "x64"): self.win_env[arch] = "environment." + arch # Relative path from build output dir to base dir. build_to_top = gyp.common.InvertRelativePath(build_dir, toplevel_dir) self.build_to_base = os.path.join(build_to_top, base_dir) # Relative path from base dir to build dir. base_to_top = gyp.common.InvertRelativePath(base_dir, toplevel_dir) self.base_to_build = os.path.join(base_to_top, build_dir) def ExpandSpecial(self, path, product_dir=None): """Expand specials like $!PRODUCT_DIR in |path|. If |product_dir| is None, assumes the cwd is already the product dir. Otherwise, |product_dir| is the relative path to the product dir. """ PRODUCT_DIR = "$!PRODUCT_DIR" if PRODUCT_DIR in path: if product_dir: path = path.replace(PRODUCT_DIR, product_dir) else: path = path.replace(PRODUCT_DIR + "/", "") path = path.replace(PRODUCT_DIR + "\\", "") path = path.replace(PRODUCT_DIR, ".") INTERMEDIATE_DIR = "$!INTERMEDIATE_DIR" if INTERMEDIATE_DIR in path: int_dir = self.GypPathToUniqueOutput("gen") # GypPathToUniqueOutput generates a path relative to the product dir, # so insert product_dir in front if it is provided. path = path.replace( INTERMEDIATE_DIR, os.path.join(product_dir or "", int_dir) ) CONFIGURATION_NAME = "$|CONFIGURATION_NAME" path = path.replace(CONFIGURATION_NAME, self.config_name) return path def ExpandRuleVariables(self, path, root, dirname, source, ext, name): if self.flavor == "win": path = self.msvs_settings.ConvertVSMacros(path, config=self.config_name) path = path.replace(generator_default_variables["RULE_INPUT_ROOT"], root) path = path.replace(generator_default_variables["RULE_INPUT_DIRNAME"], dirname) path = path.replace(generator_default_variables["RULE_INPUT_PATH"], source) path = path.replace(generator_default_variables["RULE_INPUT_EXT"], ext) path = path.replace(generator_default_variables["RULE_INPUT_NAME"], name) return path def GypPathToNinja(self, path, env=None): """Translate a gyp path to a ninja path, optionally expanding environment variable references in |path| with |env|. See the above discourse on path conversions.""" if env: if self.flavor == "mac": path = gyp.xcode_emulation.ExpandEnvVars(path, env) elif self.flavor == "win": path = gyp.msvs_emulation.ExpandMacros(path, env) if path.startswith("$!"): expanded = self.ExpandSpecial(path) if self.flavor == "win": expanded = os.path.normpath(expanded) return expanded if "$|" in path: path = self.ExpandSpecial(path) assert "$" not in path, path return os.path.normpath(os.path.join(self.build_to_base, path)) def GypPathToUniqueOutput(self, path, qualified=True): """Translate a gyp path to a ninja path for writing output. If qualified is True, qualify the resulting filename with the name of the target. This is necessary when e.g. compiling the same path twice for two separate output targets. See the above discourse on path conversions.""" path = self.ExpandSpecial(path) assert not path.startswith("$"), path # Translate the path following this scheme: # Input: foo/bar.gyp, target targ, references baz/out.o # Output: obj/foo/baz/targ.out.o (if qualified) # obj/foo/baz/out.o (otherwise) # (and obj.host instead of obj for cross-compiles) # # Why this scheme and not some other one? # 1) for a given input, you can compute all derived outputs by matching # its path, even if the input is brought via a gyp file with '..'. # 2) simple files like libraries and stamps have a simple filename. obj = "obj" if self.toolset != "target": obj += "." + self.toolset path_dir, path_basename = os.path.split(path) assert not os.path.isabs(path_dir), ( "'%s' can not be absolute path (see crbug.com/462153)." % path_dir ) if qualified: path_basename = self.name + "." + path_basename return os.path.normpath( os.path.join(obj, self.base_dir, path_dir, path_basename) ) def WriteCollapsedDependencies(self, name, targets, order_only=None): """Given a list of targets, return a path for a single file representing the result of building all the targets or None. Uses a stamp file if necessary.""" assert targets == [item for item in targets if item], targets if len(targets) == 0: assert not order_only return None if len(targets) > 1 or order_only: stamp = self.GypPathToUniqueOutput(name + ".stamp") targets = self.ninja.build(stamp, "stamp", targets, order_only=order_only) self.ninja.newline() return targets[0] def _SubninjaNameForArch(self, arch): output_file_base = os.path.splitext(self.output_file_name)[0] return f"{output_file_base}.{arch}.ninja" def WriteSpec(self, spec, config_name, generator_flags): """The main entry point for NinjaWriter: write the build rules for a spec. Returns a Target object, which represents the output paths for this spec. Returns None if there are no outputs (e.g. a settings-only 'none' type target).""" self.config_name = config_name self.name = spec["target_name"] self.toolset = spec["toolset"] config = spec["configurations"][config_name] self.target = Target(spec["type"]) self.is_standalone_static_library = bool( spec.get("standalone_static_library", 0) ) self.target_rpath = generator_flags.get("target_rpath", r"\$$ORIGIN/lib/") self.is_mac_bundle = gyp.xcode_emulation.IsMacBundle(self.flavor, spec) self.xcode_settings = self.msvs_settings = None if self.flavor == "mac": self.xcode_settings = gyp.xcode_emulation.XcodeSettings(spec) mac_toolchain_dir = generator_flags.get("mac_toolchain_dir", None) if mac_toolchain_dir: self.xcode_settings.mac_toolchain_dir = mac_toolchain_dir if self.flavor == "win": self.msvs_settings = gyp.msvs_emulation.MsvsSettings(spec, generator_flags) arch = self.msvs_settings.GetArch(config_name) self.ninja.variable("arch", self.win_env[arch]) self.ninja.variable("cc", "$cl_" + arch) self.ninja.variable("cxx", "$cl_" + arch) self.ninja.variable("cc_host", "$cl_" + arch) self.ninja.variable("cxx_host", "$cl_" + arch) self.ninja.variable("asm", "$ml_" + arch) if self.flavor == "mac": self.archs = self.xcode_settings.GetActiveArchs(config_name) if len(self.archs) > 1: self.arch_subninjas = { arch: ninja_syntax.Writer( OpenOutput( os.path.join( self.toplevel_build, self._SubninjaNameForArch(arch) ), "w", ) ) for arch in self.archs } # Compute predepends for all rules. # actions_depends is the dependencies this target depends on before running # any of its action/rule/copy steps. # compile_depends is the dependencies this target depends on before running # any of its compile steps. actions_depends = [] compile_depends = [] # TODO(evan): it is rather confusing which things are lists and which # are strings. Fix these. if "dependencies" in spec: for dep in spec["dependencies"]: if dep in self.target_outputs: target = self.target_outputs[dep] actions_depends.append(target.PreActionInput(self.flavor)) compile_depends.append(target.PreCompileInput()) if target.uses_cpp: self.target.uses_cpp = True actions_depends = [item for item in actions_depends if item] compile_depends = [item for item in compile_depends if item] actions_depends = self.WriteCollapsedDependencies( "actions_depends", actions_depends ) compile_depends = self.WriteCollapsedDependencies( "compile_depends", compile_depends ) self.target.preaction_stamp = actions_depends self.target.precompile_stamp = compile_depends # Write out actions, rules, and copies. These must happen before we # compile any sources, so compute a list of predependencies for sources # while we do it. extra_sources = [] mac_bundle_depends = [] self.target.actions_stamp = self.WriteActionsRulesCopies( spec, extra_sources, actions_depends, mac_bundle_depends ) # If we have actions/rules/copies, we depend directly on those, but # otherwise we depend on dependent target's actions/rules/copies etc. # We never need to explicitly depend on previous target's link steps, # because no compile ever depends on them. compile_depends_stamp = self.target.actions_stamp or compile_depends # Write out the compilation steps, if any. link_deps = [] try: sources = extra_sources + spec.get("sources", []) except TypeError: print("extra_sources: ", str(extra_sources)) print('spec.get("sources"): ', str(spec.get("sources"))) raise if sources: if self.flavor == "mac" and len(self.archs) > 1: # Write subninja file containing compile and link commands scoped to # a single arch if a fat binary is being built. for arch in self.archs: self.ninja.subninja(self._SubninjaNameForArch(arch)) pch = None if self.flavor == "win": gyp.msvs_emulation.VerifyMissingSources( sources, self.abs_build_dir, generator_flags, self.GypPathToNinja ) pch = gyp.msvs_emulation.PrecompiledHeader( self.msvs_settings, config_name, self.GypPathToNinja, self.GypPathToUniqueOutput, self.obj_ext, ) else: pch = gyp.xcode_emulation.MacPrefixHeader( self.xcode_settings, self.GypPathToNinja, lambda path, lang: self.GypPathToUniqueOutput(path + "-" + lang), ) link_deps = self.WriteSources( self.ninja, config_name, config, sources, compile_depends_stamp, pch, spec, ) # Some actions/rules output 'sources' that are already object files. obj_outputs = [f for f in sources if f.endswith(self.obj_ext)] if obj_outputs: if self.flavor != "mac" or len(self.archs) == 1: link_deps += [self.GypPathToNinja(o) for o in obj_outputs] else: print( "Warning: Actions/rules writing object files don't work with " "multiarch targets, dropping. (target %s)" % spec["target_name"] ) elif self.flavor == "mac" and len(self.archs) > 1: link_deps = collections.defaultdict(list) compile_deps = self.target.actions_stamp or actions_depends if self.flavor == "win" and self.target.type == "static_library": self.target.component_objs = link_deps self.target.compile_deps = compile_deps # Write out a link step, if needed. output = None is_empty_bundle = not link_deps and not mac_bundle_depends if link_deps or self.target.actions_stamp or actions_depends: output = self.WriteTarget( spec, config_name, config, link_deps, compile_deps ) if self.is_mac_bundle: mac_bundle_depends.append(output) # Bundle all of the above together, if needed. if self.is_mac_bundle: output = self.WriteMacBundle(spec, mac_bundle_depends, is_empty_bundle) if not output: return None assert self.target.FinalOutput(), output return self.target def _WinIdlRule(self, source, prebuild, outputs): """Handle the implicit VS .idl rule for one source file. Fills |outputs| with files that are generated.""" outdir, output, vars, flags = self.msvs_settings.GetIdlBuildData( source, self.config_name ) outdir = self.GypPathToNinja(outdir) def fix_path(path, rel=None): path = os.path.join(outdir, path) dirname, basename = os.path.split(source) root, ext = os.path.splitext(basename) path = self.ExpandRuleVariables(path, root, dirname, source, ext, basename) if rel: path = os.path.relpath(path, rel) return path vars = [(name, fix_path(value, outdir)) for name, value in vars] output = [fix_path(p) for p in output] vars.append(("outdir", outdir)) vars.append(("idlflags", flags)) input = self.GypPathToNinja(source) self.ninja.build(output, "idl", input, variables=vars, order_only=prebuild) outputs.extend(output) def WriteWinIdlFiles(self, spec, prebuild): """Writes rules to match MSVS's implicit idl handling.""" assert self.flavor == "win" if self.msvs_settings.HasExplicitIdlRulesOrActions(spec): return [] outputs = [] for source in filter(lambda x: x.endswith(".idl"), spec["sources"]): self._WinIdlRule(source, prebuild, outputs) return outputs def WriteActionsRulesCopies( self, spec, extra_sources, prebuild, mac_bundle_depends ): """Write out the Actions, Rules, and Copies steps. Return a path representing the outputs of these steps.""" outputs = [] if self.is_mac_bundle: mac_bundle_resources = spec.get("mac_bundle_resources", [])[:] else: mac_bundle_resources = [] extra_mac_bundle_resources = [] if "actions" in spec: outputs += self.WriteActions( spec["actions"], extra_sources, prebuild, extra_mac_bundle_resources ) if "rules" in spec: outputs += self.WriteRules( spec["rules"], extra_sources, prebuild, mac_bundle_resources, extra_mac_bundle_resources, ) if "copies" in spec: outputs += self.WriteCopies(spec["copies"], prebuild, mac_bundle_depends) if "sources" in spec and self.flavor == "win": outputs += self.WriteWinIdlFiles(spec, prebuild) if self.xcode_settings and self.xcode_settings.IsIosFramework(): self.WriteiOSFrameworkHeaders(spec, outputs, prebuild) stamp = self.WriteCollapsedDependencies("actions_rules_copies", outputs) if self.is_mac_bundle: xcassets = self.WriteMacBundleResources( extra_mac_bundle_resources + mac_bundle_resources, mac_bundle_depends ) partial_info_plist = self.WriteMacXCassets(xcassets, mac_bundle_depends) self.WriteMacInfoPlist(partial_info_plist, mac_bundle_depends) return stamp def GenerateDescription(self, verb, message, fallback): """Generate and return a description of a build step. |verb| is the short summary, e.g. ACTION or RULE. |message| is a hand-written description, or None if not available. |fallback| is the gyp-level name of the step, usable as a fallback. """ if self.toolset != "target": verb += "(%s)" % self.toolset if message: return f"{verb} {self.ExpandSpecial(message)}" else: return f"{verb} {self.name}: {fallback}" def WriteActions( self, actions, extra_sources, prebuild, extra_mac_bundle_resources ): # Actions cd into the base directory. env = self.GetToolchainEnv() all_outputs = [] for action in actions: # First write out a rule for the action. name = "{}_{}".format(action["action_name"], self.hash_for_rules) description = self.GenerateDescription( "ACTION", action.get("message", None), name ) win_shell_flags = ( self.msvs_settings.GetRuleShellFlags(action) if self.flavor == "win" else None ) args = action["action"] depfile = action.get("depfile", None) if depfile: depfile = self.ExpandSpecial(depfile, self.base_to_build) pool = "console" if int(action.get("ninja_use_console", 0)) else None rule_name, _ = self.WriteNewNinjaRule( name, args, description, win_shell_flags, env, pool, depfile=depfile ) inputs = [self.GypPathToNinja(i, env) for i in action["inputs"]] if int(action.get("process_outputs_as_sources", False)): extra_sources += action["outputs"] if int(action.get("process_outputs_as_mac_bundle_resources", False)): extra_mac_bundle_resources += action["outputs"] outputs = [self.GypPathToNinja(o, env) for o in action["outputs"]] # Then write out an edge using the rule. self.ninja.build(outputs, rule_name, inputs, order_only=prebuild) all_outputs += outputs self.ninja.newline() return all_outputs def WriteRules( self, rules, extra_sources, prebuild, mac_bundle_resources, extra_mac_bundle_resources, ): env = self.GetToolchainEnv() all_outputs = [] for rule in rules: # Skip a rule with no action and no inputs. if "action" not in rule and not rule.get("rule_sources", []): continue # First write out a rule for the rule action. name = "{}_{}".format(rule["rule_name"], self.hash_for_rules) args = rule["action"] description = self.GenerateDescription( "RULE", rule.get("message", None), ("%s " + generator_default_variables["RULE_INPUT_PATH"]) % name, ) win_shell_flags = ( self.msvs_settings.GetRuleShellFlags(rule) if self.flavor == "win" else None ) pool = "console" if int(rule.get("ninja_use_console", 0)) else None rule_name, args = self.WriteNewNinjaRule( name, args, description, win_shell_flags, env, pool ) # TODO: if the command references the outputs directly, we should # simplify it to just use $out. # Rules can potentially make use of some special variables which # must vary per source file. # Compute the list of variables we'll need to provide. special_locals = ("source", "root", "dirname", "ext", "name") needed_variables = {"source"} for argument in args: for var in special_locals: if "${%s}" % var in argument: needed_variables.add(var) needed_variables = sorted(needed_variables) def cygwin_munge(path): # pylint: disable=cell-var-from-loop if win_shell_flags and win_shell_flags.cygwin: return path.replace("\\", "/") return path inputs = [self.GypPathToNinja(i, env) for i in rule.get("inputs", [])] # If there are n source files matching the rule, and m additional rule # inputs, then adding 'inputs' to each build edge written below will # write m * n inputs. Collapsing reduces this to m + n. sources = rule.get("rule_sources", []) num_inputs = len(inputs) if prebuild: num_inputs += 1 if num_inputs > 2 and len(sources) > 2: inputs = [ self.WriteCollapsedDependencies( rule["rule_name"], inputs, order_only=prebuild ) ] prebuild = [] # For each source file, write an edge that generates all the outputs. for source in sources: source = os.path.normpath(source) dirname, basename = os.path.split(source) root, ext = os.path.splitext(basename) # Gather the list of inputs and outputs, expanding $vars if possible. outputs = [ self.ExpandRuleVariables(o, root, dirname, source, ext, basename) for o in rule["outputs"] ] if int(rule.get("process_outputs_as_sources", False)): extra_sources += outputs was_mac_bundle_resource = source in mac_bundle_resources if was_mac_bundle_resource or int( rule.get("process_outputs_as_mac_bundle_resources", False) ): extra_mac_bundle_resources += outputs # Note: This is n_resources * n_outputs_in_rule. # Put to-be-removed items in a set and # remove them all in a single pass # if this becomes a performance issue. if was_mac_bundle_resource: mac_bundle_resources.remove(source) extra_bindings = [] for var in needed_variables: if var == "root": extra_bindings.append(("root", cygwin_munge(root))) elif var == "dirname": # '$dirname' is a parameter to the rule action, which means # it shouldn't be converted to a Ninja path. But we don't # want $!PRODUCT_DIR in there either. dirname_expanded = self.ExpandSpecial( dirname, self.base_to_build ) extra_bindings.append( ("dirname", cygwin_munge(dirname_expanded)) ) elif var == "source": # '$source' is a parameter to the rule action, which means # it shouldn't be converted to a Ninja path. But we don't # want $!PRODUCT_DIR in there either. source_expanded = self.ExpandSpecial(source, self.base_to_build) extra_bindings.append(("source", cygwin_munge(source_expanded))) elif var == "ext": extra_bindings.append(("ext", ext)) elif var == "name": extra_bindings.append(("name", cygwin_munge(basename))) else: assert var is None, repr(var) outputs = [self.GypPathToNinja(o, env) for o in outputs] if self.flavor == "win": # WriteNewNinjaRule uses unique_name to create a rsp file on win. extra_bindings.append( ("unique_name", hashlib.md5(outputs[0]).hexdigest()) ) self.ninja.build( outputs, rule_name, self.GypPathToNinja(source), implicit=inputs, order_only=prebuild, variables=extra_bindings, ) all_outputs.extend(outputs) return all_outputs def WriteCopies(self, copies, prebuild, mac_bundle_depends): outputs = [] if self.xcode_settings: extra_env = self.xcode_settings.GetPerTargetSettings() env = self.GetToolchainEnv(additional_settings=extra_env) else: env = self.GetToolchainEnv() for to_copy in copies: for path in to_copy["files"]: # Normalize the path so trailing slashes don't confuse us. path = os.path.normpath(path) basename = os.path.split(path)[1] src = self.GypPathToNinja(path, env) dst = self.GypPathToNinja( os.path.join(to_copy["destination"], basename), env ) outputs += self.ninja.build(dst, "copy", src, order_only=prebuild) if self.is_mac_bundle: # gyp has mac_bundle_resources to copy things into a bundle's # Resources folder, but there's no built-in way to copy files # to other places in the bundle. # Hence, some targets use copies for this. # Check if this file is copied into the current bundle, # and if so add it to the bundle depends so # that dependent targets get rebuilt if the copy input changes. if dst.startswith( self.xcode_settings.GetBundleContentsFolderPath() ): mac_bundle_depends.append(dst) return outputs def WriteiOSFrameworkHeaders(self, spec, outputs, prebuild): """Prebuild steps to generate hmap files and copy headers to destination.""" framework = self.ComputeMacBundleOutput() all_sources = spec["sources"] copy_headers = spec["mac_framework_headers"] output = self.GypPathToUniqueOutput("headers.hmap") self.xcode_settings.header_map_path = output all_headers = map( self.GypPathToNinja, filter(lambda x: x.endswith(".h"), all_sources) ) variables = [ ("framework", framework), ("copy_headers", map(self.GypPathToNinja, copy_headers)), ] outputs.extend( self.ninja.build( output, "compile_ios_framework_headers", all_headers, variables=variables, order_only=prebuild, ) ) def WriteMacBundleResources(self, resources, bundle_depends): """Writes ninja edges for 'mac_bundle_resources'.""" xcassets = [] extra_env = self.xcode_settings.GetPerTargetSettings() env = self.GetSortedXcodeEnv(additional_settings=extra_env) env = self.ComputeExportEnvString(env) isBinary = self.xcode_settings.IsBinaryOutputFormat(self.config_name) for output, res in gyp.xcode_emulation.GetMacBundleResources( generator_default_variables["PRODUCT_DIR"], self.xcode_settings, map(self.GypPathToNinja, resources), ): output = self.ExpandSpecial(output) if os.path.splitext(output)[-1] != ".xcassets": self.ninja.build( output, "mac_tool", res, variables=[ ("mactool_cmd", "copy-bundle-resource"), ("env", env), ("binary", isBinary), ], ) bundle_depends.append(output) else: xcassets.append(res) return xcassets def WriteMacXCassets(self, xcassets, bundle_depends): """Writes ninja edges for 'mac_bundle_resources' .xcassets files. This add an invocation of 'actool' via the 'mac_tool.py' helper script. It assumes that the assets catalogs define at least one imageset and thus an Assets.car file will be generated in the application resources directory. If this is not the case, then the build will probably be done at each invocation of ninja.""" if not xcassets: return extra_arguments = {} settings_to_arg = { "XCASSETS_APP_ICON": "app-icon", "XCASSETS_LAUNCH_IMAGE": "launch-image", } settings = self.xcode_settings.xcode_settings[self.config_name] for settings_key, arg_name in settings_to_arg.items(): value = settings.get(settings_key) if value: extra_arguments[arg_name] = value partial_info_plist = None if extra_arguments: partial_info_plist = self.GypPathToUniqueOutput( "assetcatalog_generated_info.plist" ) extra_arguments["output-partial-info-plist"] = partial_info_plist outputs = [] outputs.append( os.path.join(self.xcode_settings.GetBundleResourceFolder(), "Assets.car") ) if partial_info_plist: outputs.append(partial_info_plist) keys = QuoteShellArgument(json.dumps(extra_arguments), self.flavor) extra_env = self.xcode_settings.GetPerTargetSettings() env = self.GetSortedXcodeEnv(additional_settings=extra_env) env = self.ComputeExportEnvString(env) bundle_depends.extend( self.ninja.build( outputs, "compile_xcassets", xcassets, variables=[("env", env), ("keys", keys)], ) ) return partial_info_plist def WriteMacInfoPlist(self, partial_info_plist, bundle_depends): """Write build rules for bundle Info.plist files.""" info_plist, out, defines, extra_env = gyp.xcode_emulation.GetMacInfoPlist( generator_default_variables["PRODUCT_DIR"], self.xcode_settings, self.GypPathToNinja, ) if not info_plist: return out = self.ExpandSpecial(out) if defines: # Create an intermediate file to store preprocessed results. intermediate_plist = self.GypPathToUniqueOutput( os.path.basename(info_plist) ) defines = " ".join([Define(d, self.flavor) for d in defines]) info_plist = self.ninja.build( intermediate_plist, "preprocess_infoplist", info_plist, variables=[("defines", defines)], ) env = self.GetSortedXcodeEnv(additional_settings=extra_env) env = self.ComputeExportEnvString(env) if partial_info_plist: intermediate_plist = self.GypPathToUniqueOutput("merged_info.plist") info_plist = self.ninja.build( intermediate_plist, "merge_infoplist", [partial_info_plist, info_plist] ) keys = self.xcode_settings.GetExtraPlistItems(self.config_name) keys = QuoteShellArgument(json.dumps(keys), self.flavor) isBinary = self.xcode_settings.IsBinaryOutputFormat(self.config_name) self.ninja.build( out, "copy_infoplist", info_plist, variables=[("env", env), ("keys", keys), ("binary", isBinary)], ) bundle_depends.append(out) def WriteSources( self, ninja_file, config_name, config, sources, predepends, precompiled_header, spec, ): """Write build rules to compile all of |sources|.""" if self.toolset == "host": self.ninja.variable("ar", "$ar_host") self.ninja.variable("cc", "$cc_host") self.ninja.variable("cxx", "$cxx_host") self.ninja.variable("ld", "$ld_host") self.ninja.variable("ldxx", "$ldxx_host") self.ninja.variable("nm", "$nm_host") self.ninja.variable("readelf", "$readelf_host") if self.flavor != "mac" or len(self.archs) == 1: return self.WriteSourcesForArch( self.ninja, config_name, config, sources, predepends, precompiled_header, spec, ) else: return { arch: self.WriteSourcesForArch( self.arch_subninjas[arch], config_name, config, sources, predepends, precompiled_header, spec, arch=arch, ) for arch in self.archs } def WriteSourcesForArch( self, ninja_file, config_name, config, sources, predepends, precompiled_header, spec, arch=None, ): """Write build rules to compile all of |sources|.""" extra_defines = [] if self.flavor == "mac": cflags = self.xcode_settings.GetCflags(config_name, arch=arch) cflags_c = self.xcode_settings.GetCflagsC(config_name) cflags_cc = self.xcode_settings.GetCflagsCC(config_name) cflags_objc = ["$cflags_c"] + self.xcode_settings.GetCflagsObjC(config_name) cflags_objcc = ["$cflags_cc"] + self.xcode_settings.GetCflagsObjCC( config_name ) elif self.flavor == "win": asmflags = self.msvs_settings.GetAsmflags(config_name) cflags = self.msvs_settings.GetCflags(config_name) cflags_c = self.msvs_settings.GetCflagsC(config_name) cflags_cc = self.msvs_settings.GetCflagsCC(config_name) extra_defines = self.msvs_settings.GetComputedDefines(config_name) # See comment at cc_command for why there's two .pdb files. pdbpath_c = pdbpath_cc = self.msvs_settings.GetCompilerPdbName( config_name, self.ExpandSpecial ) if not pdbpath_c: obj = "obj" if self.toolset != "target": obj += "." + self.toolset pdbpath = os.path.normpath(os.path.join(obj, self.base_dir, self.name)) pdbpath_c = pdbpath + ".c.pdb" pdbpath_cc = pdbpath + ".cc.pdb" self.WriteVariableList(ninja_file, "pdbname_c", [pdbpath_c]) self.WriteVariableList(ninja_file, "pdbname_cc", [pdbpath_cc]) self.WriteVariableList(ninja_file, "pchprefix", [self.name]) else: cflags = config.get("cflags", []) cflags_c = config.get("cflags_c", []) cflags_cc = config.get("cflags_cc", []) # Respect environment variables related to build, but target-specific # flags can still override them. if self.toolset == "target": cflags_c = ( os.environ.get("CPPFLAGS", "").split() + os.environ.get("CFLAGS", "").split() + cflags_c ) cflags_cc = ( os.environ.get("CPPFLAGS", "").split() + os.environ.get("CXXFLAGS", "").split() + cflags_cc ) elif self.toolset == "host": cflags_c = ( os.environ.get("CPPFLAGS_host", "").split() + os.environ.get("CFLAGS_host", "").split() + cflags_c ) cflags_cc = ( os.environ.get("CPPFLAGS_host", "").split() + os.environ.get("CXXFLAGS_host", "").split() + cflags_cc ) defines = config.get("defines", []) + extra_defines self.WriteVariableList( ninja_file, "defines", [Define(d, self.flavor) for d in defines] ) if self.flavor == "win": self.WriteVariableList( ninja_file, "asmflags", map(self.ExpandSpecial, asmflags) ) self.WriteVariableList( ninja_file, "rcflags", [ QuoteShellArgument(self.ExpandSpecial(f), self.flavor) for f in self.msvs_settings.GetRcflags( config_name, self.GypPathToNinja ) ], ) include_dirs = config.get("include_dirs", []) env = self.GetToolchainEnv() if self.flavor == "win": include_dirs = self.msvs_settings.AdjustIncludeDirs( include_dirs, config_name ) self.WriteVariableList( ninja_file, "includes", [ QuoteShellArgument("-I" + self.GypPathToNinja(i, env), self.flavor) for i in include_dirs ], ) if self.flavor == "win": midl_include_dirs = config.get("midl_include_dirs", []) midl_include_dirs = self.msvs_settings.AdjustMidlIncludeDirs( midl_include_dirs, config_name ) self.WriteVariableList( ninja_file, "midl_includes", [ QuoteShellArgument("-I" + self.GypPathToNinja(i, env), self.flavor) for i in midl_include_dirs ], ) pch_commands = precompiled_header.GetPchBuildCommands(arch) if self.flavor == "mac": # Most targets use no precompiled headers, so only write these if needed. for ext, var in [ ("c", "cflags_pch_c"), ("cc", "cflags_pch_cc"), ("m", "cflags_pch_objc"), ("mm", "cflags_pch_objcc"), ]: include = precompiled_header.GetInclude(ext, arch) if include: ninja_file.variable(var, include) arflags = config.get("arflags", []) self.WriteVariableList(ninja_file, "cflags", map(self.ExpandSpecial, cflags)) self.WriteVariableList( ninja_file, "cflags_c", map(self.ExpandSpecial, cflags_c) ) self.WriteVariableList( ninja_file, "cflags_cc", map(self.ExpandSpecial, cflags_cc) ) if self.flavor == "mac": self.WriteVariableList( ninja_file, "cflags_objc", map(self.ExpandSpecial, cflags_objc) ) self.WriteVariableList( ninja_file, "cflags_objcc", map(self.ExpandSpecial, cflags_objcc) ) self.WriteVariableList(ninja_file, "arflags", map(self.ExpandSpecial, arflags)) ninja_file.newline() outputs = [] has_rc_source = False for source in sources: filename, ext = os.path.splitext(source) ext = ext[1:] obj_ext = self.obj_ext if ext in ("cc", "cpp", "cxx"): command = "cxx" self.target.uses_cpp = True elif ext == "c" or (ext == "S" and self.flavor != "win"): command = "cc" elif ext == "s" and self.flavor != "win": # Doesn't generate .o.d files. command = "cc_s" elif ( self.flavor == "win" and ext in ("asm", "S") and not self.msvs_settings.HasExplicitAsmRules(spec) ): command = "asm" # Add the _asm suffix as msvs is capable of handling .cc and # .asm files of the same name without collision. obj_ext = "_asm.obj" elif self.flavor == "mac" and ext == "m": command = "objc" elif self.flavor == "mac" and ext == "mm": command = "objcxx" self.target.uses_cpp = True elif self.flavor == "win" and ext == "rc": command = "rc" obj_ext = ".res" has_rc_source = True else: # Ignore unhandled extensions. continue input = self.GypPathToNinja(source) output = self.GypPathToUniqueOutput(filename + obj_ext) if arch is not None: output = AddArch(output, arch) implicit = precompiled_header.GetObjDependencies([input], [output], arch) variables = [] if self.flavor == "win": variables, output, implicit = precompiled_header.GetFlagsModifications( input, output, implicit, command, cflags_c, cflags_cc, self.ExpandSpecial, ) ninja_file.build( output, command, input, implicit=[gch for _, _, gch in implicit], order_only=predepends, variables=variables, ) outputs.append(output) if has_rc_source: resource_include_dirs = config.get("resource_include_dirs", include_dirs) self.WriteVariableList( ninja_file, "resource_includes", [ QuoteShellArgument("-I" + self.GypPathToNinja(i, env), self.flavor) for i in resource_include_dirs ], ) self.WritePchTargets(ninja_file, pch_commands) ninja_file.newline() return outputs def WritePchTargets(self, ninja_file, pch_commands): """Writes ninja rules to compile prefix headers.""" if not pch_commands: return for gch, lang_flag, lang, input in pch_commands: var_name = { "c": "cflags_pch_c", "cc": "cflags_pch_cc", "m": "cflags_pch_objc", "mm": "cflags_pch_objcc", }[lang] map = { "c": "cc", "cc": "cxx", "m": "objc", "mm": "objcxx", } cmd = map.get(lang) ninja_file.build(gch, cmd, input, variables=[(var_name, lang_flag)]) def WriteLink(self, spec, config_name, config, link_deps, compile_deps): """Write out a link step. Fills out target.binary. """ if self.flavor != "mac" or len(self.archs) == 1: return self.WriteLinkForArch( self.ninja, spec, config_name, config, link_deps, compile_deps ) else: output = self.ComputeOutput(spec) inputs = [ self.WriteLinkForArch( self.arch_subninjas[arch], spec, config_name, config, link_deps[arch], compile_deps, arch=arch, ) for arch in self.archs ] extra_bindings = [] build_output = output if not self.is_mac_bundle: self.AppendPostbuildVariable(extra_bindings, spec, output, output) # TODO(yyanagisawa): more work needed to fix: # https://code.google.com/p/gyp/issues/detail?id=411 if ( spec["type"] in ("shared_library", "loadable_module") and not self.is_mac_bundle ): extra_bindings.append(("lib", output)) self.ninja.build( [output, output + ".TOC"], "solipo", inputs, variables=extra_bindings, ) else: self.ninja.build(build_output, "lipo", inputs, variables=extra_bindings) return output def WriteLinkForArch( self, ninja_file, spec, config_name, config, link_deps, compile_deps, arch=None ): """Write out a link step. Fills out target.binary. """ command = { "executable": "link", "loadable_module": "solink_module", "shared_library": "solink", }[spec["type"]] command_suffix = "" implicit_deps = set() solibs = set() order_deps = set() if compile_deps: # Normally, the compiles of the target already depend on compile_deps, # but a shared_library target might have no sources and only link together # a few static_library deps, so the link step also needs to depend # on compile_deps to make sure actions in the shared_library target # get run before the link. order_deps.add(compile_deps) if "dependencies" in spec: # Two kinds of dependencies: # - Linkable dependencies (like a .a or a .so): add them to the link line. # - Non-linkable dependencies (like a rule that generates a file # and writes a stamp file): add them to implicit_deps extra_link_deps = set() for dep in spec["dependencies"]: target = self.target_outputs.get(dep) if not target: continue linkable = target.Linkable() if linkable: new_deps = [] if ( self.flavor == "win" and target.component_objs and self.msvs_settings.IsUseLibraryDependencyInputs(config_name) ): new_deps = target.component_objs if target.compile_deps: order_deps.add(target.compile_deps) elif self.flavor == "win" and target.import_lib: new_deps = [target.import_lib] elif target.UsesToc(self.flavor): solibs.add(target.binary) implicit_deps.add(target.binary + ".TOC") else: new_deps = [target.binary] for new_dep in new_deps: if new_dep not in extra_link_deps: extra_link_deps.add(new_dep) link_deps.append(new_dep) final_output = target.FinalOutput() if not linkable or final_output != target.binary: implicit_deps.add(final_output) extra_bindings = [] if self.target.uses_cpp and self.flavor != "win": extra_bindings.append(("ld", "$ldxx")) output = self.ComputeOutput(spec, arch) if arch is None and not self.is_mac_bundle: self.AppendPostbuildVariable(extra_bindings, spec, output, output) is_executable = spec["type"] == "executable" # The ldflags config key is not used on mac or win. On those platforms # linker flags are set via xcode_settings and msvs_settings, respectively. if self.toolset == "target": env_ldflags = os.environ.get("LDFLAGS", "").split() elif self.toolset == "host": env_ldflags = os.environ.get("LDFLAGS_host", "").split() if self.flavor == "mac": ldflags = self.xcode_settings.GetLdflags( config_name, self.ExpandSpecial(generator_default_variables["PRODUCT_DIR"]), self.GypPathToNinja, arch, ) ldflags = env_ldflags + ldflags elif self.flavor == "win": manifest_base_name = self.GypPathToUniqueOutput( self.ComputeOutputFileName(spec) ) ( ldflags, intermediate_manifest, manifest_files, ) = self.msvs_settings.GetLdflags( config_name, self.GypPathToNinja, self.ExpandSpecial, manifest_base_name, output, is_executable, self.toplevel_build, ) ldflags = env_ldflags + ldflags self.WriteVariableList(ninja_file, "manifests", manifest_files) implicit_deps = implicit_deps.union(manifest_files) if intermediate_manifest: self.WriteVariableList( ninja_file, "intermediatemanifest", [intermediate_manifest] ) command_suffix = _GetWinLinkRuleNameSuffix( self.msvs_settings.IsEmbedManifest(config_name) ) def_file = self.msvs_settings.GetDefFile(self.GypPathToNinja) if def_file: implicit_deps.add(def_file) else: # Respect environment variables related to build, but target-specific # flags can still override them. ldflags = env_ldflags + config.get("ldflags", []) if is_executable and len(solibs): rpath = "lib/" if self.toolset != "target": rpath += self.toolset ldflags.append(r"-Wl,-rpath=\$$ORIGIN/%s" % rpath) else: ldflags.append("-Wl,-rpath=%s" % self.target_rpath) ldflags.append("-Wl,-rpath-link=%s" % rpath) self.WriteVariableList(ninja_file, "ldflags", map(self.ExpandSpecial, ldflags)) library_dirs = config.get("library_dirs", []) if self.flavor == "win": library_dirs = [ self.msvs_settings.ConvertVSMacros(library_dir, config_name) for library_dir in library_dirs ] library_dirs = [ "/LIBPATH:" + QuoteShellArgument(self.GypPathToNinja(library_dir), self.flavor) for library_dir in library_dirs ] else: library_dirs = [ QuoteShellArgument("-L" + self.GypPathToNinja(library_dir), self.flavor) for library_dir in library_dirs ] libraries = gyp.common.uniquer( map(self.ExpandSpecial, spec.get("libraries", [])) ) if self.flavor == "mac": libraries = self.xcode_settings.AdjustLibraries(libraries, config_name) elif self.flavor == "win": libraries = self.msvs_settings.AdjustLibraries(libraries) self.WriteVariableList(ninja_file, "libs", library_dirs + libraries) linked_binary = output if command in ("solink", "solink_module"): extra_bindings.append(("soname", os.path.split(output)[1])) extra_bindings.append(("lib", gyp.common.EncodePOSIXShellArgument(output))) if self.flavor != "win": link_file_list = output if self.is_mac_bundle: # 'Dependency Framework.framework/Versions/A/Dependency Framework' # -> 'Dependency Framework.framework.rsp' link_file_list = self.xcode_settings.GetWrapperName() if arch: link_file_list += "." + arch link_file_list += ".rsp" # If an rspfile contains spaces, ninja surrounds the filename with # quotes around it and then passes it to open(), creating a file with # quotes in its name (and when looking for the rsp file, the name # makes it through bash which strips the quotes) :-/ link_file_list = link_file_list.replace(" ", "_") extra_bindings.append( ( "link_file_list", gyp.common.EncodePOSIXShellArgument(link_file_list), ) ) if self.flavor == "win": extra_bindings.append(("binary", output)) if ( "/NOENTRY" not in ldflags and not self.msvs_settings.GetNoImportLibrary(config_name) ): self.target.import_lib = output + ".lib" extra_bindings.append( ("implibflag", "/IMPLIB:%s" % self.target.import_lib) ) pdbname = self.msvs_settings.GetPDBName( config_name, self.ExpandSpecial, output + ".pdb" ) output = [output, self.target.import_lib] if pdbname: output.append(pdbname) elif not self.is_mac_bundle: output = [output, output + ".TOC"] else: command = command + "_notoc" elif self.flavor == "win": extra_bindings.append(("binary", output)) pdbname = self.msvs_settings.GetPDBName( config_name, self.ExpandSpecial, output + ".pdb" ) if pdbname: output = [output, pdbname] if len(solibs): extra_bindings.append( ("solibs", gyp.common.EncodePOSIXShellList(sorted(solibs))) ) ninja_file.build( output, command + command_suffix, link_deps, implicit=sorted(implicit_deps), order_only=list(order_deps), variables=extra_bindings, ) return linked_binary def WriteTarget(self, spec, config_name, config, link_deps, compile_deps): extra_link_deps = any( self.target_outputs.get(dep).Linkable() for dep in spec.get("dependencies", []) if dep in self.target_outputs ) if spec["type"] == "none" or (not link_deps and not extra_link_deps): # TODO(evan): don't call this function for 'none' target types, as # it doesn't do anything, and we fake out a 'binary' with a stamp file. self.target.binary = compile_deps self.target.type = "none" elif spec["type"] == "static_library": self.target.binary = self.ComputeOutput(spec) if ( self.flavor not in ("ios", "mac", "netbsd", "openbsd", "win") and not self.is_standalone_static_library ): self.ninja.build( self.target.binary, "alink_thin", link_deps, order_only=compile_deps ) else: variables = [] if self.xcode_settings: libtool_flags = self.xcode_settings.GetLibtoolflags(config_name) if libtool_flags: variables.append(("libtool_flags", libtool_flags)) if self.msvs_settings: libflags = self.msvs_settings.GetLibFlags( config_name, self.GypPathToNinja ) variables.append(("libflags", libflags)) if self.flavor != "mac" or len(self.archs) == 1: self.AppendPostbuildVariable( variables, spec, self.target.binary, self.target.binary ) self.ninja.build( self.target.binary, "alink", link_deps, order_only=compile_deps, variables=variables, ) else: inputs = [] for arch in self.archs: output = self.ComputeOutput(spec, arch) self.arch_subninjas[arch].build( output, "alink", link_deps[arch], order_only=compile_deps, variables=variables, ) inputs.append(output) # TODO: It's not clear if # libtool_flags should be passed to the alink # call that combines single-arch .a files into a fat .a file. self.AppendPostbuildVariable( variables, spec, self.target.binary, self.target.binary ) self.ninja.build( self.target.binary, "alink", inputs, # FIXME: test proving order_only=compile_deps isn't # needed. variables=variables, ) else: self.target.binary = self.WriteLink( spec, config_name, config, link_deps, compile_deps ) return self.target.binary def WriteMacBundle(self, spec, mac_bundle_depends, is_empty): assert self.is_mac_bundle package_framework = spec["type"] in ("shared_library", "loadable_module") output = self.ComputeMacBundleOutput() if is_empty: output += ".stamp" variables = [] self.AppendPostbuildVariable( variables, spec, output, self.target.binary, is_command_start=not package_framework, ) if package_framework and not is_empty: if spec["type"] == "shared_library" and self.xcode_settings.isIOS: self.ninja.build( output, "package_ios_framework", mac_bundle_depends, variables=variables, ) else: variables.append(("version", self.xcode_settings.GetFrameworkVersion())) self.ninja.build( output, "package_framework", mac_bundle_depends, variables=variables ) else: self.ninja.build(output, "stamp", mac_bundle_depends, variables=variables) self.target.bundle = output return output def GetToolchainEnv(self, additional_settings=None): """Returns the variables toolchain would set for build steps.""" env = self.GetSortedXcodeEnv(additional_settings=additional_settings) if self.flavor == "win": env = self.GetMsvsToolchainEnv(additional_settings=additional_settings) return env def GetMsvsToolchainEnv(self, additional_settings=None): """Returns the variables Visual Studio would set for build steps.""" return self.msvs_settings.GetVSMacroEnv( "$!PRODUCT_DIR", config=self.config_name ) def GetSortedXcodeEnv(self, additional_settings=None): """Returns the variables Xcode would set for build steps.""" assert self.abs_build_dir abs_build_dir = self.abs_build_dir return gyp.xcode_emulation.GetSortedXcodeEnv( self.xcode_settings, abs_build_dir, os.path.join(abs_build_dir, self.build_to_base), self.config_name, additional_settings, ) def GetSortedXcodePostbuildEnv(self): """Returns the variables Xcode would set for postbuild steps.""" postbuild_settings = {} # CHROMIUM_STRIP_SAVE_FILE is a chromium-specific hack. # TODO(thakis): It would be nice to have some general mechanism instead. strip_save_file = self.xcode_settings.GetPerTargetSetting( "CHROMIUM_STRIP_SAVE_FILE" ) if strip_save_file: postbuild_settings["CHROMIUM_STRIP_SAVE_FILE"] = strip_save_file return self.GetSortedXcodeEnv(additional_settings=postbuild_settings) def AppendPostbuildVariable( self, variables, spec, output, binary, is_command_start=False ): """Adds a 'postbuild' variable if there is a postbuild for |output|.""" postbuild = self.GetPostbuildCommand(spec, output, binary, is_command_start) if postbuild: variables.append(("postbuilds", postbuild)) def GetPostbuildCommand(self, spec, output, output_binary, is_command_start): """Returns a shell command that runs all the postbuilds, and removes |output| if any of them fails. If |is_command_start| is False, then the returned string will start with ' && '.""" if not self.xcode_settings or spec["type"] == "none" or not output: return "" output = QuoteShellArgument(output, self.flavor) postbuilds = gyp.xcode_emulation.GetSpecPostbuildCommands(spec, quiet=True) if output_binary is not None: postbuilds = self.xcode_settings.AddImplicitPostbuilds( self.config_name, os.path.normpath(os.path.join(self.base_to_build, output)), QuoteShellArgument( os.path.normpath(os.path.join(self.base_to_build, output_binary)), self.flavor, ), postbuilds, quiet=True, ) if not postbuilds: return "" # Postbuilds expect to be run in the gyp file's directory, so insert an # implicit postbuild to cd to there. postbuilds.insert( 0, gyp.common.EncodePOSIXShellList(["cd", self.build_to_base]) ) env = self.ComputeExportEnvString(self.GetSortedXcodePostbuildEnv()) # G will be non-null if any postbuild fails. Run all postbuilds in a # subshell. commands = ( env + " (" + " && ".join([ninja_syntax.escape(command) for command in postbuilds]) ) command_string = ( commands + "); G=$$?; " # Remove the final output if any postbuild failed. "((exit $$G) || rm -rf %s) " % output + "&& exit $$G)" ) if is_command_start: return "(" + command_string + " && " else: return "$ && (" + command_string def ComputeExportEnvString(self, env): """Given an environment, returns a string looking like 'export FOO=foo; export BAR="${FOO} bar;' that exports |env| to the shell.""" export_str = [] for k, v in env: export_str.append( "export %s=%s;" % (k, ninja_syntax.escape(gyp.common.EncodePOSIXShellArgument(v))) ) return " ".join(export_str) def ComputeMacBundleOutput(self): """Return the 'output' (full output path) to a bundle output directory.""" assert self.is_mac_bundle path = generator_default_variables["PRODUCT_DIR"] return self.ExpandSpecial( os.path.join(path, self.xcode_settings.GetWrapperName()) ) def ComputeOutputFileName(self, spec, type=None): """Compute the filename of the final output for the current target.""" if not type: type = spec["type"] default_variables = copy.copy(generator_default_variables) CalculateVariables(default_variables, {"flavor": self.flavor}) # Compute filename prefix: the product prefix, or a default for # the product type. DEFAULT_PREFIX = { "loadable_module": default_variables["SHARED_LIB_PREFIX"], "shared_library": default_variables["SHARED_LIB_PREFIX"], "static_library": default_variables["STATIC_LIB_PREFIX"], "executable": default_variables["EXECUTABLE_PREFIX"], } prefix = spec.get("product_prefix", DEFAULT_PREFIX.get(type, "")) # Compute filename extension: the product extension, or a default # for the product type. DEFAULT_EXTENSION = { "loadable_module": default_variables["SHARED_LIB_SUFFIX"], "shared_library": default_variables["SHARED_LIB_SUFFIX"], "static_library": default_variables["STATIC_LIB_SUFFIX"], "executable": default_variables["EXECUTABLE_SUFFIX"], } extension = spec.get("product_extension") extension = "." + extension if extension else DEFAULT_EXTENSION.get(type, "") if "product_name" in spec: # If we were given an explicit name, use that. target = spec["product_name"] else: # Otherwise, derive a name from the target name. target = spec["target_name"] if prefix == "lib": # Snip out an extra 'lib' from libs if appropriate. target = StripPrefix(target, "lib") if type in ( "static_library", "loadable_module", "shared_library", "executable", ): return f"{prefix}{target}{extension}" elif type == "none": return "%s.stamp" % target else: raise Exception("Unhandled output type %s" % type) def ComputeOutput(self, spec, arch=None): """Compute the path for the final output of the spec.""" type = spec["type"] if self.flavor == "win": override = self.msvs_settings.GetOutputName( self.config_name, self.ExpandSpecial ) if override: return override if ( arch is None and self.flavor == "mac" and type in ("static_library", "executable", "shared_library", "loadable_module") ): filename = self.xcode_settings.GetExecutablePath() else: filename = self.ComputeOutputFileName(spec, type) if arch is None and "product_dir" in spec: path = os.path.join(spec["product_dir"], filename) return self.ExpandSpecial(path) # Some products go into the output root, libraries go into shared library # dir, and everything else goes into the normal place. type_in_output_root = ["executable", "loadable_module"] if self.flavor == "mac" and self.toolset == "target": type_in_output_root += ["shared_library", "static_library"] elif self.flavor == "win" and self.toolset == "target": type_in_output_root += ["shared_library"] if arch is not None: # Make sure partial executables don't end up in a bundle or the regular # output directory. archdir = "arch" if self.toolset != "target": archdir = os.path.join("arch", "%s" % self.toolset) return os.path.join(archdir, AddArch(filename, arch)) elif type in type_in_output_root or self.is_standalone_static_library: return filename elif type == "shared_library": libdir = "lib" if self.toolset != "target": libdir = os.path.join("lib", "%s" % self.toolset) return os.path.join(libdir, filename) else: return self.GypPathToUniqueOutput(filename, qualified=False) def WriteVariableList(self, ninja_file, var, values): assert not isinstance(values, str) if values is None: values = [] ninja_file.variable(var, " ".join(values)) def WriteNewNinjaRule( self, name, args, description, win_shell_flags, env, pool, depfile=None ): """Write out a new ninja "rule" statement for a given command. Returns the name of the new rule, and a copy of |args| with variables expanded.""" if self.flavor == "win": args = [ self.msvs_settings.ConvertVSMacros( arg, self.base_to_build, config=self.config_name ) for arg in args ] description = self.msvs_settings.ConvertVSMacros( description, config=self.config_name ) elif self.flavor == "mac": # |env| is an empty list on non-mac. args = [gyp.xcode_emulation.ExpandEnvVars(arg, env) for arg in args] description = gyp.xcode_emulation.ExpandEnvVars(description, env) # TODO: we shouldn't need to qualify names; we do it because # currently the ninja rule namespace is global, but it really # should be scoped to the subninja. rule_name = self.name if self.toolset == "target": rule_name += "." + self.toolset rule_name += "." + name rule_name = re.sub("[^a-zA-Z0-9_]", "_", rule_name) # Remove variable references, but not if they refer to the magic rule # variables. This is not quite right, as it also protects these for # actions, not just for rules where they are valid. Good enough. protect = ["${root}", "${dirname}", "${source}", "${ext}", "${name}"] protect = "(?!" + "|".join(map(re.escape, protect)) + ")" description = re.sub(protect + r"\$", "_", description) # gyp dictates that commands are run from the base directory. # cd into the directory before running, and adjust paths in # the arguments to point to the proper locations. rspfile = None rspfile_content = None args = [self.ExpandSpecial(arg, self.base_to_build) for arg in args] if self.flavor == "win": rspfile = rule_name + ".$unique_name.rsp" # The cygwin case handles this inside the bash sub-shell. run_in = "" if win_shell_flags.cygwin else " " + self.build_to_base if win_shell_flags.cygwin: rspfile_content = self.msvs_settings.BuildCygwinBashCommandLine( args, self.build_to_base ) else: rspfile_content = gyp.msvs_emulation.EncodeRspFileList( args, win_shell_flags.quote) command = ( "%s gyp-win-tool action-wrapper $arch " % sys.executable + rspfile + run_in ) else: env = self.ComputeExportEnvString(env) command = gyp.common.EncodePOSIXShellList(args) command = "cd %s; " % self.build_to_base + env + command # GYP rules/actions express being no-ops by not touching their outputs. # Avoid executing downstream dependencies in this case by specifying # restat=1 to ninja. self.ninja.rule( rule_name, command, description, depfile=depfile, restat=True, pool=pool, rspfile=rspfile, rspfile_content=rspfile_content, ) self.ninja.newline() return rule_name, args def CalculateVariables(default_variables, params): """Calculate additional variables for use in the build (called by gyp).""" global generator_additional_non_configuration_keys global generator_additional_path_sections flavor = gyp.common.GetFlavor(params) if flavor == "mac": default_variables.setdefault("OS", "mac") default_variables.setdefault("SHARED_LIB_SUFFIX", ".dylib") default_variables.setdefault( "SHARED_LIB_DIR", generator_default_variables["PRODUCT_DIR"] ) default_variables.setdefault( "LIB_DIR", generator_default_variables["PRODUCT_DIR"] ) # Copy additional generator configuration data from Xcode, which is shared # by the Mac Ninja generator. import gyp.generator.xcode as xcode_generator generator_additional_non_configuration_keys = getattr( xcode_generator, "generator_additional_non_configuration_keys", [] ) generator_additional_path_sections = getattr( xcode_generator, "generator_additional_path_sections", [] ) global generator_extra_sources_for_rules generator_extra_sources_for_rules = getattr( xcode_generator, "generator_extra_sources_for_rules", [] ) elif flavor == "win": exts = gyp.MSVSUtil.TARGET_TYPE_EXT default_variables.setdefault("OS", "win") default_variables["EXECUTABLE_SUFFIX"] = "." + exts["executable"] default_variables["STATIC_LIB_PREFIX"] = "" default_variables["STATIC_LIB_SUFFIX"] = "." + exts["static_library"] default_variables["SHARED_LIB_PREFIX"] = "" default_variables["SHARED_LIB_SUFFIX"] = "." + exts["shared_library"] # Copy additional generator configuration data from VS, which is shared # by the Windows Ninja generator. import gyp.generator.msvs as msvs_generator generator_additional_non_configuration_keys = getattr( msvs_generator, "generator_additional_non_configuration_keys", [] ) generator_additional_path_sections = getattr( msvs_generator, "generator_additional_path_sections", [] ) gyp.msvs_emulation.CalculateCommonVariables(default_variables, params) else: operating_system = flavor if flavor == "android": operating_system = "linux" # Keep this legacy behavior for now. default_variables.setdefault("OS", operating_system) default_variables.setdefault("SHARED_LIB_SUFFIX", ".so") default_variables.setdefault( "SHARED_LIB_DIR", os.path.join("$!PRODUCT_DIR", "lib") ) default_variables.setdefault("LIB_DIR", os.path.join("$!PRODUCT_DIR", "obj")) def ComputeOutputDir(params): """Returns the path from the toplevel_dir to the build output directory.""" # generator_dir: relative path from pwd to where make puts build files. # Makes migrating from make to ninja easier, ninja doesn't put anything here. generator_dir = os.path.relpath(params["options"].generator_output or ".") # output_dir: relative path from generator_dir to the build directory. output_dir = params.get("generator_flags", {}).get("output_dir", "out") # Relative path from source root to our output files. e.g. "out" return os.path.normpath(os.path.join(generator_dir, output_dir)) def CalculateGeneratorInputInfo(params): """Called by __init__ to initialize generator values based on params.""" # E.g. "out/gypfiles" toplevel = params["options"].toplevel_dir qualified_out_dir = os.path.normpath( os.path.join(toplevel, ComputeOutputDir(params), "gypfiles") ) global generator_filelist_paths generator_filelist_paths = { "toplevel": toplevel, "qualified_out_dir": qualified_out_dir, } def OpenOutput(path, mode="w"): """Open |path| for writing, creating directories if necessary.""" gyp.common.EnsureDirExists(path) return open(path, mode) def CommandWithWrapper(cmd, wrappers, prog): wrapper = wrappers.get(cmd, "") if wrapper: return wrapper + " " + prog return prog def GetDefaultConcurrentLinks(): """Returns a best-guess for a number of concurrent links.""" pool_size = int(os.environ.get("GYP_LINK_CONCURRENCY", 0)) if pool_size: return pool_size if sys.platform in ("win32", "cygwin"): import ctypes class MEMORYSTATUSEX(ctypes.Structure): _fields_ = [ ("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong), ("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong), ("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong), ("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong), ("sullAvailExtendedVirtual", ctypes.c_ulonglong), ] stat = MEMORYSTATUSEX() stat.dwLength = ctypes.sizeof(stat) ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat)) # VS 2015 uses 20% more working set than VS 2013 and can consume all RAM # on a 64 GiB machine. mem_limit = max(1, stat.ullTotalPhys // (5 * (2 ** 30))) # total / 5GiB hard_cap = max(1, int(os.environ.get("GYP_LINK_CONCURRENCY_MAX", 2 ** 32))) return min(mem_limit, hard_cap) elif sys.platform.startswith("linux"): if os.path.exists("/proc/meminfo"): with open("/proc/meminfo") as meminfo: memtotal_re = re.compile(r"^MemTotal:\s*(\d*)\s*kB") for line in meminfo: match = memtotal_re.match(line) if not match: continue # Allow 8Gb per link on Linux because Gold is quite memory hungry return max(1, int(match.group(1)) // (8 * (2 ** 20))) return 1 elif sys.platform == "darwin": try: avail_bytes = int(subprocess.check_output(["sysctl", "-n", "hw.memsize"])) # A static library debug build of Chromium's unit_tests takes ~2.7GB, so # 4GB per ld process allows for some more bloat. return max(1, avail_bytes // (4 * (2 ** 30))) # total / 4GB except subprocess.CalledProcessError: return 1 else: # TODO(scottmg): Implement this for other platforms. return 1 def _GetWinLinkRuleNameSuffix(embed_manifest): """Returns the suffix used to select an appropriate linking rule depending on whether the manifest embedding is enabled.""" return "_embed" if embed_manifest else "" def _AddWinLinkRules(master_ninja, embed_manifest): """Adds link rules for Windows platform to |master_ninja|.""" def FullLinkCommand(ldcmd, out, binary_type): resource_name = {"exe": "1", "dll": "2"}[binary_type] return ( "%(python)s gyp-win-tool link-with-manifests $arch %(embed)s " '%(out)s "%(ldcmd)s" %(resname)s $mt $rc "$intermediatemanifest" ' "$manifests" % { "python": sys.executable, "out": out, "ldcmd": ldcmd, "resname": resource_name, "embed": embed_manifest, } ) rule_name_suffix = _GetWinLinkRuleNameSuffix(embed_manifest) use_separate_mspdbsrv = int(os.environ.get("GYP_USE_SEPARATE_MSPDBSRV", "0")) != 0 dlldesc = "LINK%s(DLL) $binary" % rule_name_suffix.upper() dllcmd = ( "%s gyp-win-tool link-wrapper $arch %s " "$ld /nologo $implibflag /DLL /OUT:$binary " "@$binary.rsp" % (sys.executable, use_separate_mspdbsrv) ) dllcmd = FullLinkCommand(dllcmd, "$binary", "dll") master_ninja.rule( "solink" + rule_name_suffix, description=dlldesc, command=dllcmd, rspfile="$binary.rsp", rspfile_content="$libs $in_newline $ldflags", restat=True, pool="link_pool", ) master_ninja.rule( "solink_module" + rule_name_suffix, description=dlldesc, command=dllcmd, rspfile="$binary.rsp", rspfile_content="$libs $in_newline $ldflags", restat=True, pool="link_pool", ) # Note that ldflags goes at the end so that it has the option of # overriding default settings earlier in the command line. exe_cmd = ( "%s gyp-win-tool link-wrapper $arch %s " "$ld /nologo /OUT:$binary @$binary.rsp" % (sys.executable, use_separate_mspdbsrv) ) exe_cmd = FullLinkCommand(exe_cmd, "$binary", "exe") master_ninja.rule( "link" + rule_name_suffix, description="LINK%s $binary" % rule_name_suffix.upper(), command=exe_cmd, rspfile="$binary.rsp", rspfile_content="$in_newline $libs $ldflags", pool="link_pool", ) def GenerateOutputForConfig(target_list, target_dicts, data, params, config_name): options = params["options"] flavor = gyp.common.GetFlavor(params) generator_flags = params.get("generator_flags", {}) # build_dir: relative path from source root to our output files. # e.g. "out/Debug" build_dir = os.path.normpath(os.path.join(ComputeOutputDir(params), config_name)) toplevel_build = os.path.join(options.toplevel_dir, build_dir) master_ninja_file = OpenOutput(os.path.join(toplevel_build, "build.ninja")) master_ninja = ninja_syntax.Writer(master_ninja_file, width=120) # Put build-time support tools in out/{config_name}. gyp.common.CopyTool(flavor, toplevel_build, generator_flags) # Grab make settings for CC/CXX. # The rules are # - The priority from low to high is gcc/g++, the 'make_global_settings' in # gyp, the environment variable. # - If there is no 'make_global_settings' for CC.host/CXX.host or # 'CC_host'/'CXX_host' environment variable, cc_host/cxx_host should be set # to cc/cxx. if flavor == "win": ar = "lib.exe" # cc and cxx must be set to the correct architecture by overriding with one # of cl_x86 or cl_x64 below. cc = "UNSET" cxx = "UNSET" ld = "link.exe" ld_host = "$ld" else: ar = "ar" cc = "cc" cxx = "c++" ld = "$cc" ldxx = "$cxx" ld_host = "$cc_host" ldxx_host = "$cxx_host" ar_host = ar cc_host = None cxx_host = None cc_host_global_setting = None cxx_host_global_setting = None clang_cl = None nm = "nm" nm_host = "nm" readelf = "readelf" readelf_host = "readelf" build_file, _, _ = gyp.common.ParseQualifiedTarget(target_list[0]) make_global_settings = data[build_file].get("make_global_settings", []) build_to_root = gyp.common.InvertRelativePath(build_dir, options.toplevel_dir) wrappers = {} for key, value in make_global_settings: if key == "AR": ar = os.path.join(build_to_root, value) if key == "AR.host": ar_host = os.path.join(build_to_root, value) if key == "CC": cc = os.path.join(build_to_root, value) if cc.endswith("clang-cl"): clang_cl = cc if key == "CXX": cxx = os.path.join(build_to_root, value) if key == "CC.host": cc_host = os.path.join(build_to_root, value) cc_host_global_setting = value if key == "CXX.host": cxx_host = os.path.join(build_to_root, value) cxx_host_global_setting = value if key == "LD": ld = os.path.join(build_to_root, value) if key == "LD.host": ld_host = os.path.join(build_to_root, value) if key == "LDXX": ldxx = os.path.join(build_to_root, value) if key == "LDXX.host": ldxx_host = os.path.join(build_to_root, value) if key == "NM": nm = os.path.join(build_to_root, value) if key == "NM.host": nm_host = os.path.join(build_to_root, value) if key == "READELF": readelf = os.path.join(build_to_root, value) if key == "READELF.host": readelf_host = os.path.join(build_to_root, value) if key.endswith("_wrapper"): wrappers[key[: -len("_wrapper")]] = os.path.join(build_to_root, value) # Support wrappers from environment variables too. for key, value in os.environ.items(): if key.lower().endswith("_wrapper"): key_prefix = key[: -len("_wrapper")] key_prefix = re.sub(r"\.HOST$", ".host", key_prefix) wrappers[key_prefix] = os.path.join(build_to_root, value) mac_toolchain_dir = generator_flags.get("mac_toolchain_dir", None) if mac_toolchain_dir: wrappers["LINK"] = "export DEVELOPER_DIR='%s' &&" % mac_toolchain_dir if flavor == "win": configs = [ target_dicts[qualified_target]["configurations"][config_name] for qualified_target in target_list ] shared_system_includes = None if not generator_flags.get("ninja_use_custom_environment_files", 0): shared_system_includes = gyp.msvs_emulation.ExtractSharedMSVSSystemIncludes( configs, generator_flags ) cl_paths = gyp.msvs_emulation.GenerateEnvironmentFiles( toplevel_build, generator_flags, shared_system_includes, OpenOutput ) for arch, path in sorted(cl_paths.items()): if clang_cl: # If we have selected clang-cl, use that instead. path = clang_cl command = CommandWithWrapper( "CC", wrappers, QuoteShellArgument(path, "win") ) if clang_cl: # Use clang-cl to cross-compile for x86 or x86_64. command += " -m32" if arch == "x86" else " -m64" master_ninja.variable("cl_" + arch, command) cc = GetEnvironFallback(["CC_target", "CC"], cc) master_ninja.variable("cc", CommandWithWrapper("CC", wrappers, cc)) cxx = GetEnvironFallback(["CXX_target", "CXX"], cxx) master_ninja.variable("cxx", CommandWithWrapper("CXX", wrappers, cxx)) if flavor == "win": master_ninja.variable("ld", ld) master_ninja.variable("idl", "midl.exe") master_ninja.variable("ar", ar) master_ninja.variable("rc", "rc.exe") master_ninja.variable("ml_x86", "ml.exe") master_ninja.variable("ml_x64", "ml64.exe") master_ninja.variable("mt", "mt.exe") else: master_ninja.variable("ld", CommandWithWrapper("LINK", wrappers, ld)) master_ninja.variable("ldxx", CommandWithWrapper("LINK", wrappers, ldxx)) master_ninja.variable("ar", GetEnvironFallback(["AR_target", "AR"], ar)) if flavor != "mac": # Mac does not use readelf/nm for .TOC generation, so avoiding polluting # the master ninja with extra unused variables. master_ninja.variable("nm", GetEnvironFallback(["NM_target", "NM"], nm)) master_ninja.variable( "readelf", GetEnvironFallback(["READELF_target", "READELF"], readelf) ) if generator_supports_multiple_toolsets: if not cc_host: cc_host = cc if not cxx_host: cxx_host = cxx master_ninja.variable("ar_host", GetEnvironFallback(["AR_host"], ar_host)) master_ninja.variable("nm_host", GetEnvironFallback(["NM_host"], nm_host)) master_ninja.variable( "readelf_host", GetEnvironFallback(["READELF_host"], readelf_host) ) cc_host = GetEnvironFallback(["CC_host"], cc_host) cxx_host = GetEnvironFallback(["CXX_host"], cxx_host) # The environment variable could be used in 'make_global_settings', like # ['CC.host', '$(CC)'] or ['CXX.host', '$(CXX)'], transform them here. if "$(CC)" in cc_host and cc_host_global_setting: cc_host = cc_host_global_setting.replace("$(CC)", cc) if "$(CXX)" in cxx_host and cxx_host_global_setting: cxx_host = cxx_host_global_setting.replace("$(CXX)", cxx) master_ninja.variable( "cc_host", CommandWithWrapper("CC.host", wrappers, cc_host) ) master_ninja.variable( "cxx_host", CommandWithWrapper("CXX.host", wrappers, cxx_host) ) if flavor == "win": master_ninja.variable("ld_host", ld_host) else: master_ninja.variable( "ld_host", CommandWithWrapper("LINK", wrappers, ld_host) ) master_ninja.variable( "ldxx_host", CommandWithWrapper("LINK", wrappers, ldxx_host) ) master_ninja.newline() master_ninja.pool("link_pool", depth=GetDefaultConcurrentLinks()) master_ninja.newline() deps = "msvc" if flavor == "win" else "gcc" if flavor != "win": master_ninja.rule( "cc", description="CC $out", command=( "$cc -MMD -MF $out.d $defines $includes $cflags $cflags_c " "$cflags_pch_c -c $in -o $out" ), depfile="$out.d", deps=deps, ) master_ninja.rule( "cc_s", description="CC $out", command=( "$cc $defines $includes $cflags $cflags_c " "$cflags_pch_c -c $in -o $out" ), ) master_ninja.rule( "cxx", description="CXX $out", command=( "$cxx -MMD -MF $out.d $defines $includes $cflags $cflags_cc " "$cflags_pch_cc -c $in -o $out" ), depfile="$out.d", deps=deps, ) else: # TODO(scottmg) Separate pdb names is a test to see if it works around # http://crbug.com/142362. It seems there's a race between the creation of # the .pdb by the precompiled header step for .cc and the compilation of # .c files. This should be handled by mspdbsrv, but rarely errors out with # c1xx : fatal error C1033: cannot open program database # By making the rules target separate pdb files this might be avoided. cc_command = ( "ninja -t msvc -e $arch " + "-- " "$cc /nologo /showIncludes /FC " "@$out.rsp /c $in /Fo$out /Fd$pdbname_c " ) cxx_command = ( "ninja -t msvc -e $arch " + "-- " "$cxx /nologo /showIncludes /FC " "@$out.rsp /c $in /Fo$out /Fd$pdbname_cc " ) master_ninja.rule( "cc", description="CC $out", command=cc_command, rspfile="$out.rsp", rspfile_content="$defines $includes $cflags $cflags_c", deps=deps, ) master_ninja.rule( "cxx", description="CXX $out", command=cxx_command, rspfile="$out.rsp", rspfile_content="$defines $includes $cflags $cflags_cc", deps=deps, ) master_ninja.rule( "idl", description="IDL $in", command=( "%s gyp-win-tool midl-wrapper $arch $outdir " "$tlb $h $dlldata $iid $proxy $in " "$midl_includes $idlflags" % sys.executable ), ) master_ninja.rule( "rc", description="RC $in", # Note: $in must be last otherwise rc.exe complains. command=( "%s gyp-win-tool rc-wrapper " "$arch $rc $defines $resource_includes $rcflags /fo$out $in" % sys.executable ), ) master_ninja.rule( "asm", description="ASM $out", command=( "%s gyp-win-tool asm-wrapper " "$arch $asm $defines $includes $asmflags /c /Fo $out $in" % sys.executable ), ) if flavor not in ("ios", "mac", "win"): master_ninja.rule( "alink", description="AR $out", command="rm -f $out && $ar rcs $arflags $out $in", ) master_ninja.rule( "alink_thin", description="AR $out", command="rm -f $out && $ar rcsT $arflags $out $in", ) # This allows targets that only need to depend on $lib's API to declare an # order-only dependency on $lib.TOC and avoid relinking such downstream # dependencies when $lib changes only in non-public ways. # The resulting string leaves an uninterpolated %{suffix} which # is used in the final substitution below. mtime_preserving_solink_base = ( "if [ ! -e $lib -o ! -e $lib.TOC ]; then " "%(solink)s && %(extract_toc)s > $lib.TOC; else " "%(solink)s && %(extract_toc)s > $lib.tmp && " "if ! cmp -s $lib.tmp $lib.TOC; then mv $lib.tmp $lib.TOC ; " "fi; fi" % { "solink": "$ld -shared $ldflags -o $lib -Wl,-soname=$soname %(suffix)s", "extract_toc": ( "{ $readelf -d $lib | grep SONAME ; " "$nm -gD -f p $lib | cut -f1-2 -d' '; }" ), } ) master_ninja.rule( "solink", description="SOLINK $lib", restat=True, command=mtime_preserving_solink_base % {"suffix": "@$link_file_list"}, rspfile="$link_file_list", rspfile_content=( "-Wl,--whole-archive $in $solibs -Wl," "--no-whole-archive $libs" ), pool="link_pool", ) master_ninja.rule( "solink_module", description="SOLINK(module) $lib", restat=True, command=mtime_preserving_solink_base % {"suffix": "@$link_file_list"}, rspfile="$link_file_list", rspfile_content="-Wl,--start-group $in $solibs $libs -Wl,--end-group", pool="link_pool", ) master_ninja.rule( "link", description="LINK $out", command=( "$ld $ldflags -o $out " "-Wl,--start-group $in $solibs $libs -Wl,--end-group" ), pool="link_pool", ) elif flavor == "win": master_ninja.rule( "alink", description="LIB $out", command=( "%s gyp-win-tool link-wrapper $arch False " "$ar /nologo /ignore:4221 /OUT:$out @$out.rsp" % sys.executable ), rspfile="$out.rsp", rspfile_content="$in_newline $libflags", ) _AddWinLinkRules(master_ninja, embed_manifest=True) _AddWinLinkRules(master_ninja, embed_manifest=False) else: master_ninja.rule( "objc", description="OBJC $out", command=( "$cc -MMD -MF $out.d $defines $includes $cflags $cflags_objc " "$cflags_pch_objc -c $in -o $out" ), depfile="$out.d", deps=deps, ) master_ninja.rule( "objcxx", description="OBJCXX $out", command=( "$cxx -MMD -MF $out.d $defines $includes $cflags $cflags_objcc " "$cflags_pch_objcc -c $in -o $out" ), depfile="$out.d", deps=deps, ) master_ninja.rule( "alink", description="LIBTOOL-STATIC $out, POSTBUILDS", command="rm -f $out && " "./gyp-mac-tool filter-libtool libtool $libtool_flags " "-static -o $out $in" "$postbuilds", ) master_ninja.rule( "lipo", description="LIPO $out, POSTBUILDS", command="rm -f $out && lipo -create $in -output $out$postbuilds", ) master_ninja.rule( "solipo", description="SOLIPO $out, POSTBUILDS", command=( "rm -f $lib $lib.TOC && lipo -create $in -output $lib$postbuilds &&" "%(extract_toc)s > $lib.TOC" % { "extract_toc": "{ otool -l $lib | grep LC_ID_DYLIB -A 5; " "nm -gP $lib | cut -f1-2 -d' ' | grep -v U$$; true; }" } ), ) # Record the public interface of $lib in $lib.TOC. See the corresponding # comment in the posix section above for details. solink_base = "$ld %(type)s $ldflags -o $lib %(suffix)s" mtime_preserving_solink_base = ( "if [ ! -e $lib -o ! -e $lib.TOC ] || " # Always force dependent targets to relink if this library # reexports something. Handling this correctly would require # recursive TOC dumping but this is rare in practice, so punt. "otool -l $lib | grep -q LC_REEXPORT_DYLIB ; then " "%(solink)s && %(extract_toc)s > $lib.TOC; " "else " "%(solink)s && %(extract_toc)s > $lib.tmp && " "if ! cmp -s $lib.tmp $lib.TOC; then " "mv $lib.tmp $lib.TOC ; " "fi; " "fi" % { "solink": solink_base, "extract_toc": "{ otool -l $lib | grep LC_ID_DYLIB -A 5; " "nm -gP $lib | cut -f1-2 -d' ' | grep -v U$$; true; }", } ) solink_suffix = "@$link_file_list$postbuilds" master_ninja.rule( "solink", description="SOLINK $lib, POSTBUILDS", restat=True, command=mtime_preserving_solink_base % {"suffix": solink_suffix, "type": "-shared"}, rspfile="$link_file_list", rspfile_content="$in $solibs $libs", pool="link_pool", ) master_ninja.rule( "solink_notoc", description="SOLINK $lib, POSTBUILDS", restat=True, command=solink_base % {"suffix": solink_suffix, "type": "-shared"}, rspfile="$link_file_list", rspfile_content="$in $solibs $libs", pool="link_pool", ) master_ninja.rule( "solink_module", description="SOLINK(module) $lib, POSTBUILDS", restat=True, command=mtime_preserving_solink_base % {"suffix": solink_suffix, "type": "-bundle"}, rspfile="$link_file_list", rspfile_content="$in $solibs $libs", pool="link_pool", ) master_ninja.rule( "solink_module_notoc", description="SOLINK(module) $lib, POSTBUILDS", restat=True, command=solink_base % {"suffix": solink_suffix, "type": "-bundle"}, rspfile="$link_file_list", rspfile_content="$in $solibs $libs", pool="link_pool", ) master_ninja.rule( "link", description="LINK $out, POSTBUILDS", command=("$ld $ldflags -o $out " "$in $solibs $libs$postbuilds"), pool="link_pool", ) master_ninja.rule( "preprocess_infoplist", description="PREPROCESS INFOPLIST $out", command=( "$cc -E -P -Wno-trigraphs -x c $defines $in -o $out && " "plutil -convert xml1 $out $out" ), ) master_ninja.rule( "copy_infoplist", description="COPY INFOPLIST $in", command="$env ./gyp-mac-tool copy-info-plist $in $out $binary $keys", ) master_ninja.rule( "merge_infoplist", description="MERGE INFOPLISTS $in", command="$env ./gyp-mac-tool merge-info-plist $out $in", ) master_ninja.rule( "compile_xcassets", description="COMPILE XCASSETS $in", command="$env ./gyp-mac-tool compile-xcassets $keys $in", ) master_ninja.rule( "compile_ios_framework_headers", description="COMPILE HEADER MAPS AND COPY FRAMEWORK HEADERS $in", command="$env ./gyp-mac-tool compile-ios-framework-header-map $out " "$framework $in && $env ./gyp-mac-tool " "copy-ios-framework-headers $framework $copy_headers", ) master_ninja.rule( "mac_tool", description="MACTOOL $mactool_cmd $in", command="$env ./gyp-mac-tool $mactool_cmd $in $out $binary", ) master_ninja.rule( "package_framework", description="PACKAGE FRAMEWORK $out, POSTBUILDS", command="./gyp-mac-tool package-framework $out $version$postbuilds " "&& touch $out", ) master_ninja.rule( "package_ios_framework", description="PACKAGE IOS FRAMEWORK $out, POSTBUILDS", command="./gyp-mac-tool package-ios-framework $out $postbuilds " "&& touch $out", ) if flavor == "win": master_ninja.rule( "stamp", description="STAMP $out", command="%s gyp-win-tool stamp $out" % sys.executable, ) else: master_ninja.rule( "stamp", description="STAMP $out", command="${postbuilds}touch $out" ) if flavor == "win": master_ninja.rule( "copy", description="COPY $in $out", command="%s gyp-win-tool recursive-mirror $in $out" % sys.executable, ) elif flavor == "zos": master_ninja.rule( "copy", description="COPY $in $out", command="rm -rf $out && cp -fRP $in $out", ) else: master_ninja.rule( "copy", description="COPY $in $out", command="ln -f $in $out 2>/dev/null || (rm -rf $out && cp -af $in $out)", ) master_ninja.newline() all_targets = set() for build_file in params["build_files"]: for target in gyp.common.AllTargets( target_list, target_dicts, os.path.normpath(build_file) ): all_targets.add(target) all_outputs = set() # target_outputs is a map from qualified target name to a Target object. target_outputs = {} # target_short_names is a map from target short name to a list of Target # objects. target_short_names = {} # short name of targets that were skipped because they didn't contain anything # interesting. # NOTE: there may be overlap between this an non_empty_target_names. empty_target_names = set() # Set of non-empty short target names. # NOTE: there may be overlap between this an empty_target_names. non_empty_target_names = set() for qualified_target in target_list: # qualified_target is like: third_party/icu/icu.gyp:icui18n#target build_file, name, toolset = gyp.common.ParseQualifiedTarget(qualified_target) this_make_global_settings = data[build_file].get("make_global_settings", []) assert make_global_settings == this_make_global_settings, ( "make_global_settings needs to be the same for all targets. " f"{this_make_global_settings} vs. {make_global_settings}" ) spec = target_dicts[qualified_target] if flavor == "mac": gyp.xcode_emulation.MergeGlobalXcodeSettingsToSpec(data[build_file], spec) # If build_file is a symlink, we must not follow it because there's a chance # it could point to a path above toplevel_dir, and we cannot correctly deal # with that case at the moment. build_file = gyp.common.RelativePath(build_file, options.toplevel_dir, False) qualified_target_for_hash = gyp.common.QualifiedTarget( build_file, name, toolset ) qualified_target_for_hash = qualified_target_for_hash.encode("utf-8") hash_for_rules = hashlib.md5(qualified_target_for_hash).hexdigest() base_path = os.path.dirname(build_file) obj = "obj" if toolset != "target": obj += "." + toolset output_file = os.path.join(obj, base_path, name + ".ninja") ninja_output = StringIO() writer = NinjaWriter( hash_for_rules, target_outputs, base_path, build_dir, ninja_output, toplevel_build, output_file, flavor, toplevel_dir=options.toplevel_dir, ) target = writer.WriteSpec(spec, config_name, generator_flags) if ninja_output.tell() > 0: # Only create files for ninja files that actually have contents. with OpenOutput(os.path.join(toplevel_build, output_file)) as ninja_file: ninja_file.write(ninja_output.getvalue()) ninja_output.close() master_ninja.subninja(output_file) if target: if name != target.FinalOutput() and spec["toolset"] == "target": target_short_names.setdefault(name, []).append(target) target_outputs[qualified_target] = target if qualified_target in all_targets: all_outputs.add(target.FinalOutput()) non_empty_target_names.add(name) else: empty_target_names.add(name) if target_short_names: # Write a short name to build this target. This benefits both the # "build chrome" case as well as the gyp tests, which expect to be # able to run actions and build libraries by their short name. master_ninja.newline() master_ninja.comment("Short names for targets.") for short_name in sorted(target_short_names): master_ninja.build( short_name, "phony", [x.FinalOutput() for x in target_short_names[short_name]], ) # Write phony targets for any empty targets that weren't written yet. As # short names are not necessarily unique only do this for short names that # haven't already been output for another target. empty_target_names = empty_target_names - non_empty_target_names if empty_target_names: master_ninja.newline() master_ninja.comment("Empty targets (output for completeness).") for name in sorted(empty_target_names): master_ninja.build(name, "phony") if all_outputs: master_ninja.newline() master_ninja.build("all", "phony", sorted(all_outputs)) master_ninja.default(generator_flags.get("default_target", "all")) master_ninja_file.close() def PerformBuild(data, configurations, params): options = params["options"] for config in configurations: builddir = os.path.join(options.toplevel_dir, "out", config) arguments = ["ninja", "-C", builddir] print(f"Building [{config}]: {arguments}") subprocess.check_call(arguments) def CallGenerateOutputForConfig(arglist): # Ignore the interrupt signal so that the parent process catches it and # kills all multiprocessing children. signal.signal(signal.SIGINT, signal.SIG_IGN) (target_list, target_dicts, data, params, config_name) = arglist GenerateOutputForConfig(target_list, target_dicts, data, params, config_name) def GenerateOutput(target_list, target_dicts, data, params): # Update target_dicts for iOS device builds. target_dicts = gyp.xcode_emulation.CloneConfigurationForDeviceAndEmulator( target_dicts ) user_config = params.get("generator_flags", {}).get("config", None) if gyp.common.GetFlavor(params) == "win": target_list, target_dicts = MSVSUtil.ShardTargets(target_list, target_dicts) target_list, target_dicts = MSVSUtil.InsertLargePdbShims( target_list, target_dicts, generator_default_variables ) if user_config: GenerateOutputForConfig(target_list, target_dicts, data, params, user_config) else: config_names = target_dicts[target_list[0]]["configurations"] if params["parallel"]: try: pool = multiprocessing.Pool(len(config_names)) arglists = [] for config_name in config_names: arglists.append( (target_list, target_dicts, data, params, config_name) ) pool.map(CallGenerateOutputForConfig, arglists) except KeyboardInterrupt as e: pool.terminate() raise e else: for config_name in config_names: GenerateOutputForConfig( target_list, target_dicts, data, params, config_name ) PK ~\'3\)node-gyp/gyp/pylib/gyp/generator/gypsh.pynu[# Copyright (c) 2011 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """gypsh output module gypsh is a GYP shell. It's not really a generator per se. All it does is fire up an interactive Python session with a few local variables set to the variables passed to the generator. Like gypd, it's intended as a debugging aid, to facilitate the exploration of .gyp structures after being processed by the input module. The expected usage is "gyp -f gypsh -D OS=desired_os". """ import code import sys # All of this stuff about generator variables was lovingly ripped from gypd.py. # That module has a much better description of what's going on and why. _generator_identity_variables = [ "EXECUTABLE_PREFIX", "EXECUTABLE_SUFFIX", "INTERMEDIATE_DIR", "PRODUCT_DIR", "RULE_INPUT_ROOT", "RULE_INPUT_DIRNAME", "RULE_INPUT_EXT", "RULE_INPUT_NAME", "RULE_INPUT_PATH", "SHARED_INTERMEDIATE_DIR", ] generator_default_variables = {} for v in _generator_identity_variables: generator_default_variables[v] = "<(%s)" % v def GenerateOutput(target_list, target_dicts, data, params): locals = { "target_list": target_list, "target_dicts": target_dicts, "data": data, } # Use a banner that looks like the stock Python one and like what # code.interact uses by default, but tack on something to indicate what # locals are available, and identify gypsh. banner = ( f"Python {sys.version} on {sys.platform}\nlocals.keys() = " f"{repr(sorted(locals.keys()))}\ngypsh" ) code.interact(banner, local=locals) PK ~\rGJ{J{,node-gyp/gyp/pylib/gyp/generator/analyzer.pynu[# Copyright (c) 2014 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ This script is intended for use as a GYP_GENERATOR. It takes as input (by way of the generator flag config_path) the path of a json file that dictates the files and targets to search for. The following keys are supported: files: list of paths (relative) of the files to search for. test_targets: unqualified target names to search for. Any target in this list that depends upon a file in |files| is output regardless of the type of target or chain of dependencies. additional_compile_targets: Unqualified targets to search for in addition to test_targets. Targets in the combined list that depend upon a file in |files| are not necessarily output. For example, if the target is of type none then the target is not output (but one of the descendants of the target will be). The following is output: error: only supplied if there is an error. compile_targets: minimal set of targets that directly or indirectly (for targets of type none) depend on the files in |files| and is one of the supplied targets or a target that one of the supplied targets depends on. The expectation is this set of targets is passed into a build step. This list always contains the output of test_targets as well. test_targets: set of targets from the supplied |test_targets| that either directly or indirectly depend upon a file in |files|. This list if useful if additional processing needs to be done for certain targets after the build, such as running tests. status: outputs one of three values: none of the supplied files were found, one of the include files changed so that it should be assumed everything changed (in this case test_targets and compile_targets are not output) or at least one file was found. invalid_targets: list of supplied targets that were not found. Example: Consider a graph like the following: A D / \ B C A depends upon both B and C, A is of type none and B and C are executables. D is an executable, has no dependencies and nothing depends on it. If |additional_compile_targets| = ["A"], |test_targets| = ["B", "C"] and files = ["b.cc", "d.cc"] (B depends upon b.cc and D depends upon d.cc), then the following is output: |compile_targets| = ["B"] B must built as it depends upon the changed file b.cc and the supplied target A depends upon it. A is not output as a build_target as it is of type none with no rules and actions. |test_targets| = ["B"] B directly depends upon the change file b.cc. Even though the file d.cc, which D depends upon, has changed D is not output as it was not supplied by way of |additional_compile_targets| or |test_targets|. If the generator flag analyzer_output_path is specified, output is written there. Otherwise output is written to stdout. In Gyp the "all" target is shorthand for the root targets in the files passed to gyp. For example, if file "a.gyp" contains targets "a1" and "a2", and file "b.gyp" contains targets "b1" and "b2" and "a2" has a dependency on "b2" and gyp is supplied "a.gyp" then "all" consists of "a1" and "a2". Notice that "b1" and "b2" are not in the "all" target as "b.gyp" was not directly supplied to gyp. OTOH if both "a.gyp" and "b.gyp" are supplied to gyp then the "all" target includes "b1" and "b2". """ import gyp.common import json import os import posixpath debug = False found_dependency_string = "Found dependency" no_dependency_string = "No dependencies" # Status when it should be assumed that everything has changed. all_changed_string = "Found dependency (all)" # MatchStatus is used indicate if and how a target depends upon the supplied # sources. # The target's sources contain one of the supplied paths. MATCH_STATUS_MATCHES = 1 # The target has a dependency on another target that contains one of the # supplied paths. MATCH_STATUS_MATCHES_BY_DEPENDENCY = 2 # The target's sources weren't in the supplied paths and none of the target's # dependencies depend upon a target that matched. MATCH_STATUS_DOESNT_MATCH = 3 # The target doesn't contain the source, but the dependent targets have not yet # been visited to determine a more specific status yet. MATCH_STATUS_TBD = 4 generator_supports_multiple_toolsets = gyp.common.CrossCompileRequested() generator_wants_static_library_dependencies_adjusted = False generator_default_variables = {} for dirname in [ "INTERMEDIATE_DIR", "SHARED_INTERMEDIATE_DIR", "PRODUCT_DIR", "LIB_DIR", "SHARED_LIB_DIR", ]: generator_default_variables[dirname] = "!!!" for unused in [ "RULE_INPUT_PATH", "RULE_INPUT_ROOT", "RULE_INPUT_NAME", "RULE_INPUT_DIRNAME", "RULE_INPUT_EXT", "EXECUTABLE_PREFIX", "EXECUTABLE_SUFFIX", "STATIC_LIB_PREFIX", "STATIC_LIB_SUFFIX", "SHARED_LIB_PREFIX", "SHARED_LIB_SUFFIX", "CONFIGURATION_NAME", ]: generator_default_variables[unused] = "" def _ToGypPath(path): """Converts a path to the format used by gyp.""" if os.sep == "\\" and os.altsep == "/": return path.replace("\\", "/") return path def _ResolveParent(path, base_path_components): """Resolves |path|, which starts with at least one '../'. Returns an empty string if the path shouldn't be considered. See _AddSources() for a description of |base_path_components|.""" depth = 0 while path.startswith("../"): depth += 1 path = path[3:] # Relative includes may go outside the source tree. For example, an action may # have inputs in /usr/include, which are not in the source tree. if depth > len(base_path_components): return "" if depth == len(base_path_components): return path return ( "/".join(base_path_components[0 : len(base_path_components) - depth]) + "/" + path ) def _AddSources(sources, base_path, base_path_components, result): """Extracts valid sources from |sources| and adds them to |result|. Each source file is relative to |base_path|, but may contain '..'. To make resolving '..' easier |base_path_components| contains each of the directories in |base_path|. Additionally each source may contain variables. Such sources are ignored as it is assumed dependencies on them are expressed and tracked in some other means.""" # NOTE: gyp paths are always posix style. for source in sources: if not len(source) or source.startswith("!!!") or source.startswith("$"): continue # variable expansion may lead to //. org_source = source source = source[0] + source[1:].replace("//", "/") if source.startswith("../"): source = _ResolveParent(source, base_path_components) if len(source): result.append(source) continue result.append(base_path + source) if debug: print("AddSource", org_source, result[len(result) - 1]) def _ExtractSourcesFromAction(action, base_path, base_path_components, results): if "inputs" in action: _AddSources(action["inputs"], base_path, base_path_components, results) def _ToLocalPath(toplevel_dir, path): """Converts |path| to a path relative to |toplevel_dir|.""" if path == toplevel_dir: return "" if path.startswith(toplevel_dir + "/"): return path[len(toplevel_dir) + len("/") :] return path def _ExtractSources(target, target_dict, toplevel_dir): # |target| is either absolute or relative and in the format of the OS. Gyp # source paths are always posix. Convert |target| to a posix path relative to # |toplevel_dir_|. This is done to make it easy to build source paths. base_path = posixpath.dirname(_ToLocalPath(toplevel_dir, _ToGypPath(target))) base_path_components = base_path.split("/") # Add a trailing '/' so that _AddSources() can easily build paths. if len(base_path): base_path += "/" if debug: print("ExtractSources", target, base_path) results = [] if "sources" in target_dict: _AddSources(target_dict["sources"], base_path, base_path_components, results) # Include the inputs from any actions. Any changes to these affect the # resulting output. if "actions" in target_dict: for action in target_dict["actions"]: _ExtractSourcesFromAction(action, base_path, base_path_components, results) if "rules" in target_dict: for rule in target_dict["rules"]: _ExtractSourcesFromAction(rule, base_path, base_path_components, results) return results class Target: """Holds information about a particular target: deps: set of Targets this Target depends upon. This is not recursive, only the direct dependent Targets. match_status: one of the MatchStatus values. back_deps: set of Targets that have a dependency on this Target. visited: used during iteration to indicate whether we've visited this target. This is used for two iterations, once in building the set of Targets and again in _GetBuildTargets(). name: fully qualified name of the target. requires_build: True if the target type is such that it needs to be built. See _DoesTargetTypeRequireBuild for details. added_to_compile_targets: used when determining if the target was added to the set of targets that needs to be built. in_roots: true if this target is a descendant of one of the root nodes. is_executable: true if the type of target is executable. is_static_library: true if the type of target is static_library. is_or_has_linked_ancestor: true if the target does a link (eg executable), or if there is a target in back_deps that does a link.""" def __init__(self, name): self.deps = set() self.match_status = MATCH_STATUS_TBD self.back_deps = set() self.name = name # TODO(sky): I don't like hanging this off Target. This state is specific # to certain functions and should be isolated there. self.visited = False self.requires_build = False self.added_to_compile_targets = False self.in_roots = False self.is_executable = False self.is_static_library = False self.is_or_has_linked_ancestor = False class Config: """Details what we're looking for files: set of files to search for targets: see file description for details.""" def __init__(self): self.files = [] self.targets = set() self.additional_compile_target_names = set() self.test_target_names = set() def Init(self, params): """Initializes Config. This is a separate method as it raises an exception if there is a parse error.""" generator_flags = params.get("generator_flags", {}) config_path = generator_flags.get("config_path", None) if not config_path: return try: f = open(config_path) config = json.load(f) f.close() except OSError: raise Exception("Unable to open file " + config_path) except ValueError as e: raise Exception("Unable to parse config file " + config_path + str(e)) if not isinstance(config, dict): raise Exception("config_path must be a JSON file containing a dictionary") self.files = config.get("files", []) self.additional_compile_target_names = set( config.get("additional_compile_targets", []) ) self.test_target_names = set(config.get("test_targets", [])) def _WasBuildFileModified(build_file, data, files, toplevel_dir): """Returns true if the build file |build_file| is either in |files| or one of the files included by |build_file| is in |files|. |toplevel_dir| is the root of the source tree.""" if _ToLocalPath(toplevel_dir, _ToGypPath(build_file)) in files: if debug: print("gyp file modified", build_file) return True # First element of included_files is the file itself. if len(data[build_file]["included_files"]) <= 1: return False for include_file in data[build_file]["included_files"][1:]: # |included_files| are relative to the directory of the |build_file|. rel_include_file = _ToGypPath( gyp.common.UnrelativePath(include_file, build_file) ) if _ToLocalPath(toplevel_dir, rel_include_file) in files: if debug: print( "included gyp file modified, gyp_file=", build_file, "included file=", rel_include_file, ) return True return False def _GetOrCreateTargetByName(targets, target_name): """Creates or returns the Target at targets[target_name]. If there is no Target for |target_name| one is created. Returns a tuple of whether a new Target was created and the Target.""" if target_name in targets: return False, targets[target_name] target = Target(target_name) targets[target_name] = target return True, target def _DoesTargetTypeRequireBuild(target_dict): """Returns true if the target type is such that it needs to be built.""" # If a 'none' target has rules or actions we assume it requires a build. return bool( target_dict["type"] != "none" or target_dict.get("actions") or target_dict.get("rules") ) def _GenerateTargets(data, target_list, target_dicts, toplevel_dir, files, build_files): """Returns a tuple of the following: . A dictionary mapping from fully qualified name to Target. . A list of the targets that have a source file in |files|. . Targets that constitute the 'all' target. See description at top of file for details on the 'all' target. This sets the |match_status| of the targets that contain any of the source files in |files| to MATCH_STATUS_MATCHES. |toplevel_dir| is the root of the source tree.""" # Maps from target name to Target. name_to_target = {} # Targets that matched. matching_targets = [] # Queue of targets to visit. targets_to_visit = target_list[:] # Maps from build file to a boolean indicating whether the build file is in # |files|. build_file_in_files = {} # Root targets across all files. roots = set() # Set of Targets in |build_files|. build_file_targets = set() while len(targets_to_visit) > 0: target_name = targets_to_visit.pop() created_target, target = _GetOrCreateTargetByName(name_to_target, target_name) if created_target: roots.add(target) elif target.visited: continue target.visited = True target.requires_build = _DoesTargetTypeRequireBuild(target_dicts[target_name]) target_type = target_dicts[target_name]["type"] target.is_executable = target_type == "executable" target.is_static_library = target_type == "static_library" target.is_or_has_linked_ancestor = ( target_type in {"executable", "shared_library"} ) build_file = gyp.common.ParseQualifiedTarget(target_name)[0] if build_file not in build_file_in_files: build_file_in_files[build_file] = _WasBuildFileModified( build_file, data, files, toplevel_dir ) if build_file in build_files: build_file_targets.add(target) # If a build file (or any of its included files) is modified we assume all # targets in the file are modified. if build_file_in_files[build_file]: print("matching target from modified build file", target_name) target.match_status = MATCH_STATUS_MATCHES matching_targets.append(target) else: sources = _ExtractSources( target_name, target_dicts[target_name], toplevel_dir ) for source in sources: if _ToGypPath(os.path.normpath(source)) in files: print("target", target_name, "matches", source) target.match_status = MATCH_STATUS_MATCHES matching_targets.append(target) break # Add dependencies to visit as well as updating back pointers for deps. for dep in target_dicts[target_name].get("dependencies", []): targets_to_visit.append(dep) created_dep_target, dep_target = _GetOrCreateTargetByName( name_to_target, dep ) if not created_dep_target: roots.discard(dep_target) target.deps.add(dep_target) dep_target.back_deps.add(target) return name_to_target, matching_targets, roots & build_file_targets def _GetUnqualifiedToTargetMapping(all_targets, to_find): """Returns a tuple of the following: . mapping (dictionary) from unqualified name to Target for all the Targets in |to_find|. . any target names not found. If this is empty all targets were found.""" result = {} if not to_find: return {}, [] to_find = set(to_find) for target_name in all_targets: extracted = gyp.common.ParseQualifiedTarget(target_name) if len(extracted) > 1 and extracted[1] in to_find: to_find.remove(extracted[1]) result[extracted[1]] = all_targets[target_name] if not to_find: return result, [] return result, list(to_find) def _DoesTargetDependOnMatchingTargets(target): """Returns true if |target| or any of its dependencies is one of the targets containing the files supplied as input to analyzer. This updates |matches| of the Targets as it recurses. target: the Target to look for.""" if target.match_status == MATCH_STATUS_DOESNT_MATCH: return False if ( target.match_status in {MATCH_STATUS_MATCHES, MATCH_STATUS_MATCHES_BY_DEPENDENCY} ): return True for dep in target.deps: if _DoesTargetDependOnMatchingTargets(dep): target.match_status = MATCH_STATUS_MATCHES_BY_DEPENDENCY print("\t", target.name, "matches by dep", dep.name) return True target.match_status = MATCH_STATUS_DOESNT_MATCH return False def _GetTargetsDependingOnMatchingTargets(possible_targets): """Returns the list of Targets in |possible_targets| that depend (either directly on indirectly) on at least one of the targets containing the files supplied as input to analyzer. possible_targets: targets to search from.""" found = [] print("Targets that matched by dependency:") for target in possible_targets: if _DoesTargetDependOnMatchingTargets(target): found.append(target) return found def _AddCompileTargets(target, roots, add_if_no_ancestor, result): """Recurses through all targets that depend on |target|, adding all targets that need to be built (and are in |roots|) to |result|. roots: set of root targets. add_if_no_ancestor: If true and there are no ancestors of |target| then add |target| to |result|. |target| must still be in |roots|. result: targets that need to be built are added here.""" if target.visited: return target.visited = True target.in_roots = target in roots for back_dep_target in target.back_deps: _AddCompileTargets(back_dep_target, roots, False, result) target.added_to_compile_targets |= back_dep_target.added_to_compile_targets target.in_roots |= back_dep_target.in_roots target.is_or_has_linked_ancestor |= back_dep_target.is_or_has_linked_ancestor # Always add 'executable' targets. Even though they may be built by other # targets that depend upon them it makes detection of what is going to be # built easier. # And always add static_libraries that have no dependencies on them from # linkables. This is necessary as the other dependencies on them may be # static libraries themselves, which are not compile time dependencies. if target.in_roots and ( target.is_executable or ( not target.added_to_compile_targets and (add_if_no_ancestor or target.requires_build) ) or ( target.is_static_library and add_if_no_ancestor and not target.is_or_has_linked_ancestor ) ): print( "\t\tadding to compile targets", target.name, "executable", target.is_executable, "added_to_compile_targets", target.added_to_compile_targets, "add_if_no_ancestor", add_if_no_ancestor, "requires_build", target.requires_build, "is_static_library", target.is_static_library, "is_or_has_linked_ancestor", target.is_or_has_linked_ancestor, ) result.add(target) target.added_to_compile_targets = True def _GetCompileTargets(matching_targets, supplied_targets): """Returns the set of Targets that require a build. matching_targets: targets that changed and need to be built. supplied_targets: set of targets supplied to analyzer to search from.""" result = set() for target in matching_targets: print("finding compile targets for match", target.name) _AddCompileTargets(target, supplied_targets, True, result) return result def _WriteOutput(params, **values): """Writes the output, either to stdout or a file is specified.""" if "error" in values: print("Error:", values["error"]) if "status" in values: print(values["status"]) if "targets" in values: values["targets"].sort() print("Supplied targets that depend on changed files:") for target in values["targets"]: print("\t", target) if "invalid_targets" in values: values["invalid_targets"].sort() print("The following targets were not found:") for target in values["invalid_targets"]: print("\t", target) if "build_targets" in values: values["build_targets"].sort() print("Targets that require a build:") for target in values["build_targets"]: print("\t", target) if "compile_targets" in values: values["compile_targets"].sort() print("Targets that need to be built:") for target in values["compile_targets"]: print("\t", target) if "test_targets" in values: values["test_targets"].sort() print("Test targets:") for target in values["test_targets"]: print("\t", target) output_path = params.get("generator_flags", {}).get("analyzer_output_path", None) if not output_path: print(json.dumps(values)) return try: f = open(output_path, "w") f.write(json.dumps(values) + "\n") f.close() except OSError as e: print("Error writing to output file", output_path, str(e)) def _WasGypIncludeFileModified(params, files): """Returns true if one of the files in |files| is in the set of included files.""" if params["options"].includes: for include in params["options"].includes: if _ToGypPath(os.path.normpath(include)) in files: print("Include file modified, assuming all changed", include) return True return False def _NamesNotIn(names, mapping): """Returns a list of the values in |names| that are not in |mapping|.""" return [name for name in names if name not in mapping] def _LookupTargets(names, mapping): """Returns a list of the mapping[name] for each value in |names| that is in |mapping|.""" return [mapping[name] for name in names if name in mapping] def CalculateVariables(default_variables, params): """Calculate additional variables for use in the build (called by gyp).""" flavor = gyp.common.GetFlavor(params) if flavor == "mac": default_variables.setdefault("OS", "mac") elif flavor == "win": default_variables.setdefault("OS", "win") gyp.msvs_emulation.CalculateCommonVariables(default_variables, params) else: operating_system = flavor if flavor == "android": operating_system = "linux" # Keep this legacy behavior for now. default_variables.setdefault("OS", operating_system) class TargetCalculator: """Calculates the matching test_targets and matching compile_targets.""" def __init__( self, files, additional_compile_target_names, test_target_names, data, target_list, target_dicts, toplevel_dir, build_files, ): self._additional_compile_target_names = set(additional_compile_target_names) self._test_target_names = set(test_target_names) ( self._name_to_target, self._changed_targets, self._root_targets, ) = _GenerateTargets( data, target_list, target_dicts, toplevel_dir, frozenset(files), build_files ) ( self._unqualified_mapping, self.invalid_targets, ) = _GetUnqualifiedToTargetMapping( self._name_to_target, self._supplied_target_names_no_all() ) def _supplied_target_names(self): return self._additional_compile_target_names | self._test_target_names def _supplied_target_names_no_all(self): """Returns the supplied test targets without 'all'.""" result = self._supplied_target_names() result.discard("all") return result def is_build_impacted(self): """Returns true if the supplied files impact the build at all.""" return self._changed_targets def find_matching_test_target_names(self): """Returns the set of output test targets.""" assert self.is_build_impacted() # Find the test targets first. 'all' is special cased to mean all the # root targets. To deal with all the supplied |test_targets| are expanded # to include the root targets during lookup. If any of the root targets # match, we remove it and replace it with 'all'. test_target_names_no_all = set(self._test_target_names) test_target_names_no_all.discard("all") test_targets_no_all = _LookupTargets( test_target_names_no_all, self._unqualified_mapping ) test_target_names_contains_all = "all" in self._test_target_names if test_target_names_contains_all: test_targets = list(set(test_targets_no_all) | set(self._root_targets)) else: test_targets = list(test_targets_no_all) print("supplied test_targets") for target_name in self._test_target_names: print("\t", target_name) print("found test_targets") for target in test_targets: print("\t", target.name) print("searching for matching test targets") matching_test_targets = _GetTargetsDependingOnMatchingTargets(test_targets) matching_test_targets_contains_all = test_target_names_contains_all and set( matching_test_targets ) & set(self._root_targets) if matching_test_targets_contains_all: # Remove any of the targets for all that were not explicitly supplied, # 'all' is subsequentely added to the matching names below. matching_test_targets = list( set(matching_test_targets) & set(test_targets_no_all) ) print("matched test_targets") for target in matching_test_targets: print("\t", target.name) matching_target_names = [ gyp.common.ParseQualifiedTarget(target.name)[1] for target in matching_test_targets ] if matching_test_targets_contains_all: matching_target_names.append("all") print("\tall") return matching_target_names def find_matching_compile_target_names(self): """Returns the set of output compile targets.""" assert self.is_build_impacted() # Compile targets are found by searching up from changed targets. # Reset the visited status for _GetBuildTargets. for target in self._name_to_target.values(): target.visited = False supplied_targets = _LookupTargets( self._supplied_target_names_no_all(), self._unqualified_mapping ) if "all" in self._supplied_target_names(): supplied_targets = list(set(supplied_targets) | set(self._root_targets)) print("Supplied test_targets & compile_targets") for target in supplied_targets: print("\t", target.name) print("Finding compile targets") compile_targets = _GetCompileTargets(self._changed_targets, supplied_targets) return [ gyp.common.ParseQualifiedTarget(target.name)[1] for target in compile_targets ] def GenerateOutput(target_list, target_dicts, data, params): """Called by gyp as the final stage. Outputs results.""" config = Config() try: config.Init(params) if not config.files: raise Exception( "Must specify files to analyze via config_path generator " "flag" ) toplevel_dir = _ToGypPath(os.path.abspath(params["options"].toplevel_dir)) if debug: print("toplevel_dir", toplevel_dir) if _WasGypIncludeFileModified(params, config.files): result_dict = { "status": all_changed_string, "test_targets": list(config.test_target_names), "compile_targets": list( config.additional_compile_target_names | config.test_target_names ), } _WriteOutput(params, **result_dict) return calculator = TargetCalculator( config.files, config.additional_compile_target_names, config.test_target_names, data, target_list, target_dicts, toplevel_dir, params["build_files"], ) if not calculator.is_build_impacted(): result_dict = { "status": no_dependency_string, "test_targets": [], "compile_targets": [], } if calculator.invalid_targets: result_dict["invalid_targets"] = calculator.invalid_targets _WriteOutput(params, **result_dict) return test_target_names = calculator.find_matching_test_target_names() compile_target_names = calculator.find_matching_compile_target_names() found_at_least_one_target = compile_target_names or test_target_names result_dict = { "test_targets": test_target_names, "status": found_dependency_string if found_at_least_one_target else no_dependency_string, "compile_targets": list(set(compile_target_names) | set(test_target_names)), } if calculator.invalid_targets: result_dict["invalid_targets"] = calculator.invalid_targets _WriteOutput(params, **result_dict) except Exception as e: _WriteOutput(params, error=str(e)) PK ~\g (node-gyp/gyp/pylib/gyp/generator/gypd.pynu[# Copyright (c) 2011 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """gypd output module This module produces gyp input as its output. Output files are given the .gypd extension to avoid overwriting the .gyp files that they are generated from. Internal references to .gyp files (such as those found in "dependencies" sections) are not adjusted to point to .gypd files instead; unlike other paths, which are relative to the .gyp or .gypd file, such paths are relative to the directory from which gyp was run to create the .gypd file. This generator module is intended to be a sample and a debugging aid, hence the "d" for "debug" in .gypd. It is useful to inspect the results of the various merges, expansions, and conditional evaluations performed by gyp and to see a representation of what would be fed to a generator module. It's not advisable to rename .gypd files produced by this module to .gyp, because they will have all merges, expansions, and evaluations already performed and the relevant constructs not present in the output; paths to dependencies may be wrong; and various sections that do not belong in .gyp files such as such as "included_files" and "*_excluded" will be present. Output will also be stripped of comments. This is not intended to be a general-purpose gyp pretty-printer; for that, you probably just want to run "pprint.pprint(eval(open('source.gyp').read()))", which will still strip comments but won't do all of the other things done to this module's output. The specific formatting of the output generated by this module is subject to change. """ import gyp.common import pprint # These variables should just be spit back out as variable references. _generator_identity_variables = [ "CONFIGURATION_NAME", "EXECUTABLE_PREFIX", "EXECUTABLE_SUFFIX", "INTERMEDIATE_DIR", "LIB_DIR", "PRODUCT_DIR", "RULE_INPUT_ROOT", "RULE_INPUT_DIRNAME", "RULE_INPUT_EXT", "RULE_INPUT_NAME", "RULE_INPUT_PATH", "SHARED_INTERMEDIATE_DIR", "SHARED_LIB_DIR", "SHARED_LIB_PREFIX", "SHARED_LIB_SUFFIX", "STATIC_LIB_PREFIX", "STATIC_LIB_SUFFIX", ] # gypd doesn't define a default value for OS like many other generator # modules. Specify "-D OS=whatever" on the command line to provide a value. generator_default_variables = {} # gypd supports multiple toolsets generator_supports_multiple_toolsets = True # TODO(mark): This always uses <, which isn't right. The input module should # notify the generator to tell it which phase it is operating in, and this # module should use < for the early phase and then switch to > for the late # phase. Bonus points for carrying @ back into the output too. for v in _generator_identity_variables: generator_default_variables[v] = "<(%s)" % v def GenerateOutput(target_list, target_dicts, data, params): output_files = {} for qualified_target in target_list: [input_file, target] = gyp.common.ParseQualifiedTarget(qualified_target)[0:2] if input_file[-4:] != ".gyp": continue input_file_stem = input_file[:-4] output_file = input_file_stem + params["options"].suffix + ".gypd" output_files[output_file] = output_files.get(output_file, input_file) for output_file, input_file in output_files.items(): output = open(output_file, "w") pprint.pprint(data[input_file], output) output.close() PK ~\oW(node-gyp/gyp/pylib/gyp/generator/make.pynu[# Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # Notes: # # This is all roughly based on the Makefile system used by the Linux # kernel, but is a non-recursive make -- we put the entire dependency # graph in front of make and let it figure it out. # # The code below generates a separate .mk file for each target, but # all are sourced by the top-level Makefile. This means that all # variables in .mk-files clobber one another. Be careful to use := # where appropriate for immediate evaluation, and similarly to watch # that you're not relying on a variable value to last between different # .mk files. # # TODOs: # # Global settings and utility functions are currently stuffed in the # toplevel Makefile. It may make sense to generate some .mk files on # the side to keep the files readable. import os import re import subprocess import gyp import gyp.common import gyp.xcode_emulation from gyp.common import GetEnvironFallback import hashlib generator_default_variables = { "EXECUTABLE_PREFIX": "", "EXECUTABLE_SUFFIX": "", "STATIC_LIB_PREFIX": "lib", "SHARED_LIB_PREFIX": "lib", "STATIC_LIB_SUFFIX": ".a", "INTERMEDIATE_DIR": "$(obj).$(TOOLSET)/$(TARGET)/geni", "SHARED_INTERMEDIATE_DIR": "$(obj)/gen", "PRODUCT_DIR": "$(builddir)", "RULE_INPUT_ROOT": "%(INPUT_ROOT)s", # This gets expanded by Python. "RULE_INPUT_DIRNAME": "%(INPUT_DIRNAME)s", # This gets expanded by Python. "RULE_INPUT_PATH": "$(abspath $<)", "RULE_INPUT_EXT": "$(suffix $<)", "RULE_INPUT_NAME": "$(notdir $<)", "CONFIGURATION_NAME": "$(BUILDTYPE)", } # Make supports multiple toolsets generator_supports_multiple_toolsets = gyp.common.CrossCompileRequested() # Request sorted dependencies in the order from dependents to dependencies. generator_wants_sorted_dependencies = False # Placates pylint. generator_additional_non_configuration_keys = [] generator_additional_path_sections = [] generator_extra_sources_for_rules = [] generator_filelist_paths = None def CalculateVariables(default_variables, params): """Calculate additional variables for use in the build (called by gyp).""" flavor = gyp.common.GetFlavor(params) if flavor == "mac": default_variables.setdefault("OS", "mac") default_variables.setdefault("SHARED_LIB_SUFFIX", ".dylib") default_variables.setdefault( "SHARED_LIB_DIR", generator_default_variables["PRODUCT_DIR"] ) default_variables.setdefault( "LIB_DIR", generator_default_variables["PRODUCT_DIR"] ) # Copy additional generator configuration data from Xcode, which is shared # by the Mac Make generator. import gyp.generator.xcode as xcode_generator global generator_additional_non_configuration_keys generator_additional_non_configuration_keys = getattr( xcode_generator, "generator_additional_non_configuration_keys", [] ) global generator_additional_path_sections generator_additional_path_sections = getattr( xcode_generator, "generator_additional_path_sections", [] ) global generator_extra_sources_for_rules generator_extra_sources_for_rules = getattr( xcode_generator, "generator_extra_sources_for_rules", [] ) COMPILABLE_EXTENSIONS.update({".m": "objc", ".mm": "objcxx"}) else: operating_system = flavor if flavor == "android": operating_system = "linux" # Keep this legacy behavior for now. default_variables.setdefault("OS", operating_system) if flavor == "aix": default_variables.setdefault("SHARED_LIB_SUFFIX", ".a") elif flavor == "zos": default_variables.setdefault("SHARED_LIB_SUFFIX", ".x") COMPILABLE_EXTENSIONS.update({".pli": "pli"}) else: default_variables.setdefault("SHARED_LIB_SUFFIX", ".so") default_variables.setdefault("SHARED_LIB_DIR", "$(builddir)/lib.$(TOOLSET)") default_variables.setdefault("LIB_DIR", "$(obj).$(TOOLSET)") def CalculateGeneratorInputInfo(params): """Calculate the generator specific info that gets fed to input (called by gyp).""" generator_flags = params.get("generator_flags", {}) android_ndk_version = generator_flags.get("android_ndk_version", None) # Android NDK requires a strict link order. if android_ndk_version: global generator_wants_sorted_dependencies generator_wants_sorted_dependencies = True output_dir = params["options"].generator_output or params["options"].toplevel_dir builddir_name = generator_flags.get("output_dir", "out") qualified_out_dir = os.path.normpath( os.path.join(output_dir, builddir_name, "gypfiles") ) global generator_filelist_paths generator_filelist_paths = { "toplevel": params["options"].toplevel_dir, "qualified_out_dir": qualified_out_dir, } # The .d checking code below uses these functions: # wildcard, sort, foreach, shell, wordlist # wildcard can handle spaces, the rest can't. # Since I could find no way to make foreach work with spaces in filenames # correctly, the .d files have spaces replaced with another character. The .d # file for # Chromium\ Framework.framework/foo # is for example # out/Release/.deps/out/Release/Chromium?Framework.framework/foo # This is the replacement character. SPACE_REPLACEMENT = "?" LINK_COMMANDS_LINUX = """\ quiet_cmd_alink = AR($(TOOLSET)) $@ cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^) quiet_cmd_alink_thin = AR($(TOOLSET)) $@ cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^) # Due to circular dependencies between libraries :(, we wrap the # special "figure out circular dependencies" flags around the entire # input list during linking. quiet_cmd_link = LINK($(TOOLSET)) $@ cmd_link = $(LINK.$(TOOLSET)) -o $@ $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,--start-group $(LD_INPUTS) $(LIBS) -Wl,--end-group # Note: this does not handle spaces in paths define xargs $(1) $(word 1,$(2)) $(if $(word 2,$(2)),$(call xargs,$(1),$(wordlist 2,$(words $(2)),$(2)))) endef define write-to-file @: >$(1) $(call xargs,@printf "%s\\n" >>$(1),$(2)) endef OBJ_FILE_LIST := ar-file-list define create_archive rm -f $(1) $(1).$(OBJ_FILE_LIST); mkdir -p `dirname $(1)` $(call write-to-file,$(1).$(OBJ_FILE_LIST),$(filter %.o,$(2))) $(AR.$(TOOLSET)) crs $(1) @$(1).$(OBJ_FILE_LIST) endef define create_thin_archive rm -f $(1) $(OBJ_FILE_LIST); mkdir -p `dirname $(1)` $(call write-to-file,$(1).$(OBJ_FILE_LIST),$(filter %.o,$(2))) $(AR.$(TOOLSET)) crsT $(1) @$(1).$(OBJ_FILE_LIST) endef # We support two kinds of shared objects (.so): # 1) shared_library, which is just bundling together many dependent libraries # into a link line. # 2) loadable_module, which is generating a module intended for dlopen(). # # They differ only slightly: # In the former case, we want to package all dependent code into the .so. # In the latter case, we want to package just the API exposed by the # outermost module. # This means shared_library uses --whole-archive, while loadable_module doesn't. # (Note that --whole-archive is incompatible with the --start-group used in # normal linking.) # Other shared-object link notes: # - Set SONAME to the library filename so our binaries don't reference # the local, absolute paths used on the link command-line. quiet_cmd_solink = SOLINK($(TOOLSET)) $@ cmd_solink = $(LINK.$(TOOLSET)) -o $@ -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS) quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ cmd_solink_module = $(LINK.$(TOOLSET)) -o $@ -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS) """ # noqa: E501 LINK_COMMANDS_MAC = """\ quiet_cmd_alink = LIBTOOL-STATIC $@ cmd_alink = rm -f $@ && ./gyp-mac-tool filter-libtool libtool $(GYP_LIBTOOLFLAGS) -static -o $@ $(filter %.o,$^) quiet_cmd_link = LINK($(TOOLSET)) $@ cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) quiet_cmd_solink = SOLINK($(TOOLSET)) $@ cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ cmd_solink_module = $(LINK.$(TOOLSET)) -bundle $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS) """ # noqa: E501 LINK_COMMANDS_ANDROID = """\ quiet_cmd_alink = AR($(TOOLSET)) $@ cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^) quiet_cmd_alink_thin = AR($(TOOLSET)) $@ cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^) # Note: this does not handle spaces in paths define xargs $(1) $(word 1,$(2)) $(if $(word 2,$(2)),$(call xargs,$(1),$(wordlist 2,$(words $(2)),$(2)))) endef define write-to-file @: >$(1) $(call xargs,@printf "%s\\n" >>$(1),$(2)) endef OBJ_FILE_LIST := ar-file-list define create_archive rm -f $(1) $(1).$(OBJ_FILE_LIST); mkdir -p `dirname $(1)` $(call write-to-file,$(1).$(OBJ_FILE_LIST),$(filter %.o,$(2))) $(AR.$(TOOLSET)) crs $(1) @$(1).$(OBJ_FILE_LIST) endef define create_thin_archive rm -f $(1) $(OBJ_FILE_LIST); mkdir -p `dirname $(1)` $(call write-to-file,$(1).$(OBJ_FILE_LIST),$(filter %.o,$(2))) $(AR.$(TOOLSET)) crsT $(1) @$(1).$(OBJ_FILE_LIST) endef # Due to circular dependencies between libraries :(, we wrap the # special "figure out circular dependencies" flags around the entire # input list during linking. quiet_cmd_link = LINK($(TOOLSET)) $@ quiet_cmd_link_host = LINK($(TOOLSET)) $@ cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS) cmd_link_host = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS) # Other shared-object link notes: # - Set SONAME to the library filename so our binaries don't reference # the local, absolute paths used on the link command-line. quiet_cmd_solink = SOLINK($(TOOLSET)) $@ cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS) quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS) quiet_cmd_solink_module_host = SOLINK_MODULE($(TOOLSET)) $@ cmd_solink_module_host = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS) """ # noqa: E501 LINK_COMMANDS_AIX = """\ quiet_cmd_alink = AR($(TOOLSET)) $@ cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) -X32_64 crs $@ $(filter %.o,$^) quiet_cmd_alink_thin = AR($(TOOLSET)) $@ cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) -X32_64 crs $@ $(filter %.o,$^) quiet_cmd_link = LINK($(TOOLSET)) $@ cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS) quiet_cmd_solink = SOLINK($(TOOLSET)) $@ cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS) quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS) """ # noqa: E501 LINK_COMMANDS_OS400 = """\ quiet_cmd_alink = AR($(TOOLSET)) $@ cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) -X64 crs $@ $(filter %.o,$^) quiet_cmd_alink_thin = AR($(TOOLSET)) $@ cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) -X64 crs $@ $(filter %.o,$^) quiet_cmd_link = LINK($(TOOLSET)) $@ cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS) quiet_cmd_solink = SOLINK($(TOOLSET)) $@ cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS) quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS) """ # noqa: E501 LINK_COMMANDS_OS390 = """\ quiet_cmd_alink = AR($(TOOLSET)) $@ cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^) quiet_cmd_alink_thin = AR($(TOOLSET)) $@ cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^) quiet_cmd_link = LINK($(TOOLSET)) $@ cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS) quiet_cmd_solink = SOLINK($(TOOLSET)) $@ cmd_solink = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS) quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ cmd_solink_module = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS) """ # noqa: E501 # Header of toplevel Makefile. # This should go into the build tree, but it's easier to keep it here for now. SHARED_HEADER = ( """\ # We borrow heavily from the kernel build setup, though we are simpler since # we don't have Kconfig tweaking settings on us. # The implicit make rules have it looking for RCS files, among other things. # We instead explicitly write all the rules we care about. # It's even quicker (saves ~200ms) to pass -r on the command line. MAKEFLAGS=-r # The source directory tree. srcdir := %(srcdir)s abs_srcdir := $(abspath $(srcdir)) # The name of the builddir. builddir_name ?= %(builddir)s # The V=1 flag on command line makes us verbosely print command lines. ifdef V quiet= else quiet=quiet_ endif # Specify BUILDTYPE=Release on the command line for a release build. BUILDTYPE ?= %(default_configuration)s # Directory all our build output goes into. # Note that this must be two directories beneath src/ for unit tests to pass, # as they reach into the src/ directory for data with relative paths. builddir ?= $(builddir_name)/$(BUILDTYPE) abs_builddir := $(abspath $(builddir)) depsdir := $(builddir)/.deps # Object output directory. obj := $(builddir)/obj abs_obj := $(abspath $(obj)) # We build up a list of every single one of the targets so we can slurp in the # generated dependency rule Makefiles in one pass. all_deps := %(make_global_settings)s CC.target ?= %(CC.target)s CFLAGS.target ?= $(CPPFLAGS) $(CFLAGS) CXX.target ?= %(CXX.target)s CXXFLAGS.target ?= $(CPPFLAGS) $(CXXFLAGS) LINK.target ?= %(LINK.target)s LDFLAGS.target ?= $(LDFLAGS) AR.target ?= $(AR) PLI.target ?= %(PLI.target)s # C++ apps need to be linked with g++. LINK ?= $(CXX.target) # TODO(evan): move all cross-compilation logic to gyp-time so we don't need # to replicate this environment fallback in make as well. CC.host ?= %(CC.host)s CFLAGS.host ?= $(CPPFLAGS_host) $(CFLAGS_host) CXX.host ?= %(CXX.host)s CXXFLAGS.host ?= $(CPPFLAGS_host) $(CXXFLAGS_host) LINK.host ?= %(LINK.host)s LDFLAGS.host ?= $(LDFLAGS_host) AR.host ?= %(AR.host)s PLI.host ?= %(PLI.host)s # Define a dir function that can handle spaces. # http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions # "leading spaces cannot appear in the text of the first argument as written. # These characters can be put into the argument value by variable substitution." empty := space := $(empty) $(empty) # http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces replace_spaces = $(subst $(space),""" + SPACE_REPLACEMENT + """,$1) unreplace_spaces = $(subst """ + SPACE_REPLACEMENT + """,$(space),$1) dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1))) # Flags to make gcc output dependency info. Note that you need to be # careful here to use the flags that ccache and distcc can understand. # We write to a dep file on the side first and then rename at the end # so we can't end up with a broken dep file. depfile = $(depsdir)/$(call replace_spaces,$@).d DEPFLAGS = %(makedep_args)s -MF $(depfile).raw # We have to fixup the deps output in a few ways. # (1) the file output should mention the proper .o file. # ccache or distcc lose the path to the target, so we convert a rule of # the form: # foobar.o: DEP1 DEP2 # into # path/to/foobar.o: DEP1 DEP2 # (2) we want missing files not to cause us to fail to build. # We want to rewrite # foobar.o: DEP1 DEP2 \\ # DEP3 # to # DEP1: # DEP2: # DEP3: # so if the files are missing, they're just considered phony rules. # We have to do some pretty insane escaping to get those backslashes # and dollar signs past make, the shell, and sed at the same time. # Doesn't work with spaces, but that's fine: .d files have spaces in # their names replaced with other characters.""" r""" define fixup_dep # The depfile may not exist if the input file didn't have any #includes. touch $(depfile).raw # Fixup path as in (1). sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile) # Add extra rules as in (2). # We remove slashes and replace spaces with new lines; # remove blank lines; # delete the first line and append a colon to the remaining lines. sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\ grep -v '^$$' |\ sed -e 1d -e 's|$$|:|' \ >> $(depfile) rm $(depfile).raw endef """ """ # Command definitions: # - cmd_foo is the actual command to run; # - quiet_cmd_foo is the brief-output summary of the command. quiet_cmd_cc = CC($(TOOLSET)) $@ cmd_cc = $(CC.$(TOOLSET)) -o $@ $< $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c quiet_cmd_cxx = CXX($(TOOLSET)) $@ cmd_cxx = $(CXX.$(TOOLSET)) -o $@ $< $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c %(extra_commands)s quiet_cmd_touch = TOUCH $@ cmd_touch = touch $@ quiet_cmd_copy = COPY $@ # send stderr to /dev/null to ignore messages when linking directories. cmd_copy = ln -f "$<" "$@" 2>/dev/null || (rm -rf "$@" && cp %(copy_archive_args)s "$<" "$@") quiet_cmd_symlink = SYMLINK $@ cmd_symlink = ln -sf "$<" "$@" %(link_commands)s """ # noqa: E501 r""" # Define an escape_quotes function to escape single quotes. # This allows us to handle quotes properly as long as we always use # use single quotes and escape_quotes. escape_quotes = $(subst ','\'',$(1)) # This comment is here just to include a ' to unconfuse syntax highlighting. # Define an escape_vars function to escape '$' variable syntax. # This allows us to read/write command lines with shell variables (e.g. # $LD_LIBRARY_PATH), without triggering make substitution. escape_vars = $(subst $$,$$$$,$(1)) # Helper that expands to a shell command to echo a string exactly as it is in # make. This uses printf instead of echo because printf's behaviour with respect # to escape sequences is more portable than echo's across different shells # (e.g., dash, bash). exact_echo = printf '%%s\n' '$(call escape_quotes,$(1))' """ """ # Helper to compare the command we're about to run against the command # we logged the last time we ran the command. Produces an empty # string (false) when the commands match. # Tricky point: Make has no string-equality test function. # The kernel uses the following, but it seems like it would have false # positives, where one string reordered its arguments. # arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \\ # $(filter-out $(cmd_$@), $(cmd_$(1)))) # We instead substitute each for the empty string into the other, and # say they're equal if both substitutions produce the empty string. # .d files contain """ + SPACE_REPLACEMENT + """ instead of spaces, take that into account. command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\\ $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) # Helper that is non-empty when a prerequisite changes. # Normally make does this implicitly, but we force rules to always run # so we can check their command lines. # $? -- new prerequisites # $| -- order-only dependencies prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) # Helper that executes all postbuilds until one fails. define do_postbuilds @E=0;\\ for p in $(POSTBUILDS); do\\ eval $$p;\\ E=$$?;\\ if [ $$E -ne 0 ]; then\\ break;\\ fi;\\ done;\\ if [ $$E -ne 0 ]; then\\ rm -rf "$@";\\ exit $$E;\\ fi endef # do_cmd: run a command via the above cmd_foo names, if necessary. # Should always run for a given target to handle command-line changes. # Second argument, if non-zero, makes it do asm/C/C++ dependency munging. # Third argument, if non-zero, makes it do POSTBUILDS processing. # Note: We intentionally do NOT call dirx for depfile, since it contains """ + SPACE_REPLACEMENT + """ for # spaces already and dirx strips the """ + SPACE_REPLACEMENT + """ characters. define do_cmd $(if $(or $(command_changed),$(prereq_changed)), @$(call exact_echo, $($(quiet)cmd_$(1))) @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" $(if $(findstring flock,$(word %(flock_index)d,$(cmd_$1))), @$(cmd_$(1)) @echo " $(quiet_cmd_$(1)): Finished", @$(cmd_$(1)) ) @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) @$(if $(2),$(fixup_dep)) $(if $(and $(3), $(POSTBUILDS)), $(call do_postbuilds) ) ) endef # Declare the "%(default_target)s" target first so it is the default, # even though we don't have the deps yet. .PHONY: %(default_target)s %(default_target)s: # make looks for ways to re-generate included makefiles, but in our case, we # don't have a direct way. Explicitly telling make that it has nothing to do # for them makes it go faster. %%.d: ; # Use FORCE_DO_CMD to force a target to run. Should be coupled with # do_cmd. .PHONY: FORCE_DO_CMD FORCE_DO_CMD: """ # noqa: E501 ) SHARED_HEADER_MAC_COMMANDS = """ quiet_cmd_objc = CXX($(TOOLSET)) $@ cmd_objc = $(CC.$(TOOLSET)) $(GYP_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< quiet_cmd_objcxx = CXX($(TOOLSET)) $@ cmd_objcxx = $(CXX.$(TOOLSET)) $(GYP_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< # Commands for precompiled header files. quiet_cmd_pch_c = CXX($(TOOLSET)) $@ cmd_pch_c = $(CC.$(TOOLSET)) $(GYP_PCH_CFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< quiet_cmd_pch_cc = CXX($(TOOLSET)) $@ cmd_pch_cc = $(CC.$(TOOLSET)) $(GYP_PCH_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< quiet_cmd_pch_m = CXX($(TOOLSET)) $@ cmd_pch_m = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< quiet_cmd_pch_mm = CXX($(TOOLSET)) $@ cmd_pch_mm = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< # gyp-mac-tool is written next to the root Makefile by gyp. # Use $(4) for the command, since $(2) and $(3) are used as flag by do_cmd # already. quiet_cmd_mac_tool = MACTOOL $(4) $< cmd_mac_tool = ./gyp-mac-tool $(4) $< "$@" quiet_cmd_mac_package_framework = PACKAGE FRAMEWORK $@ cmd_mac_package_framework = ./gyp-mac-tool package-framework "$@" $(4) quiet_cmd_infoplist = INFOPLIST $@ cmd_infoplist = $(CC.$(TOOLSET)) -E -P -Wno-trigraphs -x c $(INFOPLIST_DEFINES) "$<" -o "$@" """ # noqa: E501 def WriteRootHeaderSuffixRules(writer): extensions = sorted(COMPILABLE_EXTENSIONS.keys(), key=str.lower) writer.write("# Suffix rules, putting all outputs into $(obj).\n") for ext in extensions: writer.write("$(obj).$(TOOLSET)/%%.o: $(srcdir)/%%%s FORCE_DO_CMD\n" % ext) writer.write("\t@$(call do_cmd,%s,1)\n" % COMPILABLE_EXTENSIONS[ext]) writer.write("\n# Try building from generated source, too.\n") for ext in extensions: writer.write( "$(obj).$(TOOLSET)/%%.o: $(obj).$(TOOLSET)/%%%s FORCE_DO_CMD\n" % ext ) writer.write("\t@$(call do_cmd,%s,1)\n" % COMPILABLE_EXTENSIONS[ext]) writer.write("\n") for ext in extensions: writer.write("$(obj).$(TOOLSET)/%%.o: $(obj)/%%%s FORCE_DO_CMD\n" % ext) writer.write("\t@$(call do_cmd,%s,1)\n" % COMPILABLE_EXTENSIONS[ext]) writer.write("\n") SHARED_HEADER_OS390_COMMANDS = """ PLIFLAGS.target ?= -qlp=64 -qlimits=extname=31 $(PLIFLAGS) PLIFLAGS.host ?= -qlp=64 -qlimits=extname=31 $(PLIFLAGS) quiet_cmd_pli = PLI($(TOOLSET)) $@ cmd_pli = $(PLI.$(TOOLSET)) $(GYP_PLIFLAGS) $(PLIFLAGS.$(TOOLSET)) -c $< && \ if [ -f $(notdir $@) ]; then /bin/cp $(notdir $@) $@; else true; fi """ SHARED_HEADER_SUFFIX_RULES_COMMENT1 = """\ # Suffix rules, putting all outputs into $(obj). """ SHARED_HEADER_SUFFIX_RULES_COMMENT2 = """\ # Try building from generated source, too. """ SHARED_FOOTER = """\ # "all" is a concatenation of the "all" targets from all the included # sub-makefiles. This is just here to clarify. all: # Add in dependency-tracking rules. $(all_deps) is the list of every single # target in our tree. Only consider the ones with .d (dependency) info: d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d)) ifneq ($(d_files),) include $(d_files) endif """ header = """\ # This file is generated by gyp; do not edit. """ # Maps every compilable file extension to the do_cmd that compiles it. COMPILABLE_EXTENSIONS = { ".c": "cc", ".cc": "cxx", ".cpp": "cxx", ".cxx": "cxx", ".s": "cc", ".S": "cc", } def Compilable(filename): """Return true if the file is compilable (should be in OBJS).""" return any(res for res in (filename.endswith(e) for e in COMPILABLE_EXTENSIONS)) def Linkable(filename): """Return true if the file is linkable (should be on the link line).""" return filename.endswith(".o") def Target(filename): """Translate a compilable filename to its .o target.""" return os.path.splitext(filename)[0] + ".o" def EscapeShellArgument(s): """Quotes an argument so that it will be interpreted literally by a POSIX shell. Taken from http://stackoverflow.com/questions/35817/whats-the-best-way-to-escape-ossystem-calls-in-python """ return "'" + s.replace("'", "'\\''") + "'" def EscapeMakeVariableExpansion(s): """Make has its own variable expansion syntax using $. We must escape it for string to be interpreted literally.""" return s.replace("$", "$$") def EscapeCppDefine(s): """Escapes a CPP define so that it will reach the compiler unaltered.""" s = EscapeShellArgument(s) s = EscapeMakeVariableExpansion(s) # '#' characters must be escaped even embedded in a string, else Make will # treat it as the start of a comment. return s.replace("#", r"\#") def QuoteIfNecessary(string): """TODO: Should this ideally be replaced with one or more of the above functions?""" if '"' in string: string = '"' + string.replace('"', '\\"') + '"' return string def StringToMakefileVariable(string): """Convert a string to a value that is acceptable as a make variable name.""" return re.sub("[^a-zA-Z0-9_]", "_", string) srcdir_prefix = "" def Sourceify(path): """Convert a path to its source directory form.""" if "$(" in path: return path if os.path.isabs(path): return path return srcdir_prefix + path def QuoteSpaces(s, quote=r"\ "): return s.replace(" ", quote) def SourceifyAndQuoteSpaces(path): """Convert a path to its source directory form and quote spaces.""" return QuoteSpaces(Sourceify(path)) # Map from qualified target to path to output. target_outputs = {} # Map from qualified target to any linkable output. A subset # of target_outputs. E.g. when mybinary depends on liba, we want to # include liba in the linker line; when otherbinary depends on # mybinary, we just want to build mybinary first. target_link_deps = {} class MakefileWriter: """MakefileWriter packages up the writing of one target-specific foobar.mk. Its only real entry point is Write(), and is mostly used for namespacing. """ def __init__(self, generator_flags, flavor): self.generator_flags = generator_flags self.flavor = flavor self.suffix_rules_srcdir = {} self.suffix_rules_objdir1 = {} self.suffix_rules_objdir2 = {} # Generate suffix rules for all compilable extensions. for ext in COMPILABLE_EXTENSIONS: # Suffix rules for source folder. self.suffix_rules_srcdir.update( { ext: ( """\ $(obj).$(TOOLSET)/$(TARGET)/%%.o: $(srcdir)/%%%s FORCE_DO_CMD \t@$(call do_cmd,%s,1) """ % (ext, COMPILABLE_EXTENSIONS[ext]) ) } ) # Suffix rules for generated source files. self.suffix_rules_objdir1.update( { ext: ( """\ $(obj).$(TOOLSET)/$(TARGET)/%%.o: $(obj).$(TOOLSET)/%%%s FORCE_DO_CMD \t@$(call do_cmd,%s,1) """ % (ext, COMPILABLE_EXTENSIONS[ext]) ) } ) self.suffix_rules_objdir2.update( { ext: ( """\ $(obj).$(TOOLSET)/$(TARGET)/%%.o: $(obj)/%%%s FORCE_DO_CMD \t@$(call do_cmd,%s,1) """ % (ext, COMPILABLE_EXTENSIONS[ext]) ) } ) def Write( self, qualified_target, base_path, output_filename, spec, configs, part_of_all ): """The main entry point: writes a .mk file for a single target. Arguments: qualified_target: target we're generating base_path: path relative to source root we're building in, used to resolve target-relative paths output_filename: output .mk file name to write spec, configs: gyp info part_of_all: flag indicating this target is part of 'all' """ gyp.common.EnsureDirExists(output_filename) self.fp = open(output_filename, "w") self.fp.write(header) self.qualified_target = qualified_target self.path = base_path self.target = spec["target_name"] self.type = spec["type"] self.toolset = spec["toolset"] self.is_mac_bundle = gyp.xcode_emulation.IsMacBundle(self.flavor, spec) if self.flavor == "mac": self.xcode_settings = gyp.xcode_emulation.XcodeSettings(spec) else: self.xcode_settings = None deps, link_deps = self.ComputeDeps(spec) # Some of the generation below can add extra output, sources, or # link dependencies. All of the out params of the functions that # follow use names like extra_foo. extra_outputs = [] extra_sources = [] extra_link_deps = [] extra_mac_bundle_resources = [] mac_bundle_deps = [] if self.is_mac_bundle: self.output = self.ComputeMacBundleOutput(spec) self.output_binary = self.ComputeMacBundleBinaryOutput(spec) else: self.output = self.output_binary = self.ComputeOutput(spec) self.is_standalone_static_library = bool( spec.get("standalone_static_library", 0) ) self._INSTALLABLE_TARGETS = ("executable", "loadable_module", "shared_library") if self.is_standalone_static_library or self.type in self._INSTALLABLE_TARGETS: self.alias = os.path.basename(self.output) install_path = self._InstallableTargetInstallPath() else: self.alias = self.output install_path = self.output self.WriteLn("TOOLSET := " + self.toolset) self.WriteLn("TARGET := " + self.target) # Actions must come first, since they can generate more OBJs for use below. if "actions" in spec: self.WriteActions( spec["actions"], extra_sources, extra_outputs, extra_mac_bundle_resources, part_of_all, ) # Rules must be early like actions. if "rules" in spec: self.WriteRules( spec["rules"], extra_sources, extra_outputs, extra_mac_bundle_resources, part_of_all, ) if "copies" in spec: self.WriteCopies(spec["copies"], extra_outputs, part_of_all) # Bundle resources. if self.is_mac_bundle: all_mac_bundle_resources = ( spec.get("mac_bundle_resources", []) + extra_mac_bundle_resources ) self.WriteMacBundleResources(all_mac_bundle_resources, mac_bundle_deps) self.WriteMacInfoPlist(mac_bundle_deps) # Sources. all_sources = spec.get("sources", []) + extra_sources if all_sources: self.WriteSources( configs, deps, all_sources, extra_outputs, extra_link_deps, part_of_all, gyp.xcode_emulation.MacPrefixHeader( self.xcode_settings, lambda p: Sourceify(self.Absolutify(p)), self.Pchify, ), ) sources = [x for x in all_sources if Compilable(x)] if sources: self.WriteLn(SHARED_HEADER_SUFFIX_RULES_COMMENT1) extensions = {os.path.splitext(s)[1] for s in sources} for ext in extensions: if ext in self.suffix_rules_srcdir: self.WriteLn(self.suffix_rules_srcdir[ext]) self.WriteLn(SHARED_HEADER_SUFFIX_RULES_COMMENT2) for ext in extensions: if ext in self.suffix_rules_objdir1: self.WriteLn(self.suffix_rules_objdir1[ext]) for ext in extensions: if ext in self.suffix_rules_objdir2: self.WriteLn(self.suffix_rules_objdir2[ext]) self.WriteLn("# End of this set of suffix rules") # Add dependency from bundle to bundle binary. if self.is_mac_bundle: mac_bundle_deps.append(self.output_binary) self.WriteTarget( spec, configs, deps, extra_link_deps + link_deps, mac_bundle_deps, extra_outputs, part_of_all, ) # Update global list of target outputs, used in dependency tracking. target_outputs[qualified_target] = install_path # Update global list of link dependencies. if self.type in ("static_library", "shared_library"): target_link_deps[qualified_target] = self.output_binary # Currently any versions have the same effect, but in future the behavior # could be different. if self.generator_flags.get("android_ndk_version", None): self.WriteAndroidNdkModuleRule(self.target, all_sources, link_deps) self.fp.close() def WriteSubMake(self, output_filename, makefile_path, targets, build_dir): """Write a "sub-project" Makefile. This is a small, wrapper Makefile that calls the top-level Makefile to build the targets from a single gyp file (i.e. a sub-project). Arguments: output_filename: sub-project Makefile name to write makefile_path: path to the top-level Makefile targets: list of "all" targets for this sub-project build_dir: build output directory, relative to the sub-project """ gyp.common.EnsureDirExists(output_filename) self.fp = open(output_filename, "w") self.fp.write(header) # For consistency with other builders, put sub-project build output in the # sub-project dir (see test/subdirectory/gyptest-subdir-all.py). self.WriteLn( "export builddir_name ?= %s" % os.path.join(os.path.dirname(output_filename), build_dir) ) self.WriteLn(".PHONY: all") self.WriteLn("all:") if makefile_path: makefile_path = " -C " + makefile_path self.WriteLn("\t$(MAKE){} {}".format(makefile_path, " ".join(targets))) self.fp.close() def WriteActions( self, actions, extra_sources, extra_outputs, extra_mac_bundle_resources, part_of_all, ): """Write Makefile code for any 'actions' from the gyp input. extra_sources: a list that will be filled in with newly generated source files, if any extra_outputs: a list that will be filled in with any outputs of these actions (used to make other pieces dependent on these actions) part_of_all: flag indicating this target is part of 'all' """ env = self.GetSortedXcodeEnv() for action in actions: name = StringToMakefileVariable( "{}_{}".format(self.qualified_target, action["action_name"]) ) self.WriteLn('### Rules for action "%s":' % action["action_name"]) inputs = action["inputs"] outputs = action["outputs"] # Build up a list of outputs. # Collect the output dirs we'll need. dirs = set() for out in outputs: dir = os.path.split(out)[0] if dir: dirs.add(dir) if int(action.get("process_outputs_as_sources", False)): extra_sources += outputs if int(action.get("process_outputs_as_mac_bundle_resources", False)): extra_mac_bundle_resources += outputs # Write the actual command. action_commands = action["action"] if self.flavor == "mac": action_commands = [ gyp.xcode_emulation.ExpandEnvVars(command, env) for command in action_commands ] command = gyp.common.EncodePOSIXShellList(action_commands) if "message" in action: self.WriteLn( "quiet_cmd_{} = ACTION {} $@".format(name, action["message"]) ) else: self.WriteLn(f"quiet_cmd_{name} = ACTION {name} $@") if len(dirs) > 0: command = "mkdir -p %s" % " ".join(dirs) + "; " + command cd_action = "cd %s; " % Sourceify(self.path or ".") # command and cd_action get written to a toplevel variable called # cmd_foo. Toplevel variables can't handle things that change per # makefile like $(TARGET), so hardcode the target. command = command.replace("$(TARGET)", self.target) cd_action = cd_action.replace("$(TARGET)", self.target) # Set LD_LIBRARY_PATH in case the action runs an executable from this # build which links to shared libs from this build. # actions run on the host, so they should in theory only use host # libraries, but until everything is made cross-compile safe, also use # target libraries. # TODO(piman): when everything is cross-compile safe, remove lib.target if self.flavor in {"zos", "aix"}: self.WriteLn( "cmd_%s = LIBPATH=$(builddir)/lib.host:" "$(builddir)/lib.target:$$LIBPATH; " "export LIBPATH; " "%s%s" % (name, cd_action, command) ) else: self.WriteLn( "cmd_%s = LD_LIBRARY_PATH=$(builddir)/lib.host:" "$(builddir)/lib.target:$$LD_LIBRARY_PATH; " "export LD_LIBRARY_PATH; " "%s%s" % (name, cd_action, command) ) self.WriteLn() outputs = [self.Absolutify(o) for o in outputs] # The makefile rules are all relative to the top dir, but the gyp actions # are defined relative to their containing dir. This replaces the obj # variable for the action rule with an absolute version so that the output # goes in the right place. # Only write the 'obj' and 'builddir' rules for the "primary" output (:1); # it's superfluous for the "extra outputs", and this avoids accidentally # writing duplicate dummy rules for those outputs. # Same for environment. self.WriteLn("%s: obj := $(abs_obj)" % QuoteSpaces(outputs[0])) self.WriteLn("%s: builddir := $(abs_builddir)" % QuoteSpaces(outputs[0])) self.WriteSortedXcodeEnv(outputs[0], self.GetSortedXcodeEnv()) for input in inputs: assert " " not in input, ( "Spaces in action input filenames not supported (%s)" % input ) for output in outputs: assert " " not in output, ( "Spaces in action output filenames not supported (%s)" % output ) # See the comment in WriteCopies about expanding env vars. outputs = [gyp.xcode_emulation.ExpandEnvVars(o, env) for o in outputs] inputs = [gyp.xcode_emulation.ExpandEnvVars(i, env) for i in inputs] self.WriteDoCmd( outputs, [Sourceify(self.Absolutify(i)) for i in inputs], part_of_all=part_of_all, command=name, ) # Stuff the outputs in a variable so we can refer to them later. outputs_variable = "action_%s_outputs" % name self.WriteLn("{} := {}".format(outputs_variable, " ".join(outputs))) extra_outputs.append("$(%s)" % outputs_variable) self.WriteLn() self.WriteLn() def WriteRules( self, rules, extra_sources, extra_outputs, extra_mac_bundle_resources, part_of_all, ): """Write Makefile code for any 'rules' from the gyp input. extra_sources: a list that will be filled in with newly generated source files, if any extra_outputs: a list that will be filled in with any outputs of these rules (used to make other pieces dependent on these rules) part_of_all: flag indicating this target is part of 'all' """ env = self.GetSortedXcodeEnv() for rule in rules: name = StringToMakefileVariable( "{}_{}".format(self.qualified_target, rule["rule_name"]) ) count = 0 self.WriteLn("### Generated for rule %s:" % name) all_outputs = [] for rule_source in rule.get("rule_sources", []): dirs = set() (rule_source_dirname, rule_source_basename) = os.path.split(rule_source) (rule_source_root, rule_source_ext) = os.path.splitext( rule_source_basename ) outputs = [ self.ExpandInputRoot(out, rule_source_root, rule_source_dirname) for out in rule["outputs"] ] for out in outputs: dir = os.path.dirname(out) if dir: dirs.add(dir) if int(rule.get("process_outputs_as_sources", False)): extra_sources += outputs if int(rule.get("process_outputs_as_mac_bundle_resources", False)): extra_mac_bundle_resources += outputs inputs = [ Sourceify(self.Absolutify(i)) for i in [rule_source] + rule.get("inputs", []) ] actions = ["$(call do_cmd,%s_%d)" % (name, count)] if name == "resources_grit": # HACK: This is ugly. Grit intentionally doesn't touch the # timestamp of its output file when the file doesn't change, # which is fine in hash-based dependency systems like scons # and forge, but not kosher in the make world. After some # discussion, hacking around it here seems like the least # amount of pain. actions += ["@touch --no-create $@"] # See the comment in WriteCopies about expanding env vars. outputs = [gyp.xcode_emulation.ExpandEnvVars(o, env) for o in outputs] inputs = [gyp.xcode_emulation.ExpandEnvVars(i, env) for i in inputs] outputs = [self.Absolutify(o) for o in outputs] all_outputs += outputs # Only write the 'obj' and 'builddir' rules for the "primary" output # (:1); it's superfluous for the "extra outputs", and this avoids # accidentally writing duplicate dummy rules for those outputs. self.WriteLn("%s: obj := $(abs_obj)" % outputs[0]) self.WriteLn("%s: builddir := $(abs_builddir)" % outputs[0]) self.WriteMakeRule( outputs, inputs, actions, command="%s_%d" % (name, count) ) # Spaces in rule filenames are not supported, but rule variables have # spaces in them (e.g. RULE_INPUT_PATH expands to '$(abspath $<)'). # The spaces within the variables are valid, so remove the variables # before checking. variables_with_spaces = re.compile(r"\$\([^ ]* \$<\)") for output in outputs: output = re.sub(variables_with_spaces, "", output) assert " " not in output, ( "Spaces in rule filenames not yet supported (%s)" % output ) self.WriteLn("all_deps += %s" % " ".join(outputs)) action = [ self.ExpandInputRoot(ac, rule_source_root, rule_source_dirname) for ac in rule["action"] ] mkdirs = "" if len(dirs) > 0: mkdirs = "mkdir -p %s; " % " ".join(dirs) cd_action = "cd %s; " % Sourceify(self.path or ".") # action, cd_action, and mkdirs get written to a toplevel variable # called cmd_foo. Toplevel variables can't handle things that change # per makefile like $(TARGET), so hardcode the target. if self.flavor == "mac": action = [ gyp.xcode_emulation.ExpandEnvVars(command, env) for command in action ] action = gyp.common.EncodePOSIXShellList(action) action = action.replace("$(TARGET)", self.target) cd_action = cd_action.replace("$(TARGET)", self.target) mkdirs = mkdirs.replace("$(TARGET)", self.target) # Set LD_LIBRARY_PATH in case the rule runs an executable from this # build which links to shared libs from this build. # rules run on the host, so they should in theory only use host # libraries, but until everything is made cross-compile safe, also use # target libraries. # TODO(piman): when everything is cross-compile safe, remove lib.target self.WriteLn( "cmd_%(name)s_%(count)d = LD_LIBRARY_PATH=" "$(builddir)/lib.host:$(builddir)/lib.target:$$LD_LIBRARY_PATH; " "export LD_LIBRARY_PATH; " "%(cd_action)s%(mkdirs)s%(action)s" % { "action": action, "cd_action": cd_action, "count": count, "mkdirs": mkdirs, "name": name, } ) self.WriteLn( "quiet_cmd_%(name)s_%(count)d = RULE %(name)s_%(count)d $@" % {"count": count, "name": name} ) self.WriteLn() count += 1 outputs_variable = "rule_%s_outputs" % name self.WriteList(all_outputs, outputs_variable) extra_outputs.append("$(%s)" % outputs_variable) self.WriteLn("### Finished generating for rule: %s" % name) self.WriteLn() self.WriteLn("### Finished generating for all rules") self.WriteLn("") def WriteCopies(self, copies, extra_outputs, part_of_all): """Write Makefile code for any 'copies' from the gyp input. extra_outputs: a list that will be filled in with any outputs of this action (used to make other pieces dependent on this action) part_of_all: flag indicating this target is part of 'all' """ self.WriteLn("### Generated for copy rule.") variable = StringToMakefileVariable(self.qualified_target + "_copies") outputs = [] for copy in copies: for path in copy["files"]: # Absolutify() may call normpath, and will strip trailing slashes. path = Sourceify(self.Absolutify(path)) filename = os.path.split(path)[1] output = Sourceify( self.Absolutify(os.path.join(copy["destination"], filename)) ) # If the output path has variables in it, which happens in practice for # 'copies', writing the environment as target-local doesn't work, # because the variables are already needed for the target name. # Copying the environment variables into global make variables doesn't # work either, because then the .d files will potentially contain spaces # after variable expansion, and .d file handling cannot handle spaces. # As a workaround, manually expand variables at gyp time. Since 'copies' # can't run scripts, there's no need to write the env then. # WriteDoCmd() will escape spaces for .d files. env = self.GetSortedXcodeEnv() output = gyp.xcode_emulation.ExpandEnvVars(output, env) path = gyp.xcode_emulation.ExpandEnvVars(path, env) self.WriteDoCmd([output], [path], "copy", part_of_all) outputs.append(output) self.WriteLn( "{} = {}".format(variable, " ".join(QuoteSpaces(o) for o in outputs)) ) extra_outputs.append("$(%s)" % variable) self.WriteLn() def WriteMacBundleResources(self, resources, bundle_deps): """Writes Makefile code for 'mac_bundle_resources'.""" self.WriteLn("### Generated for mac_bundle_resources") for output, res in gyp.xcode_emulation.GetMacBundleResources( generator_default_variables["PRODUCT_DIR"], self.xcode_settings, [Sourceify(self.Absolutify(r)) for r in resources], ): _, ext = os.path.splitext(output) if ext != ".xcassets": # Make does not supports '.xcassets' emulation. self.WriteDoCmd( [output], [res], "mac_tool,,,copy-bundle-resource", part_of_all=True ) bundle_deps.append(output) def WriteMacInfoPlist(self, bundle_deps): """Write Makefile code for bundle Info.plist files.""" info_plist, out, defines, extra_env = gyp.xcode_emulation.GetMacInfoPlist( generator_default_variables["PRODUCT_DIR"], self.xcode_settings, lambda p: Sourceify(self.Absolutify(p)), ) if not info_plist: return if defines: # Create an intermediate file to store preprocessed results. intermediate_plist = "$(obj).$(TOOLSET)/$(TARGET)/" + os.path.basename( info_plist ) self.WriteList( defines, intermediate_plist + ": INFOPLIST_DEFINES", "-D", quoter=EscapeCppDefine, ) self.WriteMakeRule( [intermediate_plist], [info_plist], [ "$(call do_cmd,infoplist)", # "Convert" the plist so that any weird whitespace changes from the # preprocessor do not affect the XML parser in mac_tool. "@plutil -convert xml1 $@ $@", ], ) info_plist = intermediate_plist # plists can contain envvars and substitute them into the file. self.WriteSortedXcodeEnv( out, self.GetSortedXcodeEnv(additional_settings=extra_env) ) self.WriteDoCmd( [out], [info_plist], "mac_tool,,,copy-info-plist", part_of_all=True ) bundle_deps.append(out) def WriteSources( self, configs, deps, sources, extra_outputs, extra_link_deps, part_of_all, precompiled_header, ): """Write Makefile code for any 'sources' from the gyp input. These are source files necessary to build the current target. configs, deps, sources: input from gyp. extra_outputs: a list of extra outputs this action should be dependent on; used to serialize action/rules before compilation extra_link_deps: a list that will be filled in with any outputs of compilation (to be used in link lines) part_of_all: flag indicating this target is part of 'all' """ # Write configuration-specific variables for CFLAGS, etc. for configname in sorted(configs.keys()): config = configs[configname] self.WriteList( config.get("defines"), "DEFS_%s" % configname, prefix="-D", quoter=EscapeCppDefine, ) if self.flavor == "mac": cflags = self.xcode_settings.GetCflags( configname, arch=config.get("xcode_configuration_platform") ) cflags_c = self.xcode_settings.GetCflagsC(configname) cflags_cc = self.xcode_settings.GetCflagsCC(configname) cflags_objc = self.xcode_settings.GetCflagsObjC(configname) cflags_objcc = self.xcode_settings.GetCflagsObjCC(configname) else: cflags = config.get("cflags") cflags_c = config.get("cflags_c") cflags_cc = config.get("cflags_cc") self.WriteLn("# Flags passed to all source files.") self.WriteList(cflags, "CFLAGS_%s" % configname) self.WriteLn("# Flags passed to only C files.") self.WriteList(cflags_c, "CFLAGS_C_%s" % configname) self.WriteLn("# Flags passed to only C++ files.") self.WriteList(cflags_cc, "CFLAGS_CC_%s" % configname) if self.flavor == "mac": self.WriteLn("# Flags passed to only ObjC files.") self.WriteList(cflags_objc, "CFLAGS_OBJC_%s" % configname) self.WriteLn("# Flags passed to only ObjC++ files.") self.WriteList(cflags_objcc, "CFLAGS_OBJCC_%s" % configname) includes = config.get("include_dirs") if includes: includes = [Sourceify(self.Absolutify(i)) for i in includes] self.WriteList(includes, "INCS_%s" % configname, prefix="-I") compilable = list(filter(Compilable, sources)) objs = [self.Objectify(self.Absolutify(Target(c))) for c in compilable] self.WriteList(objs, "OBJS") for obj in objs: assert " " not in obj, "Spaces in object filenames not supported (%s)" % obj self.WriteLn( "# Add to the list of files we specially track " "dependencies for." ) self.WriteLn("all_deps += $(OBJS)") self.WriteLn() # Make sure our dependencies are built first. if deps: self.WriteMakeRule( ["$(OBJS)"], deps, comment="Make sure our dependencies are built " "before any of us.", order_only=True, ) # Make sure the actions and rules run first. # If they generate any extra headers etc., the per-.o file dep tracking # will catch the proper rebuilds, so order only is still ok here. if extra_outputs: self.WriteMakeRule( ["$(OBJS)"], extra_outputs, comment="Make sure our actions/rules run " "before any of us.", order_only=True, ) pchdeps = precompiled_header.GetObjDependencies(compilable, objs) if pchdeps: self.WriteLn("# Dependencies from obj files to their precompiled headers") for source, obj, gch in pchdeps: self.WriteLn(f"{obj}: {gch}") self.WriteLn("# End precompiled header dependencies") if objs: extra_link_deps.append("$(OBJS)") self.WriteLn( """\ # CFLAGS et al overrides must be target-local. # See "Target-specific Variable Values" in the GNU Make manual.""" ) self.WriteLn("$(OBJS): TOOLSET := $(TOOLSET)") self.WriteLn( "$(OBJS): GYP_CFLAGS := " "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "%s " % precompiled_header.GetInclude("c") + "$(CFLAGS_$(BUILDTYPE)) " "$(CFLAGS_C_$(BUILDTYPE))" ) self.WriteLn( "$(OBJS): GYP_CXXFLAGS := " "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "%s " % precompiled_header.GetInclude("cc") + "$(CFLAGS_$(BUILDTYPE)) " "$(CFLAGS_CC_$(BUILDTYPE))" ) if self.flavor == "mac": self.WriteLn( "$(OBJS): GYP_OBJCFLAGS := " "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "%s " % precompiled_header.GetInclude("m") + "$(CFLAGS_$(BUILDTYPE)) " "$(CFLAGS_C_$(BUILDTYPE)) " "$(CFLAGS_OBJC_$(BUILDTYPE))" ) self.WriteLn( "$(OBJS): GYP_OBJCXXFLAGS := " "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "%s " % precompiled_header.GetInclude("mm") + "$(CFLAGS_$(BUILDTYPE)) " "$(CFLAGS_CC_$(BUILDTYPE)) " "$(CFLAGS_OBJCC_$(BUILDTYPE))" ) self.WritePchTargets(precompiled_header.GetPchBuildCommands()) # If there are any object files in our input file list, link them into our # output. extra_link_deps += [source for source in sources if Linkable(source)] self.WriteLn() def WritePchTargets(self, pch_commands): """Writes make rules to compile prefix headers.""" if not pch_commands: return for gch, lang_flag, lang, input in pch_commands: extra_flags = { "c": "$(CFLAGS_C_$(BUILDTYPE))", "cc": "$(CFLAGS_CC_$(BUILDTYPE))", "m": "$(CFLAGS_C_$(BUILDTYPE)) $(CFLAGS_OBJC_$(BUILDTYPE))", "mm": "$(CFLAGS_CC_$(BUILDTYPE)) $(CFLAGS_OBJCC_$(BUILDTYPE))", }[lang] var_name = { "c": "GYP_PCH_CFLAGS", "cc": "GYP_PCH_CXXFLAGS", "m": "GYP_PCH_OBJCFLAGS", "mm": "GYP_PCH_OBJCXXFLAGS", }[lang] self.WriteLn( f"{gch}: {var_name} := {lang_flag} " + "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "$(CFLAGS_$(BUILDTYPE)) " + extra_flags ) self.WriteLn(f"{gch}: {input} FORCE_DO_CMD") self.WriteLn("\t@$(call do_cmd,pch_%s,1)" % lang) self.WriteLn("") assert " " not in gch, "Spaces in gch filenames not supported (%s)" % gch self.WriteLn("all_deps += %s" % gch) self.WriteLn("") def ComputeOutputBasename(self, spec): """Return the 'output basename' of a gyp spec. E.g., the loadable module 'foobar' in directory 'baz' will produce 'libfoobar.so' """ assert not self.is_mac_bundle if self.flavor == "mac" and self.type in ( "static_library", "executable", "shared_library", "loadable_module", ): return self.xcode_settings.GetExecutablePath() target = spec["target_name"] target_prefix = "" target_ext = "" if self.type == "static_library": if target[:3] == "lib": target = target[3:] target_prefix = "lib" target_ext = ".a" elif self.type in ("loadable_module", "shared_library"): if target[:3] == "lib": target = target[3:] target_prefix = "lib" if self.flavor == "aix": target_ext = ".a" elif self.flavor == "zos": target_ext = ".x" else: target_ext = ".so" elif self.type == "none": target = "%s.stamp" % target elif self.type != "executable": print( "ERROR: What output file should be generated?", "type", self.type, "target", target, ) target_prefix = spec.get("product_prefix", target_prefix) target = spec.get("product_name", target) product_ext = spec.get("product_extension") if product_ext: target_ext = "." + product_ext return target_prefix + target + target_ext def _InstallImmediately(self): return ( self.toolset == "target" and self.flavor == "mac" and self.type in ("static_library", "executable", "shared_library", "loadable_module") ) def ComputeOutput(self, spec): """Return the 'output' (full output path) of a gyp spec. E.g., the loadable module 'foobar' in directory 'baz' will produce '$(obj)/baz/libfoobar.so' """ assert not self.is_mac_bundle path = os.path.join("$(obj)." + self.toolset, self.path) if self.type == "executable" or self._InstallImmediately(): path = "$(builddir)" path = spec.get("product_dir", path) return os.path.join(path, self.ComputeOutputBasename(spec)) def ComputeMacBundleOutput(self, spec): """Return the 'output' (full output path) to a bundle output directory.""" assert self.is_mac_bundle path = generator_default_variables["PRODUCT_DIR"] return os.path.join(path, self.xcode_settings.GetWrapperName()) def ComputeMacBundleBinaryOutput(self, spec): """Return the 'output' (full output path) to the binary in a bundle.""" path = generator_default_variables["PRODUCT_DIR"] return os.path.join(path, self.xcode_settings.GetExecutablePath()) def ComputeDeps(self, spec): """Compute the dependencies of a gyp spec. Returns a tuple (deps, link_deps), where each is a list of filenames that will need to be put in front of make for either building (deps) or linking (link_deps). """ deps = [] link_deps = [] if "dependencies" in spec: deps.extend( [ target_outputs[dep] for dep in spec["dependencies"] if target_outputs[dep] ] ) for dep in spec["dependencies"]: if dep in target_link_deps: link_deps.append(target_link_deps[dep]) deps.extend(link_deps) # TODO: It seems we need to transitively link in libraries (e.g. -lfoo)? # This hack makes it work: # link_deps.extend(spec.get('libraries', [])) return (gyp.common.uniquer(deps), gyp.common.uniquer(link_deps)) def GetSharedObjectFromSidedeck(self, sidedeck): """Return the shared object files based on sidedeck""" return re.sub(r"\.x$", ".so", sidedeck) def GetUnversionedSidedeckFromSidedeck(self, sidedeck): """Return the shared object files based on sidedeck""" return re.sub(r"\.\d+\.x$", ".x", sidedeck) def WriteDependencyOnExtraOutputs(self, target, extra_outputs): self.WriteMakeRule( [self.output_binary], extra_outputs, comment="Build our special outputs first.", order_only=True, ) def WriteTarget( self, spec, configs, deps, link_deps, bundle_deps, extra_outputs, part_of_all ): """Write Makefile code to produce the final target of the gyp spec. spec, configs: input from gyp. deps, link_deps: dependency lists; see ComputeDeps() extra_outputs: any extra outputs that our target should depend on part_of_all: flag indicating this target is part of 'all' """ self.WriteLn("### Rules for final target.") if extra_outputs: self.WriteDependencyOnExtraOutputs(self.output_binary, extra_outputs) self.WriteMakeRule( extra_outputs, deps, comment=("Preserve order dependency of " "special output on deps."), order_only=True, ) target_postbuilds = {} if self.type != "none": for configname in sorted(configs.keys()): config = configs[configname] if self.flavor == "mac": ldflags = self.xcode_settings.GetLdflags( configname, generator_default_variables["PRODUCT_DIR"], lambda p: Sourceify(self.Absolutify(p)), arch=config.get("xcode_configuration_platform"), ) # TARGET_POSTBUILDS_$(BUILDTYPE) is added to postbuilds later on. gyp_to_build = gyp.common.InvertRelativePath(self.path) target_postbuild = self.xcode_settings.AddImplicitPostbuilds( configname, QuoteSpaces( os.path.normpath(os.path.join(gyp_to_build, self.output)) ), QuoteSpaces( os.path.normpath( os.path.join(gyp_to_build, self.output_binary) ) ), ) if target_postbuild: target_postbuilds[configname] = target_postbuild else: ldflags = config.get("ldflags", []) # Compute an rpath for this output if needed. if any(dep.endswith(".so") or ".so." in dep for dep in deps): # We want to get the literal string "$ORIGIN" # into the link command, so we need lots of escaping. ldflags.append(r"-Wl,-rpath=\$$ORIGIN/") ldflags.append(r"-Wl,-rpath-link=\$(builddir)/") library_dirs = config.get("library_dirs", []) ldflags += [("-L%s" % library_dir) for library_dir in library_dirs] self.WriteList(ldflags, "LDFLAGS_%s" % configname) if self.flavor == "mac": self.WriteList( self.xcode_settings.GetLibtoolflags(configname), "LIBTOOLFLAGS_%s" % configname, ) libraries = spec.get("libraries") if libraries: # Remove duplicate entries libraries = gyp.common.uniquer(libraries) if self.flavor == "mac": libraries = self.xcode_settings.AdjustLibraries(libraries) self.WriteList(libraries, "LIBS") self.WriteLn( "%s: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE))" % QuoteSpaces(self.output_binary) ) self.WriteLn("%s: LIBS := $(LIBS)" % QuoteSpaces(self.output_binary)) if self.flavor == "mac": self.WriteLn( "%s: GYP_LIBTOOLFLAGS := $(LIBTOOLFLAGS_$(BUILDTYPE))" % QuoteSpaces(self.output_binary) ) # Postbuild actions. Like actions, but implicitly depend on the target's # output. postbuilds = [] if self.flavor == "mac": if target_postbuilds: postbuilds.append("$(TARGET_POSTBUILDS_$(BUILDTYPE))") postbuilds.extend(gyp.xcode_emulation.GetSpecPostbuildCommands(spec)) if postbuilds: # Envvars may be referenced by TARGET_POSTBUILDS_$(BUILDTYPE), # so we must output its definition first, since we declare variables # using ":=". self.WriteSortedXcodeEnv(self.output, self.GetSortedXcodePostbuildEnv()) for configname in target_postbuilds: self.WriteLn( "%s: TARGET_POSTBUILDS_%s := %s" % ( QuoteSpaces(self.output), configname, gyp.common.EncodePOSIXShellList(target_postbuilds[configname]), ) ) # Postbuilds expect to be run in the gyp file's directory, so insert an # implicit postbuild to cd to there. postbuilds.insert(0, gyp.common.EncodePOSIXShellList(["cd", self.path])) for i, postbuild in enumerate(postbuilds): if not postbuild.startswith("$"): postbuilds[i] = EscapeShellArgument(postbuild) self.WriteLn("%s: builddir := $(abs_builddir)" % QuoteSpaces(self.output)) self.WriteLn( "%s: POSTBUILDS := %s" % (QuoteSpaces(self.output), " ".join(postbuilds)) ) # A bundle directory depends on its dependencies such as bundle resources # and bundle binary. When all dependencies have been built, the bundle # needs to be packaged. if self.is_mac_bundle: # If the framework doesn't contain a binary, then nothing depends # on the actions -- make the framework depend on them directly too. self.WriteDependencyOnExtraOutputs(self.output, extra_outputs) # Bundle dependencies. Note that the code below adds actions to this # target, so if you move these two lines, move the lines below as well. self.WriteList([QuoteSpaces(dep) for dep in bundle_deps], "BUNDLE_DEPS") self.WriteLn("%s: $(BUNDLE_DEPS)" % QuoteSpaces(self.output)) # After the framework is built, package it. Needs to happen before # postbuilds, since postbuilds depend on this. if self.type in ("shared_library", "loadable_module"): self.WriteLn( "\t@$(call do_cmd,mac_package_framework,,,%s)" % self.xcode_settings.GetFrameworkVersion() ) # Bundle postbuilds can depend on the whole bundle, so run them after # the bundle is packaged, not already after the bundle binary is done. if postbuilds: self.WriteLn("\t@$(call do_postbuilds)") postbuilds = [] # Don't write postbuilds for target's output. # Needed by test/mac/gyptest-rebuild.py. self.WriteLn("\t@true # No-op, used by tests") # Since this target depends on binary and resources which are in # nested subfolders, the framework directory will be older than # its dependencies usually. To prevent this rule from executing # on every build (expensive, especially with postbuilds), expliclity # update the time on the framework directory. self.WriteLn("\t@touch -c %s" % QuoteSpaces(self.output)) if postbuilds: assert not self.is_mac_bundle, ( "Postbuilds for bundles should be done " "on the bundle, not the binary (target '%s')" % self.target ) assert "product_dir" not in spec, ( "Postbuilds do not work with " "custom product_dir" ) if self.type == "executable": self.WriteLn( "%s: LD_INPUTS := %s" % ( QuoteSpaces(self.output_binary), " ".join(QuoteSpaces(dep) for dep in link_deps), ) ) if self.toolset == "host" and self.flavor == "android": self.WriteDoCmd( [self.output_binary], link_deps, "link_host", part_of_all, postbuilds=postbuilds, ) else: self.WriteDoCmd( [self.output_binary], link_deps, "link", part_of_all, postbuilds=postbuilds, ) elif self.type == "static_library": for link_dep in link_deps: assert " " not in link_dep, ( "Spaces in alink input filenames not supported (%s)" % link_dep ) if ( self.flavor not in ("mac", "openbsd", "netbsd", "win") and not self.is_standalone_static_library ): if self.flavor in ("linux", "android"): self.WriteMakeRule( [self.output_binary], link_deps, actions=["$(call create_thin_archive,$@,$^)"], ) else: self.WriteDoCmd( [self.output_binary], link_deps, "alink_thin", part_of_all, postbuilds=postbuilds, ) else: if self.flavor in ("linux", "android"): self.WriteMakeRule( [self.output_binary], link_deps, actions=["$(call create_archive,$@,$^)"], ) else: self.WriteDoCmd( [self.output_binary], link_deps, "alink", part_of_all, postbuilds=postbuilds, ) elif self.type == "shared_library": self.WriteLn( "%s: LD_INPUTS := %s" % ( QuoteSpaces(self.output_binary), " ".join(QuoteSpaces(dep) for dep in link_deps), ) ) self.WriteDoCmd( [self.output_binary], link_deps, "solink", part_of_all, postbuilds=postbuilds, ) # z/OS has a .so target as well as a sidedeck .x target if self.flavor == "zos": self.WriteLn( "%s: %s" % ( QuoteSpaces( self.GetSharedObjectFromSidedeck(self.output_binary) ), QuoteSpaces(self.output_binary), ) ) elif self.type == "loadable_module": for link_dep in link_deps: assert " " not in link_dep, ( "Spaces in module input filenames not supported (%s)" % link_dep ) if self.toolset == "host" and self.flavor == "android": self.WriteDoCmd( [self.output_binary], link_deps, "solink_module_host", part_of_all, postbuilds=postbuilds, ) else: self.WriteDoCmd( [self.output_binary], link_deps, "solink_module", part_of_all, postbuilds=postbuilds, ) elif self.type == "none": # Write a stamp line. self.WriteDoCmd( [self.output_binary], deps, "touch", part_of_all, postbuilds=postbuilds ) else: print("WARNING: no output for", self.type, self.target) # Add an alias for each target (if there are any outputs). # Installable target aliases are created below. if (self.output and self.output != self.target) and ( self.type not in self._INSTALLABLE_TARGETS ): self.WriteMakeRule( [self.target], [self.output], comment="Add target alias", phony=True ) if part_of_all: self.WriteMakeRule( ["all"], [self.target], comment='Add target alias to "all" target.', phony=True, ) # Add special-case rules for our installable targets. # 1) They need to install to the build dir or "product" dir. # 2) They get shortcuts for building (e.g. "make chrome"). # 3) They are part of "make all". if self.type in self._INSTALLABLE_TARGETS or self.is_standalone_static_library: if self.type == "shared_library": file_desc = "shared library" elif self.type == "static_library": file_desc = "static library" else: file_desc = "executable" install_path = self._InstallableTargetInstallPath() installable_deps = [] if self.flavor != "zos": installable_deps.append(self.output) if ( self.flavor == "mac" and "product_dir" not in spec and self.toolset == "target" ): # On mac, products are created in install_path immediately. assert install_path == self.output, f"{install_path} != {self.output}" # Point the target alias to the final binary output. self.WriteMakeRule( [self.target], [install_path], comment="Add target alias", phony=True ) if install_path != self.output: assert not self.is_mac_bundle # See comment a few lines above. self.WriteDoCmd( [install_path], [self.output], "copy", comment="Copy this to the %s output path." % file_desc, part_of_all=part_of_all, ) if self.flavor != "zos": installable_deps.append(install_path) if self.flavor == "zos" and self.type == "shared_library": # lib.target/libnode.so has a dependency on $(obj).target/libnode.so self.WriteDoCmd( [self.GetSharedObjectFromSidedeck(install_path)], [self.GetSharedObjectFromSidedeck(self.output)], "copy", comment="Copy this to the %s output path." % file_desc, part_of_all=part_of_all, ) # Create a symlink of libnode.x to libnode.version.x self.WriteDoCmd( [self.GetUnversionedSidedeckFromSidedeck(install_path)], [install_path], "symlink", comment="Symlnk this to the %s output path." % file_desc, part_of_all=part_of_all, ) # Place libnode.version.so and libnode.x symlink in lib.target dir installable_deps.append(self.GetSharedObjectFromSidedeck(install_path)) installable_deps.append( self.GetUnversionedSidedeckFromSidedeck(install_path) ) if self.alias not in (self.output, self.target): self.WriteMakeRule( [self.alias], installable_deps, comment="Short alias for building this %s." % file_desc, phony=True, ) if self.flavor == "zos" and self.type == "shared_library": # Make sure that .x symlink target is run self.WriteMakeRule( ["all"], [ self.GetUnversionedSidedeckFromSidedeck(install_path), self.GetSharedObjectFromSidedeck(install_path), ], comment='Add %s to "all" target.' % file_desc, phony=True, ) elif part_of_all: self.WriteMakeRule( ["all"], [install_path], comment='Add %s to "all" target.' % file_desc, phony=True, ) def WriteList(self, value_list, variable=None, prefix="", quoter=QuoteIfNecessary): """Write a variable definition that is a list of values. E.g. WriteList(['a','b'], 'foo', prefix='blah') writes out foo = blaha blahb but in a pretty-printed style. """ values = "" if value_list: value_list = [quoter(prefix + value) for value in value_list] values = " \\\n\t" + " \\\n\t".join(value_list) self.fp.write(f"{variable} :={values}\n\n") def WriteDoCmd( self, outputs, inputs, command, part_of_all, comment=None, postbuilds=False ): """Write a Makefile rule that uses do_cmd. This makes the outputs dependent on the command line that was run, as well as support the V= make command line flag. """ suffix = "" if postbuilds: assert "," not in command suffix = ",,1" # Tell do_cmd to honor $POSTBUILDS self.WriteMakeRule( outputs, inputs, actions=[f"$(call do_cmd,{command}{suffix})"], comment=comment, command=command, force=True, ) # Add our outputs to the list of targets we read depfiles from. # all_deps is only used for deps file reading, and for deps files we replace # spaces with ? because escaping doesn't work with make's $(sort) and # other functions. outputs = [QuoteSpaces(o, SPACE_REPLACEMENT) for o in outputs] self.WriteLn("all_deps += %s" % " ".join(outputs)) def WriteMakeRule( self, outputs, inputs, actions=None, comment=None, order_only=False, force=False, phony=False, command=None, ): """Write a Makefile rule, with some extra tricks. outputs: a list of outputs for the rule (note: this is not directly supported by make; see comments below) inputs: a list of inputs for the rule actions: a list of shell commands to run for the rule comment: a comment to put in the Makefile above the rule (also useful for making this Python script's code self-documenting) order_only: if true, makes the dependency order-only force: if true, include FORCE_DO_CMD as an order-only dep phony: if true, the rule does not actually generate the named output, the output is just a name to run the rule command: (optional) command name to generate unambiguous labels """ outputs = [QuoteSpaces(o) for o in outputs] inputs = [QuoteSpaces(i) for i in inputs] if comment: self.WriteLn("# " + comment) if phony: self.WriteLn(".PHONY: " + " ".join(outputs)) if actions: self.WriteLn("%s: TOOLSET := $(TOOLSET)" % outputs[0]) force_append = " FORCE_DO_CMD" if force else "" if order_only: # Order only rule: Just write a simple rule. # TODO(evanm): just make order_only a list of deps instead of this hack. self.WriteLn( "{}: | {}{}".format(" ".join(outputs), " ".join(inputs), force_append) ) elif len(outputs) == 1: # Regular rule, one output: Just write a simple rule. self.WriteLn("{}: {}{}".format(outputs[0], " ".join(inputs), force_append)) else: # Regular rule, more than one output: Multiple outputs are tricky in # make. We will write three rules: # - All outputs depend on an intermediate file. # - Make .INTERMEDIATE depend on the intermediate. # - The intermediate file depends on the inputs and executes the # actual command. # - The intermediate recipe will 'touch' the intermediate file. # - The multi-output rule will have an do-nothing recipe. # Hash the target name to avoid generating overlong filenames. cmddigest = hashlib.sha1( (command or self.target).encode("utf-8") ).hexdigest() intermediate = "%s.intermediate" % cmddigest self.WriteLn("{}: {}".format(" ".join(outputs), intermediate)) self.WriteLn("\t%s" % "@:") self.WriteLn("{}: {}".format(".INTERMEDIATE", intermediate)) self.WriteLn( "{}: {}{}".format(intermediate, " ".join(inputs), force_append) ) actions.insert(0, "$(call do_cmd,touch)") if actions: for action in actions: self.WriteLn("\t%s" % action) self.WriteLn() def WriteAndroidNdkModuleRule(self, module_name, all_sources, link_deps): """Write a set of LOCAL_XXX definitions for Android NDK. These variable definitions will be used by Android NDK but do nothing for non-Android applications. Arguments: module_name: Android NDK module name, which must be unique among all module names. all_sources: A list of source files (will be filtered by Compilable). link_deps: A list of link dependencies, which must be sorted in the order from dependencies to dependents. """ if self.type not in ("executable", "shared_library", "static_library"): return self.WriteLn("# Variable definitions for Android applications") self.WriteLn("include $(CLEAR_VARS)") self.WriteLn("LOCAL_MODULE := " + module_name) self.WriteLn( "LOCAL_CFLAGS := $(CFLAGS_$(BUILDTYPE)) " "$(DEFS_$(BUILDTYPE)) " # LOCAL_CFLAGS is applied to both of C and C++. There is # no way to specify $(CFLAGS_C_$(BUILDTYPE)) only for C # sources. "$(CFLAGS_C_$(BUILDTYPE)) " # $(INCS_$(BUILDTYPE)) includes the prefix '-I' while # LOCAL_C_INCLUDES does not expect it. So put it in # LOCAL_CFLAGS. "$(INCS_$(BUILDTYPE))" ) # LOCAL_CXXFLAGS is obsolete and LOCAL_CPPFLAGS is preferred. self.WriteLn("LOCAL_CPPFLAGS := $(CFLAGS_CC_$(BUILDTYPE))") self.WriteLn("LOCAL_C_INCLUDES :=") self.WriteLn("LOCAL_LDLIBS := $(LDFLAGS_$(BUILDTYPE)) $(LIBS)") # Detect the C++ extension. cpp_ext = {".cc": 0, ".cpp": 0, ".cxx": 0} default_cpp_ext = ".cpp" for filename in all_sources: ext = os.path.splitext(filename)[1] if ext in cpp_ext: cpp_ext[ext] += 1 if cpp_ext[ext] > cpp_ext[default_cpp_ext]: default_cpp_ext = ext self.WriteLn("LOCAL_CPP_EXTENSION := " + default_cpp_ext) self.WriteList( list(map(self.Absolutify, filter(Compilable, all_sources))), "LOCAL_SRC_FILES", ) # Filter out those which do not match prefix and suffix and produce # the resulting list without prefix and suffix. def DepsToModules(deps, prefix, suffix): modules = [] for filepath in deps: filename = os.path.basename(filepath) if filename.startswith(prefix) and filename.endswith(suffix): modules.append(filename[len(prefix) : -len(suffix)]) return modules # Retrieve the default value of 'SHARED_LIB_SUFFIX' params = {"flavor": "linux"} default_variables = {} CalculateVariables(default_variables, params) self.WriteList( DepsToModules( link_deps, generator_default_variables["SHARED_LIB_PREFIX"], default_variables["SHARED_LIB_SUFFIX"], ), "LOCAL_SHARED_LIBRARIES", ) self.WriteList( DepsToModules( link_deps, generator_default_variables["STATIC_LIB_PREFIX"], generator_default_variables["STATIC_LIB_SUFFIX"], ), "LOCAL_STATIC_LIBRARIES", ) if self.type == "executable": self.WriteLn("include $(BUILD_EXECUTABLE)") elif self.type == "shared_library": self.WriteLn("include $(BUILD_SHARED_LIBRARY)") elif self.type == "static_library": self.WriteLn("include $(BUILD_STATIC_LIBRARY)") self.WriteLn() def WriteLn(self, text=""): self.fp.write(text + "\n") def GetSortedXcodeEnv(self, additional_settings=None): return gyp.xcode_emulation.GetSortedXcodeEnv( self.xcode_settings, "$(abs_builddir)", os.path.join("$(abs_srcdir)", self.path), "$(BUILDTYPE)", additional_settings, ) def GetSortedXcodePostbuildEnv(self): # CHROMIUM_STRIP_SAVE_FILE is a chromium-specific hack. # TODO(thakis): It would be nice to have some general mechanism instead. strip_save_file = self.xcode_settings.GetPerTargetSetting( "CHROMIUM_STRIP_SAVE_FILE", "" ) # Even if strip_save_file is empty, explicitly write it. Else a postbuild # might pick up an export from an earlier target. return self.GetSortedXcodeEnv( additional_settings={"CHROMIUM_STRIP_SAVE_FILE": strip_save_file} ) def WriteSortedXcodeEnv(self, target, env): for k, v in env: # For # foo := a\ b # the escaped space does the right thing. For # export foo := a\ b # it does not -- the backslash is written to the env as literal character. # So don't escape spaces in |env[k]|. self.WriteLn(f"{QuoteSpaces(target)}: export {k} := {v}") def Objectify(self, path): """Convert a path to its output directory form.""" if "$(" in path: path = path.replace("$(obj)/", "$(obj).%s/$(TARGET)/" % self.toolset) if "$(obj)" not in path: path = f"$(obj).{self.toolset}/$(TARGET)/{path}" return path def Pchify(self, path, lang): """Convert a prefix header path to its output directory form.""" path = self.Absolutify(path) if "$(" in path: path = path.replace( "$(obj)/", f"$(obj).{self.toolset}/$(TARGET)/pch-{lang}" ) return path return f"$(obj).{self.toolset}/$(TARGET)/pch-{lang}/{path}" def Absolutify(self, path): """Convert a subdirectory-relative path into a base-relative path. Skips over paths that contain variables.""" if "$(" in path: # Don't call normpath in this case, as it might collapse the # path too aggressively if it features '..'. However it's still # important to strip trailing slashes. return path.rstrip("/") return os.path.normpath(os.path.join(self.path, path)) def ExpandInputRoot(self, template, expansion, dirname): if "%(INPUT_ROOT)s" not in template and "%(INPUT_DIRNAME)s" not in template: return template path = template % { "INPUT_ROOT": expansion, "INPUT_DIRNAME": dirname, } return path def _InstallableTargetInstallPath(self): """Returns the location of the final output for an installable target.""" # Functionality removed for all platforms to match Xcode and hoist # shared libraries into PRODUCT_DIR for users: # Xcode puts shared_library results into PRODUCT_DIR, and some gyp files # rely on this. Emulate this behavior for mac. # if self.type == "shared_library" and ( # self.flavor != "mac" or self.toolset != "target" # ): # # Install all shared libs into a common directory (per toolset) for # # convenient access with LD_LIBRARY_PATH. # return "$(builddir)/lib.%s/%s" % (self.toolset, self.alias) if self.flavor == "zos" and self.type == "shared_library": return "$(builddir)/lib.%s/%s" % (self.toolset, self.alias) return "$(builddir)/" + self.alias def WriteAutoRegenerationRule(params, root_makefile, makefile_name, build_files): """Write the target to regenerate the Makefile.""" options = params["options"] build_files_args = [ gyp.common.RelativePath(filename, options.toplevel_dir) for filename in params["build_files_arg"] ] gyp_binary = gyp.common.FixIfRelativePath( params["gyp_binary"], options.toplevel_dir ) if not gyp_binary.startswith(os.sep): gyp_binary = os.path.join(".", gyp_binary) root_makefile.write( "quiet_cmd_regen_makefile = ACTION Regenerating $@\n" "cmd_regen_makefile = cd $(srcdir); %(cmd)s\n" "%(makefile_name)s: %(deps)s\n" "\t$(call do_cmd,regen_makefile)\n\n" % { "makefile_name": makefile_name, "deps": " ".join(SourceifyAndQuoteSpaces(bf) for bf in build_files), "cmd": gyp.common.EncodePOSIXShellList( [gyp_binary, "-fmake"] + gyp.RegenerateFlags(options) + build_files_args ), } ) def PerformBuild(data, configurations, params): options = params["options"] for config in configurations: arguments = ["make"] if options.toplevel_dir and options.toplevel_dir != ".": arguments += "-C", options.toplevel_dir arguments.append("BUILDTYPE=" + config) print(f"Building [{config}]: {arguments}") subprocess.check_call(arguments) def GenerateOutput(target_list, target_dicts, data, params): options = params["options"] flavor = gyp.common.GetFlavor(params) generator_flags = params.get("generator_flags", {}) builddir_name = generator_flags.get("output_dir", "out") android_ndk_version = generator_flags.get("android_ndk_version", None) default_target = generator_flags.get("default_target", "all") def CalculateMakefilePath(build_file, base_name): """Determine where to write a Makefile for a given gyp file.""" # Paths in gyp files are relative to the .gyp file, but we want # paths relative to the source root for the master makefile. Grab # the path of the .gyp file as the base to relativize against. # E.g. "foo/bar" when we're constructing targets for "foo/bar/baz.gyp". base_path = gyp.common.RelativePath(os.path.dirname(build_file), options.depth) # We write the file in the base_path directory. output_file = os.path.join(options.depth, base_path, base_name) if options.generator_output: output_file = os.path.join( options.depth, options.generator_output, base_path, base_name ) base_path = gyp.common.RelativePath( os.path.dirname(build_file), options.toplevel_dir ) return base_path, output_file # TODO: search for the first non-'Default' target. This can go # away when we add verification that all targets have the # necessary configurations. default_configuration = None toolsets = {target_dicts[target]["toolset"] for target in target_list} for target in target_list: spec = target_dicts[target] if spec["default_configuration"] != "Default": default_configuration = spec["default_configuration"] break if not default_configuration: default_configuration = "Default" srcdir = "." makefile_name = "Makefile" + options.suffix makefile_path = os.path.join(options.toplevel_dir, makefile_name) if options.generator_output: global srcdir_prefix makefile_path = os.path.join( options.toplevel_dir, options.generator_output, makefile_name ) srcdir = gyp.common.RelativePath(srcdir, options.generator_output) srcdir_prefix = "$(srcdir)/" flock_command = "flock" copy_archive_arguments = "-af" makedep_arguments = "-MMD" header_params = { "default_target": default_target, "builddir": builddir_name, "default_configuration": default_configuration, "flock": flock_command, "flock_index": 1, "link_commands": LINK_COMMANDS_LINUX, "extra_commands": "", "srcdir": srcdir, "copy_archive_args": copy_archive_arguments, "makedep_args": makedep_arguments, "CC.target": GetEnvironFallback(("CC_target", "CC"), "$(CC)"), "AR.target": GetEnvironFallback(("AR_target", "AR"), "$(AR)"), "CXX.target": GetEnvironFallback(("CXX_target", "CXX"), "$(CXX)"), "LINK.target": GetEnvironFallback(("LINK_target", "LINK"), "$(LINK)"), "PLI.target": GetEnvironFallback(("PLI_target", "PLI"), "pli"), "CC.host": GetEnvironFallback(("CC_host", "CC"), "gcc"), "AR.host": GetEnvironFallback(("AR_host", "AR"), "ar"), "CXX.host": GetEnvironFallback(("CXX_host", "CXX"), "g++"), "LINK.host": GetEnvironFallback(("LINK_host", "LINK"), "$(CXX.host)"), "PLI.host": GetEnvironFallback(("PLI_host", "PLI"), "pli"), } if flavor == "mac": flock_command = "./gyp-mac-tool flock" header_params.update( { "flock": flock_command, "flock_index": 2, "link_commands": LINK_COMMANDS_MAC, "extra_commands": SHARED_HEADER_MAC_COMMANDS, } ) elif flavor == "android": header_params.update({"link_commands": LINK_COMMANDS_ANDROID}) elif flavor == "zos": copy_archive_arguments = "-fPR" CC_target = GetEnvironFallback(("CC_target", "CC"), "njsc") makedep_arguments = "-MMD" if CC_target == "clang": CC_host = GetEnvironFallback(("CC_host", "CC"), "clang") CXX_target = GetEnvironFallback(("CXX_target", "CXX"), "clang++") CXX_host = GetEnvironFallback(("CXX_host", "CXX"), "clang++") elif CC_target == "ibm-clang64": CC_host = GetEnvironFallback(("CC_host", "CC"), "ibm-clang64") CXX_target = GetEnvironFallback(("CXX_target", "CXX"), "ibm-clang++64") CXX_host = GetEnvironFallback(("CXX_host", "CXX"), "ibm-clang++64") elif CC_target == "ibm-clang": CC_host = GetEnvironFallback(("CC_host", "CC"), "ibm-clang") CXX_target = GetEnvironFallback(("CXX_target", "CXX"), "ibm-clang++") CXX_host = GetEnvironFallback(("CXX_host", "CXX"), "ibm-clang++") else: # Node.js versions prior to v18: makedep_arguments = "-qmakedep=gcc" CC_host = GetEnvironFallback(("CC_host", "CC"), "njsc") CXX_target = GetEnvironFallback(("CXX_target", "CXX"), "njsc++") CXX_host = GetEnvironFallback(("CXX_host", "CXX"), "njsc++") header_params.update( { "copy_archive_args": copy_archive_arguments, "makedep_args": makedep_arguments, "link_commands": LINK_COMMANDS_OS390, "extra_commands": SHARED_HEADER_OS390_COMMANDS, "CC.target": CC_target, "CXX.target": CXX_target, "CC.host": CC_host, "CXX.host": CXX_host, } ) elif flavor == "solaris": copy_archive_arguments = "-pPRf@" header_params.update( { "copy_archive_args": copy_archive_arguments, "flock": "./gyp-flock-tool flock", "flock_index": 2, } ) elif flavor == "freebsd": # Note: OpenBSD has sysutils/flock. lockf seems to be FreeBSD specific. header_params.update({"flock": "lockf"}) elif flavor == "openbsd": copy_archive_arguments = "-pPRf" header_params.update({"copy_archive_args": copy_archive_arguments}) elif flavor == "aix": copy_archive_arguments = "-pPRf" header_params.update( { "copy_archive_args": copy_archive_arguments, "link_commands": LINK_COMMANDS_AIX, "flock": "./gyp-flock-tool flock", "flock_index": 2, } ) elif flavor == "os400": copy_archive_arguments = "-pPRf" header_params.update( { "copy_archive_args": copy_archive_arguments, "link_commands": LINK_COMMANDS_OS400, "flock": "./gyp-flock-tool flock", "flock_index": 2, } ) build_file, _, _ = gyp.common.ParseQualifiedTarget(target_list[0]) make_global_settings_array = data[build_file].get("make_global_settings", []) wrappers = {} for key, value in make_global_settings_array: if key.endswith("_wrapper"): wrappers[key[: -len("_wrapper")]] = "$(abspath %s)" % value make_global_settings = "" for key, value in make_global_settings_array: if re.match(".*_wrapper", key): continue if value[0] != "$": value = "$(abspath %s)" % value wrapper = wrappers.get(key) if wrapper: value = f"{wrapper} {value}" del wrappers[key] if key in ("CC", "CC.host", "CXX", "CXX.host"): make_global_settings += ( "ifneq (,$(filter $(origin %s), undefined default))\n" % key ) # Let gyp-time envvars win over global settings. env_key = key.replace(".", "_") # CC.host -> CC_host if env_key in os.environ: value = os.environ[env_key] make_global_settings += f" {key} = {value}\n" make_global_settings += "endif\n" else: make_global_settings += f"{key} ?= {value}\n" # TODO(ukai): define cmd when only wrapper is specified in # make_global_settings. header_params["make_global_settings"] = make_global_settings gyp.common.EnsureDirExists(makefile_path) root_makefile = open(makefile_path, "w") root_makefile.write(SHARED_HEADER % header_params) # Currently any versions have the same effect, but in future the behavior # could be different. if android_ndk_version: root_makefile.write( "# Define LOCAL_PATH for build of Android applications.\n" "LOCAL_PATH := $(call my-dir)\n" "\n" ) for toolset in toolsets: root_makefile.write("TOOLSET := %s\n" % toolset) WriteRootHeaderSuffixRules(root_makefile) # Put build-time support tools next to the root Makefile. dest_path = os.path.dirname(makefile_path) gyp.common.CopyTool(flavor, dest_path) # Find the list of targets that derive from the gyp file(s) being built. needed_targets = set() for build_file in params["build_files"]: for target in gyp.common.AllTargets(target_list, target_dicts, build_file): needed_targets.add(target) build_files = set() include_list = set() for qualified_target in target_list: build_file, target, toolset = gyp.common.ParseQualifiedTarget(qualified_target) this_make_global_settings = data[build_file].get("make_global_settings", []) assert make_global_settings_array == this_make_global_settings, ( "make_global_settings needs to be the same for all targets " f"{this_make_global_settings} vs. {make_global_settings}" ) build_files.add(gyp.common.RelativePath(build_file, options.toplevel_dir)) included_files = data[build_file]["included_files"] for included_file in included_files: # The included_files entries are relative to the dir of the build file # that included them, so we have to undo that and then make them relative # to the root dir. relative_include_file = gyp.common.RelativePath( gyp.common.UnrelativePath(included_file, build_file), options.toplevel_dir, ) abs_include_file = os.path.abspath(relative_include_file) # If the include file is from the ~/.gyp dir, we should use absolute path # so that relocating the src dir doesn't break the path. if params["home_dot_gyp"] and abs_include_file.startswith( params["home_dot_gyp"] ): build_files.add(abs_include_file) else: build_files.add(relative_include_file) base_path, output_file = CalculateMakefilePath( build_file, target + "." + toolset + options.suffix + ".mk" ) spec = target_dicts[qualified_target] configs = spec["configurations"] if flavor == "mac": gyp.xcode_emulation.MergeGlobalXcodeSettingsToSpec(data[build_file], spec) writer = MakefileWriter(generator_flags, flavor) writer.Write( qualified_target, base_path, output_file, spec, configs, part_of_all=qualified_target in needed_targets, ) # Our root_makefile lives at the source root. Compute the relative path # from there to the output_file for including. mkfile_rel_path = gyp.common.RelativePath( output_file, os.path.dirname(makefile_path) ) include_list.add(mkfile_rel_path) # Write out per-gyp (sub-project) Makefiles. depth_rel_path = gyp.common.RelativePath(options.depth, os.getcwd()) for build_file in build_files: # The paths in build_files were relativized above, so undo that before # testing against the non-relativized items in target_list and before # calculating the Makefile path. build_file = os.path.join(depth_rel_path, build_file) gyp_targets = [ target_dicts[qualified_target]["target_name"] for qualified_target in target_list if qualified_target.startswith(build_file) and qualified_target in needed_targets ] # Only generate Makefiles for gyp files with targets. if not gyp_targets: continue base_path, output_file = CalculateMakefilePath( build_file, os.path.splitext(os.path.basename(build_file))[0] + ".Makefile" ) makefile_rel_path = gyp.common.RelativePath( os.path.dirname(makefile_path), os.path.dirname(output_file) ) writer.WriteSubMake(output_file, makefile_rel_path, gyp_targets, builddir_name) # Write out the sorted list of includes. root_makefile.write("\n") for include_file in sorted(include_list): # We wrap each .mk include in an if statement so users can tell make to # not load a file by setting NO_LOAD. The below make code says, only # load the .mk file if the .mk filename doesn't start with a token in # NO_LOAD. root_makefile.write( "ifeq ($(strip $(foreach prefix,$(NO_LOAD),\\\n" " $(findstring $(join ^,$(prefix)),\\\n" " $(join ^," + include_file + ")))),)\n" ) root_makefile.write(" include " + include_file + "\n") root_makefile.write("endif\n") root_makefile.write("\n") if not generator_flags.get("standalone") and generator_flags.get( "auto_regeneration", True ): WriteAutoRegenerationRule(params, root_makefile, makefile_name, build_files) root_makefile.write(SHARED_FOOTER) root_makefile.close() PK ~\o_,,)node-gyp/gyp/pylib/gyp/generator/cmake.pynu[# Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """cmake output module This module is under development and should be considered experimental. This module produces cmake (2.8.8+) input as its output. One CMakeLists.txt is created for each configuration. This module's original purpose was to support editing in IDEs like KDevelop which use CMake for project management. It is also possible to use CMake to generate projects for other IDEs such as eclipse cdt and code::blocks. QtCreator will convert the CMakeLists.txt to a code::blocks cbp for the editor to read, but build using CMake. As a result QtCreator editor is unaware of compiler defines. The generated CMakeLists.txt can also be used to build on Linux. There is currently no support for building on platforms other than Linux. The generated CMakeLists.txt should properly compile all projects. However, there is a mismatch between gyp and cmake with regard to linking. All attempts are made to work around this, but CMake sometimes sees -Wl,--start-group as a library and incorrectly repeats it. As a result the output of this generator should not be relied on for building. When using with kdevelop, use version 4.4+. Previous versions of kdevelop will not be able to find the header file directories described in the generated CMakeLists.txt file. """ import multiprocessing import os import signal import subprocess import gyp.common import gyp.xcode_emulation _maketrans = str.maketrans generator_default_variables = { "EXECUTABLE_PREFIX": "", "EXECUTABLE_SUFFIX": "", "STATIC_LIB_PREFIX": "lib", "STATIC_LIB_SUFFIX": ".a", "SHARED_LIB_PREFIX": "lib", "SHARED_LIB_SUFFIX": ".so", "SHARED_LIB_DIR": "${builddir}/lib.${TOOLSET}", "LIB_DIR": "${obj}.${TOOLSET}", "INTERMEDIATE_DIR": "${obj}.${TOOLSET}/${TARGET}/geni", "SHARED_INTERMEDIATE_DIR": "${obj}/gen", "PRODUCT_DIR": "${builddir}", "RULE_INPUT_PATH": "${RULE_INPUT_PATH}", "RULE_INPUT_DIRNAME": "${RULE_INPUT_DIRNAME}", "RULE_INPUT_NAME": "${RULE_INPUT_NAME}", "RULE_INPUT_ROOT": "${RULE_INPUT_ROOT}", "RULE_INPUT_EXT": "${RULE_INPUT_EXT}", "CONFIGURATION_NAME": "${configuration}", } FULL_PATH_VARS = ("${CMAKE_CURRENT_LIST_DIR}", "${builddir}", "${obj}") generator_supports_multiple_toolsets = True generator_wants_static_library_dependencies_adjusted = True COMPILABLE_EXTENSIONS = { ".c": "cc", ".cc": "cxx", ".cpp": "cxx", ".cxx": "cxx", ".s": "s", # cc ".S": "s", # cc } def RemovePrefix(a, prefix): """Returns 'a' without 'prefix' if it starts with 'prefix'.""" return a[len(prefix) :] if a.startswith(prefix) else a def CalculateVariables(default_variables, params): """Calculate additional variables for use in the build (called by gyp).""" default_variables.setdefault("OS", gyp.common.GetFlavor(params)) def Compilable(filename): """Return true if the file is compilable (should be in OBJS).""" return any(filename.endswith(e) for e in COMPILABLE_EXTENSIONS) def Linkable(filename): """Return true if the file is linkable (should be on the link line).""" return filename.endswith(".o") def NormjoinPathForceCMakeSource(base_path, rel_path): """Resolves rel_path against base_path and returns the result. If rel_path is an absolute path it is returned unchanged. Otherwise it is resolved against base_path and normalized. If the result is a relative path, it is forced to be relative to the CMakeLists.txt. """ if os.path.isabs(rel_path): return rel_path if any(rel_path.startswith(var) for var in FULL_PATH_VARS): return rel_path # TODO: do we need to check base_path for absolute variables as well? return os.path.join( "${CMAKE_CURRENT_LIST_DIR}", os.path.normpath(os.path.join(base_path, rel_path)) ) def NormjoinPath(base_path, rel_path): """Resolves rel_path against base_path and returns the result. TODO: what is this really used for? If rel_path begins with '$' it is returned unchanged. Otherwise it is resolved against base_path if relative, then normalized. """ if rel_path.startswith("$") and not rel_path.startswith("${configuration}"): return rel_path return os.path.normpath(os.path.join(base_path, rel_path)) def CMakeStringEscape(a): """Escapes the string 'a' for use inside a CMake string. This means escaping '\' otherwise it may be seen as modifying the next character '"' otherwise it will end the string ';' otherwise the string becomes a list The following do not need to be escaped '#' when the lexer is in string state, this does not start a comment The following are yet unknown '$' generator variables (like ${obj}) must not be escaped, but text $ should be escaped what is wanted is to know which $ come from generator variables """ return a.replace("\\", "\\\\").replace(";", "\\;").replace('"', '\\"') def SetFileProperty(output, source_name, property_name, values, sep): """Given a set of source file, sets the given property on them.""" output.write("set_source_files_properties(") output.write(source_name) output.write(" PROPERTIES ") output.write(property_name) output.write(' "') for value in values: output.write(CMakeStringEscape(value)) output.write(sep) output.write('")\n') def SetFilesProperty(output, variable, property_name, values, sep): """Given a set of source files, sets the given property on them.""" output.write("set_source_files_properties(") WriteVariable(output, variable) output.write(" PROPERTIES ") output.write(property_name) output.write(' "') for value in values: output.write(CMakeStringEscape(value)) output.write(sep) output.write('")\n') def SetTargetProperty(output, target_name, property_name, values, sep=""): """Given a target, sets the given property.""" output.write("set_target_properties(") output.write(target_name) output.write(" PROPERTIES ") output.write(property_name) output.write(' "') for value in values: output.write(CMakeStringEscape(value)) output.write(sep) output.write('")\n') def SetVariable(output, variable_name, value): """Sets a CMake variable.""" output.write("set(") output.write(variable_name) output.write(' "') output.write(CMakeStringEscape(value)) output.write('")\n') def SetVariableList(output, variable_name, values): """Sets a CMake variable to a list.""" if not values: return SetVariable(output, variable_name, "") if len(values) == 1: return SetVariable(output, variable_name, values[0]) output.write("list(APPEND ") output.write(variable_name) output.write('\n "') output.write('"\n "'.join([CMakeStringEscape(value) for value in values])) output.write('")\n') def UnsetVariable(output, variable_name): """Unsets a CMake variable.""" output.write("unset(") output.write(variable_name) output.write(")\n") def WriteVariable(output, variable_name, prepend=None): if prepend: output.write(prepend) output.write("${") output.write(variable_name) output.write("}") class CMakeTargetType: def __init__(self, command, modifier, property_modifier): self.command = command self.modifier = modifier self.property_modifier = property_modifier cmake_target_type_from_gyp_target_type = { "executable": CMakeTargetType("add_executable", None, "RUNTIME"), "static_library": CMakeTargetType("add_library", "STATIC", "ARCHIVE"), "shared_library": CMakeTargetType("add_library", "SHARED", "LIBRARY"), "loadable_module": CMakeTargetType("add_library", "MODULE", "LIBRARY"), "none": CMakeTargetType("add_custom_target", "SOURCES", None), } def StringToCMakeTargetName(a): """Converts the given string 'a' to a valid CMake target name. All invalid characters are replaced by '_'. Invalid for cmake: ' ', '/', '(', ')', '"' Invalid for make: ':' Invalid for unknown reasons but cause failures: '.' """ return a.translate(_maketrans(' /():."', "_______")) def WriteActions(target_name, actions, extra_sources, extra_deps, path_to_gyp, output): """Write CMake for the 'actions' in the target. Args: target_name: the name of the CMake target being generated. actions: the Gyp 'actions' dict for this target. extra_sources: [(, )] to append with generated source files. extra_deps: [] to append with generated targets. path_to_gyp: relative path from CMakeLists.txt being generated to the Gyp file in which the target being generated is defined. """ for action in actions: action_name = StringToCMakeTargetName(action["action_name"]) action_target_name = f"{target_name}__{action_name}" inputs = action["inputs"] inputs_name = action_target_name + "__input" SetVariableList( output, inputs_name, [NormjoinPathForceCMakeSource(path_to_gyp, dep) for dep in inputs], ) outputs = action["outputs"] cmake_outputs = [ NormjoinPathForceCMakeSource(path_to_gyp, out) for out in outputs ] outputs_name = action_target_name + "__output" SetVariableList(output, outputs_name, cmake_outputs) # Build up a list of outputs. # Collect the output dirs we'll need. dirs = {dir for dir in (os.path.dirname(o) for o in outputs) if dir} if int(action.get("process_outputs_as_sources", False)): extra_sources.extend(zip(cmake_outputs, outputs)) # add_custom_command output.write("add_custom_command(OUTPUT ") WriteVariable(output, outputs_name) output.write("\n") if len(dirs) > 0: for directory in dirs: output.write(" COMMAND ${CMAKE_COMMAND} -E make_directory ") output.write(directory) output.write("\n") output.write(" COMMAND ") output.write(gyp.common.EncodePOSIXShellList(action["action"])) output.write("\n") output.write(" DEPENDS ") WriteVariable(output, inputs_name) output.write("\n") output.write(" WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/") output.write(path_to_gyp) output.write("\n") output.write(" COMMENT ") if "message" in action: output.write(action["message"]) else: output.write(action_target_name) output.write("\n") output.write(" VERBATIM\n") output.write(")\n") # add_custom_target output.write("add_custom_target(") output.write(action_target_name) output.write("\n DEPENDS ") WriteVariable(output, outputs_name) output.write("\n SOURCES ") WriteVariable(output, inputs_name) output.write("\n)\n") extra_deps.append(action_target_name) def NormjoinRulePathForceCMakeSource(base_path, rel_path, rule_source): if rel_path.startswith(("${RULE_INPUT_PATH}", "${RULE_INPUT_DIRNAME}")): if any(rule_source.startswith(var) for var in FULL_PATH_VARS): return rel_path return NormjoinPathForceCMakeSource(base_path, rel_path) def WriteRules(target_name, rules, extra_sources, extra_deps, path_to_gyp, output): """Write CMake for the 'rules' in the target. Args: target_name: the name of the CMake target being generated. actions: the Gyp 'actions' dict for this target. extra_sources: [(, )] to append with generated source files. extra_deps: [] to append with generated targets. path_to_gyp: relative path from CMakeLists.txt being generated to the Gyp file in which the target being generated is defined. """ for rule in rules: rule_name = StringToCMakeTargetName(target_name + "__" + rule["rule_name"]) inputs = rule.get("inputs", []) inputs_name = rule_name + "__input" SetVariableList( output, inputs_name, [NormjoinPathForceCMakeSource(path_to_gyp, dep) for dep in inputs], ) outputs = rule["outputs"] var_outputs = [] for count, rule_source in enumerate(rule.get("rule_sources", [])): action_name = rule_name + "_" + str(count) rule_source_dirname, rule_source_basename = os.path.split(rule_source) rule_source_root, rule_source_ext = os.path.splitext(rule_source_basename) SetVariable(output, "RULE_INPUT_PATH", rule_source) SetVariable(output, "RULE_INPUT_DIRNAME", rule_source_dirname) SetVariable(output, "RULE_INPUT_NAME", rule_source_basename) SetVariable(output, "RULE_INPUT_ROOT", rule_source_root) SetVariable(output, "RULE_INPUT_EXT", rule_source_ext) # Build up a list of outputs. # Collect the output dirs we'll need. dirs = {dir for dir in (os.path.dirname(o) for o in outputs) if dir} # Create variables for the output, as 'local' variable will be unset. these_outputs = [] for output_index, out in enumerate(outputs): output_name = action_name + "_" + str(output_index) SetVariable( output, output_name, NormjoinRulePathForceCMakeSource(path_to_gyp, out, rule_source), ) if int(rule.get("process_outputs_as_sources", False)): extra_sources.append(("${" + output_name + "}", out)) these_outputs.append("${" + output_name + "}") var_outputs.append("${" + output_name + "}") # add_custom_command output.write("add_custom_command(OUTPUT\n") for out in these_outputs: output.write(" ") output.write(out) output.write("\n") for directory in dirs: output.write(" COMMAND ${CMAKE_COMMAND} -E make_directory ") output.write(directory) output.write("\n") output.write(" COMMAND ") output.write(gyp.common.EncodePOSIXShellList(rule["action"])) output.write("\n") output.write(" DEPENDS ") WriteVariable(output, inputs_name) output.write(" ") output.write(NormjoinPath(path_to_gyp, rule_source)) output.write("\n") # CMAKE_CURRENT_LIST_DIR is where the CMakeLists.txt lives. # The cwd is the current build directory. output.write(" WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/") output.write(path_to_gyp) output.write("\n") output.write(" COMMENT ") if "message" in rule: output.write(rule["message"]) else: output.write(action_name) output.write("\n") output.write(" VERBATIM\n") output.write(")\n") UnsetVariable(output, "RULE_INPUT_PATH") UnsetVariable(output, "RULE_INPUT_DIRNAME") UnsetVariable(output, "RULE_INPUT_NAME") UnsetVariable(output, "RULE_INPUT_ROOT") UnsetVariable(output, "RULE_INPUT_EXT") # add_custom_target output.write("add_custom_target(") output.write(rule_name) output.write(" DEPENDS\n") for out in var_outputs: output.write(" ") output.write(out) output.write("\n") output.write("SOURCES ") WriteVariable(output, inputs_name) output.write("\n") for rule_source in rule.get("rule_sources", []): output.write(" ") output.write(NormjoinPath(path_to_gyp, rule_source)) output.write("\n") output.write(")\n") extra_deps.append(rule_name) def WriteCopies(target_name, copies, extra_deps, path_to_gyp, output): """Write CMake for the 'copies' in the target. Args: target_name: the name of the CMake target being generated. actions: the Gyp 'actions' dict for this target. extra_deps: [] to append with generated targets. path_to_gyp: relative path from CMakeLists.txt being generated to the Gyp file in which the target being generated is defined. """ copy_name = target_name + "__copies" # CMake gets upset with custom targets with OUTPUT which specify no output. have_copies = any(copy["files"] for copy in copies) if not have_copies: output.write("add_custom_target(") output.write(copy_name) output.write(")\n") extra_deps.append(copy_name) return class Copy: def __init__(self, ext, command): self.cmake_inputs = [] self.cmake_outputs = [] self.gyp_inputs = [] self.gyp_outputs = [] self.ext = ext self.inputs_name = None self.outputs_name = None self.command = command file_copy = Copy("", "copy") dir_copy = Copy("_dirs", "copy_directory") for copy in copies: files = copy["files"] destination = copy["destination"] for src in files: path = os.path.normpath(src) basename = os.path.split(path)[1] dst = os.path.join(destination, basename) copy = file_copy if os.path.basename(src) else dir_copy copy.cmake_inputs.append(NormjoinPathForceCMakeSource(path_to_gyp, src)) copy.cmake_outputs.append(NormjoinPathForceCMakeSource(path_to_gyp, dst)) copy.gyp_inputs.append(src) copy.gyp_outputs.append(dst) for copy in (file_copy, dir_copy): if copy.cmake_inputs: copy.inputs_name = copy_name + "__input" + copy.ext SetVariableList(output, copy.inputs_name, copy.cmake_inputs) copy.outputs_name = copy_name + "__output" + copy.ext SetVariableList(output, copy.outputs_name, copy.cmake_outputs) # add_custom_command output.write("add_custom_command(\n") output.write("OUTPUT") for copy in (file_copy, dir_copy): if copy.outputs_name: WriteVariable(output, copy.outputs_name, " ") output.write("\n") for copy in (file_copy, dir_copy): for src, dst in zip(copy.gyp_inputs, copy.gyp_outputs): # 'cmake -E copy src dst' will create the 'dst' directory if needed. output.write("COMMAND ${CMAKE_COMMAND} -E %s " % copy.command) output.write(src) output.write(" ") output.write(dst) output.write("\n") output.write("DEPENDS") for copy in (file_copy, dir_copy): if copy.inputs_name: WriteVariable(output, copy.inputs_name, " ") output.write("\n") output.write("WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/") output.write(path_to_gyp) output.write("\n") output.write("COMMENT Copying for ") output.write(target_name) output.write("\n") output.write("VERBATIM\n") output.write(")\n") # add_custom_target output.write("add_custom_target(") output.write(copy_name) output.write("\n DEPENDS") for copy in (file_copy, dir_copy): if copy.outputs_name: WriteVariable(output, copy.outputs_name, " ") output.write("\n SOURCES") if file_copy.inputs_name: WriteVariable(output, file_copy.inputs_name, " ") output.write("\n)\n") extra_deps.append(copy_name) def CreateCMakeTargetBaseName(qualified_target): """This is the name we would like the target to have.""" _, gyp_target_name, gyp_target_toolset = gyp.common.ParseQualifiedTarget( qualified_target ) cmake_target_base_name = gyp_target_name if gyp_target_toolset and gyp_target_toolset != "target": cmake_target_base_name += "_" + gyp_target_toolset return StringToCMakeTargetName(cmake_target_base_name) def CreateCMakeTargetFullName(qualified_target): """An unambiguous name for the target.""" gyp_file, gyp_target_name, gyp_target_toolset = gyp.common.ParseQualifiedTarget( qualified_target ) cmake_target_full_name = gyp_file + ":" + gyp_target_name if gyp_target_toolset and gyp_target_toolset != "target": cmake_target_full_name += "_" + gyp_target_toolset return StringToCMakeTargetName(cmake_target_full_name) class CMakeNamer: """Converts Gyp target names into CMake target names. CMake requires that target names be globally unique. One way to ensure this is to fully qualify the names of the targets. Unfortunately, this ends up with all targets looking like "chrome_chrome_gyp_chrome" instead of just "chrome". If this generator were only interested in building, it would be possible to fully qualify all target names, then create unqualified target names which depend on all qualified targets which should have had that name. This is more or less what the 'make' generator does with aliases. However, one goal of this generator is to create CMake files for use with IDEs, and fully qualified names are not as user friendly. Since target name collision is rare, we do the above only when required. Toolset variants are always qualified from the base, as this is required for building. However, it also makes sense for an IDE, as it is possible for defines to be different. """ def __init__(self, target_list): self.cmake_target_base_names_conficting = set() cmake_target_base_names_seen = set() for qualified_target in target_list: cmake_target_base_name = CreateCMakeTargetBaseName(qualified_target) if cmake_target_base_name not in cmake_target_base_names_seen: cmake_target_base_names_seen.add(cmake_target_base_name) else: self.cmake_target_base_names_conficting.add(cmake_target_base_name) def CreateCMakeTargetName(self, qualified_target): base_name = CreateCMakeTargetBaseName(qualified_target) if base_name in self.cmake_target_base_names_conficting: return CreateCMakeTargetFullName(qualified_target) return base_name def WriteTarget( namer, qualified_target, target_dicts, build_dir, config_to_use, options, generator_flags, all_qualified_targets, flavor, output, ): # The make generator does this always. # TODO: It would be nice to be able to tell CMake all dependencies. circular_libs = generator_flags.get("circular", True) if not generator_flags.get("standalone", False): output.write("\n#") output.write(qualified_target) output.write("\n") gyp_file, _, _ = gyp.common.ParseQualifiedTarget(qualified_target) rel_gyp_file = gyp.common.RelativePath(gyp_file, options.toplevel_dir) rel_gyp_dir = os.path.dirname(rel_gyp_file) # Relative path from build dir to top dir. build_to_top = gyp.common.InvertRelativePath(build_dir, options.toplevel_dir) # Relative path from build dir to gyp dir. build_to_gyp = os.path.join(build_to_top, rel_gyp_dir) path_from_cmakelists_to_gyp = build_to_gyp spec = target_dicts.get(qualified_target, {}) config = spec.get("configurations", {}).get(config_to_use, {}) xcode_settings = None if flavor == "mac": xcode_settings = gyp.xcode_emulation.XcodeSettings(spec) target_name = spec.get("target_name", "") target_type = spec.get("type", "") target_toolset = spec.get("toolset") cmake_target_type = cmake_target_type_from_gyp_target_type.get(target_type) if cmake_target_type is None: print( "Target %s has unknown target type %s, skipping." % (target_name, target_type) ) return SetVariable(output, "TARGET", target_name) SetVariable(output, "TOOLSET", target_toolset) cmake_target_name = namer.CreateCMakeTargetName(qualified_target) extra_sources = [] extra_deps = [] # Actions must come first, since they can generate more OBJs for use below. if "actions" in spec: WriteActions( cmake_target_name, spec["actions"], extra_sources, extra_deps, path_from_cmakelists_to_gyp, output, ) # Rules must be early like actions. if "rules" in spec: WriteRules( cmake_target_name, spec["rules"], extra_sources, extra_deps, path_from_cmakelists_to_gyp, output, ) # Copies if "copies" in spec: WriteCopies( cmake_target_name, spec["copies"], extra_deps, path_from_cmakelists_to_gyp, output, ) # Target and sources srcs = spec.get("sources", []) # Gyp separates the sheep from the goats based on file extensions. # A full separation is done here because of flag handing (see below). s_sources = [] c_sources = [] cxx_sources = [] linkable_sources = [] other_sources = [] for src in srcs: _, ext = os.path.splitext(src) src_type = COMPILABLE_EXTENSIONS.get(ext, None) src_norm_path = NormjoinPath(path_from_cmakelists_to_gyp, src) if src_type == "s": s_sources.append(src_norm_path) elif src_type == "cc": c_sources.append(src_norm_path) elif src_type == "cxx": cxx_sources.append(src_norm_path) elif Linkable(ext): linkable_sources.append(src_norm_path) else: other_sources.append(src_norm_path) for extra_source in extra_sources: src, real_source = extra_source _, ext = os.path.splitext(real_source) src_type = COMPILABLE_EXTENSIONS.get(ext, None) if src_type == "s": s_sources.append(src) elif src_type == "cc": c_sources.append(src) elif src_type == "cxx": cxx_sources.append(src) elif Linkable(ext): linkable_sources.append(src) else: other_sources.append(src) s_sources_name = None if s_sources: s_sources_name = cmake_target_name + "__asm_srcs" SetVariableList(output, s_sources_name, s_sources) c_sources_name = None if c_sources: c_sources_name = cmake_target_name + "__c_srcs" SetVariableList(output, c_sources_name, c_sources) cxx_sources_name = None if cxx_sources: cxx_sources_name = cmake_target_name + "__cxx_srcs" SetVariableList(output, cxx_sources_name, cxx_sources) linkable_sources_name = None if linkable_sources: linkable_sources_name = cmake_target_name + "__linkable_srcs" SetVariableList(output, linkable_sources_name, linkable_sources) other_sources_name = None if other_sources: other_sources_name = cmake_target_name + "__other_srcs" SetVariableList(output, other_sources_name, other_sources) # CMake gets upset when executable targets provide no sources. # http://www.cmake.org/pipermail/cmake/2010-July/038461.html dummy_sources_name = None has_sources = ( s_sources_name or c_sources_name or cxx_sources_name or linkable_sources_name or other_sources_name ) if target_type == "executable" and not has_sources: dummy_sources_name = cmake_target_name + "__dummy_srcs" SetVariable( output, dummy_sources_name, "${obj}.${TOOLSET}/${TARGET}/genc/dummy.c" ) output.write('if(NOT EXISTS "') WriteVariable(output, dummy_sources_name) output.write('")\n') output.write(' file(WRITE "') WriteVariable(output, dummy_sources_name) output.write('" "")\n') output.write("endif()\n") # CMake is opposed to setting linker directories and considers the practice # of setting linker directories dangerous. Instead, it favors the use of # find_library and passing absolute paths to target_link_libraries. # However, CMake does provide the command link_directories, which adds # link directories to targets defined after it is called. # As a result, link_directories must come before the target definition. # CMake unfortunately has no means of removing entries from LINK_DIRECTORIES. library_dirs = config.get("library_dirs") if library_dirs is not None: output.write("link_directories(") for library_dir in library_dirs: output.write(" ") output.write(NormjoinPath(path_from_cmakelists_to_gyp, library_dir)) output.write("\n") output.write(")\n") output.write(cmake_target_type.command) output.write("(") output.write(cmake_target_name) if cmake_target_type.modifier is not None: output.write(" ") output.write(cmake_target_type.modifier) if s_sources_name: WriteVariable(output, s_sources_name, " ") if c_sources_name: WriteVariable(output, c_sources_name, " ") if cxx_sources_name: WriteVariable(output, cxx_sources_name, " ") if linkable_sources_name: WriteVariable(output, linkable_sources_name, " ") if other_sources_name: WriteVariable(output, other_sources_name, " ") if dummy_sources_name: WriteVariable(output, dummy_sources_name, " ") output.write(")\n") # Let CMake know if the 'all' target should depend on this target. exclude_from_all = ( "TRUE" if qualified_target not in all_qualified_targets else "FALSE" ) SetTargetProperty(output, cmake_target_name, "EXCLUDE_FROM_ALL", exclude_from_all) for extra_target_name in extra_deps: SetTargetProperty( output, extra_target_name, "EXCLUDE_FROM_ALL", exclude_from_all ) # Output name and location. if target_type != "none": # Link as 'C' if there are no other files if not c_sources and not cxx_sources: SetTargetProperty(output, cmake_target_name, "LINKER_LANGUAGE", ["C"]) # Mark uncompiled sources as uncompiled. if other_sources_name: output.write("set_source_files_properties(") WriteVariable(output, other_sources_name, "") output.write(' PROPERTIES HEADER_FILE_ONLY "TRUE")\n') # Mark object sources as linkable. if linkable_sources_name: output.write("set_source_files_properties(") WriteVariable(output, other_sources_name, "") output.write(' PROPERTIES EXTERNAL_OBJECT "TRUE")\n') # Output directory target_output_directory = spec.get("product_dir") if target_output_directory is None: if target_type in ("executable", "loadable_module"): target_output_directory = generator_default_variables["PRODUCT_DIR"] elif target_type == "shared_library": target_output_directory = "${builddir}/lib.${TOOLSET}" elif spec.get("standalone_static_library", False): target_output_directory = generator_default_variables["PRODUCT_DIR"] else: base_path = gyp.common.RelativePath( os.path.dirname(gyp_file), options.toplevel_dir ) target_output_directory = "${obj}.${TOOLSET}" target_output_directory = os.path.join( target_output_directory, base_path ) cmake_target_output_directory = NormjoinPathForceCMakeSource( path_from_cmakelists_to_gyp, target_output_directory ) SetTargetProperty( output, cmake_target_name, cmake_target_type.property_modifier + "_OUTPUT_DIRECTORY", cmake_target_output_directory, ) # Output name default_product_prefix = "" default_product_name = target_name default_product_ext = "" if target_type == "static_library": static_library_prefix = generator_default_variables["STATIC_LIB_PREFIX"] default_product_name = RemovePrefix( default_product_name, static_library_prefix ) default_product_prefix = static_library_prefix default_product_ext = generator_default_variables["STATIC_LIB_SUFFIX"] elif target_type in ("loadable_module", "shared_library"): shared_library_prefix = generator_default_variables["SHARED_LIB_PREFIX"] default_product_name = RemovePrefix( default_product_name, shared_library_prefix ) default_product_prefix = shared_library_prefix default_product_ext = generator_default_variables["SHARED_LIB_SUFFIX"] elif target_type != "executable": print( "ERROR: What output file should be generated?", "type", target_type, "target", target_name, ) product_prefix = spec.get("product_prefix", default_product_prefix) product_name = spec.get("product_name", default_product_name) product_ext = spec.get("product_extension") product_ext = "." + product_ext if product_ext else default_product_ext SetTargetProperty(output, cmake_target_name, "PREFIX", product_prefix) SetTargetProperty( output, cmake_target_name, cmake_target_type.property_modifier + "_OUTPUT_NAME", product_name, ) SetTargetProperty(output, cmake_target_name, "SUFFIX", product_ext) # Make the output of this target referenceable as a source. cmake_target_output_basename = product_prefix + product_name + product_ext cmake_target_output = os.path.join( cmake_target_output_directory, cmake_target_output_basename ) SetFileProperty(output, cmake_target_output, "GENERATED", ["TRUE"], "") # Includes includes = config.get("include_dirs") if includes: # This (target include directories) is what requires CMake 2.8.8 includes_name = cmake_target_name + "__include_dirs" SetVariableList( output, includes_name, [ NormjoinPathForceCMakeSource(path_from_cmakelists_to_gyp, include) for include in includes ], ) output.write("set_property(TARGET ") output.write(cmake_target_name) output.write(" APPEND PROPERTY INCLUDE_DIRECTORIES ") WriteVariable(output, includes_name, "") output.write(")\n") # Defines defines = config.get("defines") if defines is not None: SetTargetProperty( output, cmake_target_name, "COMPILE_DEFINITIONS", defines, ";" ) # Compile Flags - http://www.cmake.org/Bug/view.php?id=6493 # CMake currently does not have target C and CXX flags. # So, instead of doing... # cflags_c = config.get('cflags_c') # if cflags_c is not None: # SetTargetProperty(output, cmake_target_name, # 'C_COMPILE_FLAGS', cflags_c, ' ') # cflags_cc = config.get('cflags_cc') # if cflags_cc is not None: # SetTargetProperty(output, cmake_target_name, # 'CXX_COMPILE_FLAGS', cflags_cc, ' ') # Instead we must... cflags = config.get("cflags", []) cflags_c = config.get("cflags_c", []) cflags_cxx = config.get("cflags_cc", []) if xcode_settings: cflags = xcode_settings.GetCflags(config_to_use) cflags_c = xcode_settings.GetCflagsC(config_to_use) cflags_cxx = xcode_settings.GetCflagsCC(config_to_use) # cflags_objc = xcode_settings.GetCflagsObjC(config_to_use) # cflags_objcc = xcode_settings.GetCflagsObjCC(config_to_use) if (not cflags_c or not c_sources) and (not cflags_cxx or not cxx_sources): SetTargetProperty(output, cmake_target_name, "COMPILE_FLAGS", cflags, " ") elif c_sources and not (s_sources or cxx_sources): flags = [] flags.extend(cflags) flags.extend(cflags_c) SetTargetProperty(output, cmake_target_name, "COMPILE_FLAGS", flags, " ") elif cxx_sources and not (s_sources or c_sources): flags = [] flags.extend(cflags) flags.extend(cflags_cxx) SetTargetProperty(output, cmake_target_name, "COMPILE_FLAGS", flags, " ") else: # TODO: This is broken, one cannot generally set properties on files, # as other targets may require different properties on the same files. if s_sources and cflags: SetFilesProperty(output, s_sources_name, "COMPILE_FLAGS", cflags, " ") if c_sources and (cflags or cflags_c): flags = [] flags.extend(cflags) flags.extend(cflags_c) SetFilesProperty(output, c_sources_name, "COMPILE_FLAGS", flags, " ") if cxx_sources and (cflags or cflags_cxx): flags = [] flags.extend(cflags) flags.extend(cflags_cxx) SetFilesProperty(output, cxx_sources_name, "COMPILE_FLAGS", flags, " ") # Linker flags ldflags = config.get("ldflags") if ldflags is not None: SetTargetProperty(output, cmake_target_name, "LINK_FLAGS", ldflags, " ") # XCode settings xcode_settings = config.get("xcode_settings", {}) for xcode_setting, xcode_value in xcode_settings.items(): SetTargetProperty( output, cmake_target_name, "XCODE_ATTRIBUTE_%s" % xcode_setting, xcode_value, "" if isinstance(xcode_value, str) else " ", ) # Note on Dependencies and Libraries: # CMake wants to handle link order, resolving the link line up front. # Gyp does not retain or enforce specifying enough information to do so. # So do as other gyp generators and use --start-group and --end-group. # Give CMake as little information as possible so that it doesn't mess it up. # Dependencies rawDeps = spec.get("dependencies", []) static_deps = [] shared_deps = [] other_deps = [] for rawDep in rawDeps: dep_cmake_name = namer.CreateCMakeTargetName(rawDep) dep_spec = target_dicts.get(rawDep, {}) dep_target_type = dep_spec.get("type", None) if dep_target_type == "static_library": static_deps.append(dep_cmake_name) elif dep_target_type == "shared_library": shared_deps.append(dep_cmake_name) else: other_deps.append(dep_cmake_name) # ensure all external dependencies are complete before internal dependencies # extra_deps currently only depend on their own deps, so otherwise run early if static_deps or shared_deps or other_deps: for extra_dep in extra_deps: output.write("add_dependencies(") output.write(extra_dep) output.write("\n") for deps in (static_deps, shared_deps, other_deps): for dep in gyp.common.uniquer(deps): output.write(" ") output.write(dep) output.write("\n") output.write(")\n") linkable = target_type in ("executable", "loadable_module", "shared_library") other_deps.extend(extra_deps) if other_deps or (not linkable and (static_deps or shared_deps)): output.write("add_dependencies(") output.write(cmake_target_name) output.write("\n") for dep in gyp.common.uniquer(other_deps): output.write(" ") output.write(dep) output.write("\n") if not linkable: for deps in (static_deps, shared_deps): for lib_dep in gyp.common.uniquer(deps): output.write(" ") output.write(lib_dep) output.write("\n") output.write(")\n") # Libraries if linkable: external_libs = [lib for lib in spec.get("libraries", []) if len(lib) > 0] if external_libs or static_deps or shared_deps: output.write("target_link_libraries(") output.write(cmake_target_name) output.write("\n") if static_deps: write_group = circular_libs and len(static_deps) > 1 and flavor != "mac" if write_group: output.write("-Wl,--start-group\n") for dep in gyp.common.uniquer(static_deps): output.write(" ") output.write(dep) output.write("\n") if write_group: output.write("-Wl,--end-group\n") if shared_deps: for dep in gyp.common.uniquer(shared_deps): output.write(" ") output.write(dep) output.write("\n") if external_libs: for lib in gyp.common.uniquer(external_libs): output.write(' "') output.write(RemovePrefix(lib, "$(SDKROOT)")) output.write('"\n') output.write(")\n") UnsetVariable(output, "TOOLSET") UnsetVariable(output, "TARGET") def GenerateOutputForConfig(target_list, target_dicts, data, params, config_to_use): options = params["options"] generator_flags = params["generator_flags"] flavor = gyp.common.GetFlavor(params) # generator_dir: relative path from pwd to where make puts build files. # Makes migrating from make to cmake easier, cmake doesn't put anything here. # Each Gyp configuration creates a different CMakeLists.txt file # to avoid incompatibilities between Gyp and CMake configurations. generator_dir = os.path.relpath(options.generator_output or ".") # output_dir: relative path from generator_dir to the build directory. output_dir = generator_flags.get("output_dir", "out") # build_dir: relative path from source root to our output files. # e.g. "out/Debug" build_dir = os.path.normpath(os.path.join(generator_dir, output_dir, config_to_use)) toplevel_build = os.path.join(options.toplevel_dir, build_dir) output_file = os.path.join(toplevel_build, "CMakeLists.txt") gyp.common.EnsureDirExists(output_file) output = open(output_file, "w") output.write("cmake_minimum_required(VERSION 2.8.8 FATAL_ERROR)\n") output.write("cmake_policy(VERSION 2.8.8)\n") gyp_file, project_target, _ = gyp.common.ParseQualifiedTarget(target_list[-1]) output.write("project(") output.write(project_target) output.write(")\n") SetVariable(output, "configuration", config_to_use) ar = None cc = None cxx = None make_global_settings = data[gyp_file].get("make_global_settings", []) build_to_top = gyp.common.InvertRelativePath(build_dir, options.toplevel_dir) for key, value in make_global_settings: if key == "AR": ar = os.path.join(build_to_top, value) if key == "CC": cc = os.path.join(build_to_top, value) if key == "CXX": cxx = os.path.join(build_to_top, value) ar = gyp.common.GetEnvironFallback(["AR_target", "AR"], ar) cc = gyp.common.GetEnvironFallback(["CC_target", "CC"], cc) cxx = gyp.common.GetEnvironFallback(["CXX_target", "CXX"], cxx) if ar: SetVariable(output, "CMAKE_AR", ar) if cc: SetVariable(output, "CMAKE_C_COMPILER", cc) if cxx: SetVariable(output, "CMAKE_CXX_COMPILER", cxx) # The following appears to be as-yet undocumented. # http://public.kitware.com/Bug/view.php?id=8392 output.write("enable_language(ASM)\n") # ASM-ATT does not support .S files. # output.write('enable_language(ASM-ATT)\n') if cc: SetVariable(output, "CMAKE_ASM_COMPILER", cc) SetVariable(output, "builddir", "${CMAKE_CURRENT_BINARY_DIR}") SetVariable(output, "obj", "${builddir}/obj") output.write("\n") # TODO: Undocumented/unsupported (the CMake Java generator depends on it). # CMake by default names the object resulting from foo.c to be foo.c.o. # Gyp traditionally names the object resulting from foo.c foo.o. # This should be irrelevant, but some targets extract .o files from .a # and depend on the name of the extracted .o files. output.write("set(CMAKE_C_OUTPUT_EXTENSION_REPLACE 1)\n") output.write("set(CMAKE_CXX_OUTPUT_EXTENSION_REPLACE 1)\n") output.write("\n") # Force ninja to use rsp files. Otherwise link and ar lines can get too long, # resulting in 'Argument list too long' errors. # However, rsp files don't work correctly on Mac. if flavor != "mac": output.write("set(CMAKE_NINJA_FORCE_RESPONSE_FILE 1)\n") output.write("\n") namer = CMakeNamer(target_list) # The list of targets upon which the 'all' target should depend. # CMake has it's own implicit 'all' target, one is not created explicitly. all_qualified_targets = set() for build_file in params["build_files"]: for qualified_target in gyp.common.AllTargets( target_list, target_dicts, os.path.normpath(build_file) ): all_qualified_targets.add(qualified_target) for qualified_target in target_list: if flavor == "mac": gyp_file, _, _ = gyp.common.ParseQualifiedTarget(qualified_target) spec = target_dicts[qualified_target] gyp.xcode_emulation.MergeGlobalXcodeSettingsToSpec(data[gyp_file], spec) WriteTarget( namer, qualified_target, target_dicts, build_dir, config_to_use, options, generator_flags, all_qualified_targets, flavor, output, ) output.close() def PerformBuild(data, configurations, params): options = params["options"] generator_flags = params["generator_flags"] # generator_dir: relative path from pwd to where make puts build files. # Makes migrating from make to cmake easier, cmake doesn't put anything here. generator_dir = os.path.relpath(options.generator_output or ".") # output_dir: relative path from generator_dir to the build directory. output_dir = generator_flags.get("output_dir", "out") for config_name in configurations: # build_dir: relative path from source root to our output files. # e.g. "out/Debug" build_dir = os.path.normpath( os.path.join(generator_dir, output_dir, config_name) ) arguments = ["cmake", "-G", "Ninja"] print(f"Generating [{config_name}]: {arguments}") subprocess.check_call(arguments, cwd=build_dir) arguments = ["ninja", "-C", build_dir] print(f"Building [{config_name}]: {arguments}") subprocess.check_call(arguments) def CallGenerateOutputForConfig(arglist): # Ignore the interrupt signal so that the parent process catches it and # kills all multiprocessing children. signal.signal(signal.SIGINT, signal.SIG_IGN) target_list, target_dicts, data, params, config_name = arglist GenerateOutputForConfig(target_list, target_dicts, data, params, config_name) def GenerateOutput(target_list, target_dicts, data, params): user_config = params.get("generator_flags", {}).get("config", None) if user_config: GenerateOutputForConfig(target_list, target_dicts, data, params, user_config) else: config_names = target_dicts[target_list[0]]["configurations"] if params["parallel"]: try: pool = multiprocessing.Pool(len(config_names)) arglists = [] for config_name in config_names: arglists.append( (target_list, target_dicts, data, params, config_name) ) pool.map(CallGenerateOutputForConfig, arglists) except KeyboardInterrupt as e: pool.terminate() raise e else: for config_name in config_names: GenerateOutputForConfig( target_list, target_dicts, data, params, config_name ) PK ~\A  8node-gyp/gyp/pylib/gyp/generator/dump_dependency_json.pynu[# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import gyp import gyp.common import gyp.msvs_emulation import json generator_supports_multiple_toolsets = True generator_wants_static_library_dependencies_adjusted = False generator_filelist_paths = {} generator_default_variables = {} for dirname in [ "INTERMEDIATE_DIR", "SHARED_INTERMEDIATE_DIR", "PRODUCT_DIR", "LIB_DIR", "SHARED_LIB_DIR", ]: # Some gyp steps fail if these are empty(!). generator_default_variables[dirname] = "dir" for unused in [ "RULE_INPUT_PATH", "RULE_INPUT_ROOT", "RULE_INPUT_NAME", "RULE_INPUT_DIRNAME", "RULE_INPUT_EXT", "EXECUTABLE_PREFIX", "EXECUTABLE_SUFFIX", "STATIC_LIB_PREFIX", "STATIC_LIB_SUFFIX", "SHARED_LIB_PREFIX", "SHARED_LIB_SUFFIX", "CONFIGURATION_NAME", ]: generator_default_variables[unused] = "" def CalculateVariables(default_variables, params): generator_flags = params.get("generator_flags", {}) for key, val in generator_flags.items(): default_variables.setdefault(key, val) default_variables.setdefault("OS", gyp.common.GetFlavor(params)) flavor = gyp.common.GetFlavor(params) if flavor == "win": gyp.msvs_emulation.CalculateCommonVariables(default_variables, params) def CalculateGeneratorInputInfo(params): """Calculate the generator specific info that gets fed to input (called by gyp).""" generator_flags = params.get("generator_flags", {}) if generator_flags.get("adjust_static_libraries", False): global generator_wants_static_library_dependencies_adjusted generator_wants_static_library_dependencies_adjusted = True toplevel = params["options"].toplevel_dir generator_dir = os.path.relpath(params["options"].generator_output or ".") # output_dir: relative path from generator_dir to the build directory. output_dir = generator_flags.get("output_dir", "out") qualified_out_dir = os.path.normpath( os.path.join(toplevel, generator_dir, output_dir, "gypfiles") ) global generator_filelist_paths generator_filelist_paths = { "toplevel": toplevel, "qualified_out_dir": qualified_out_dir, } def GenerateOutput(target_list, target_dicts, data, params): # Map of target -> list of targets it depends on. edges = {} # Queue of targets to visit. targets_to_visit = target_list[:] while len(targets_to_visit) > 0: target = targets_to_visit.pop() if target in edges: continue edges[target] = [] for dep in target_dicts[target].get("dependencies", []): edges[target].append(dep) targets_to_visit.append(dep) try: filepath = params["generator_flags"]["output_dir"] except KeyError: filepath = "." filename = os.path.join(filepath, "dump.json") f = open(filename, "w") json.dump(edges, f) f.close() print("Wrote json to %s." % filename) PK ~\@Uɺ]D]D+node-gyp/gyp/pylib/gyp/generator/eclipse.pynu[# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """GYP backend that generates Eclipse CDT settings files. This backend DOES NOT generate Eclipse CDT projects. Instead, it generates XML files that can be imported into an Eclipse CDT project. The XML file contains a list of include paths and symbols (i.e. defines). Because a full .cproject definition is not created by this generator, it's not possible to properly define the include dirs and symbols for each file individually. Instead, one set of includes/symbols is generated for the entire project. This works fairly well (and is a vast improvement in general), but may still result in a few indexer issues here and there. This generator has no automated tests, so expect it to be broken. """ from xml.sax.saxutils import escape import os.path import subprocess import gyp import gyp.common import gyp.msvs_emulation import shlex import xml.etree.ElementTree as ET generator_wants_static_library_dependencies_adjusted = False generator_default_variables = {} for dirname in ["INTERMEDIATE_DIR", "PRODUCT_DIR", "LIB_DIR", "SHARED_LIB_DIR"]: # Some gyp steps fail if these are empty(!), so we convert them to variables generator_default_variables[dirname] = "$" + dirname for unused in [ "RULE_INPUT_PATH", "RULE_INPUT_ROOT", "RULE_INPUT_NAME", "RULE_INPUT_DIRNAME", "RULE_INPUT_EXT", "EXECUTABLE_PREFIX", "EXECUTABLE_SUFFIX", "STATIC_LIB_PREFIX", "STATIC_LIB_SUFFIX", "SHARED_LIB_PREFIX", "SHARED_LIB_SUFFIX", "CONFIGURATION_NAME", ]: generator_default_variables[unused] = "" # Include dirs will occasionally use the SHARED_INTERMEDIATE_DIR variable as # part of the path when dealing with generated headers. This value will be # replaced dynamically for each configuration. generator_default_variables["SHARED_INTERMEDIATE_DIR"] = "$SHARED_INTERMEDIATE_DIR" def CalculateVariables(default_variables, params): generator_flags = params.get("generator_flags", {}) for key, val in generator_flags.items(): default_variables.setdefault(key, val) flavor = gyp.common.GetFlavor(params) default_variables.setdefault("OS", flavor) if flavor == "win": gyp.msvs_emulation.CalculateCommonVariables(default_variables, params) def CalculateGeneratorInputInfo(params): """Calculate the generator specific info that gets fed to input (called by gyp).""" generator_flags = params.get("generator_flags", {}) if generator_flags.get("adjust_static_libraries", False): global generator_wants_static_library_dependencies_adjusted generator_wants_static_library_dependencies_adjusted = True def GetAllIncludeDirectories( target_list, target_dicts, shared_intermediate_dirs, config_name, params, compiler_path, ): """Calculate the set of include directories to be used. Returns: A list including all the include_dir's specified for every target followed by any include directories that were added as cflag compiler options. """ gyp_includes_set = set() compiler_includes_list = [] # Find compiler's default include dirs. if compiler_path: command = shlex.split(compiler_path) command.extend(["-E", "-xc++", "-v", "-"]) proc = subprocess.Popen( args=command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) output = proc.communicate()[1].decode("utf-8") # Extract the list of include dirs from the output, which has this format: # ... # #include "..." search starts here: # #include <...> search starts here: # /usr/include/c++/4.6 # /usr/local/include # End of search list. # ... in_include_list = False for line in output.splitlines(): if line.startswith("#include"): in_include_list = True continue if line.startswith("End of search list."): break if in_include_list: include_dir = line.strip() if include_dir not in compiler_includes_list: compiler_includes_list.append(include_dir) flavor = gyp.common.GetFlavor(params) if flavor == "win": generator_flags = params.get("generator_flags", {}) for target_name in target_list: target = target_dicts[target_name] if config_name in target["configurations"]: config = target["configurations"][config_name] # Look for any include dirs that were explicitly added via cflags. This # may be done in gyp files to force certain includes to come at the end. # TODO(jgreenwald): Change the gyp files to not abuse cflags for this, and # remove this. if flavor == "win": msvs_settings = gyp.msvs_emulation.MsvsSettings(target, generator_flags) cflags = msvs_settings.GetCflags(config_name) else: cflags = config["cflags"] for cflag in cflags: if cflag.startswith("-I"): include_dir = cflag[2:] if include_dir not in compiler_includes_list: compiler_includes_list.append(include_dir) # Find standard gyp include dirs. if "include_dirs" in config: include_dirs = config["include_dirs"] for shared_intermediate_dir in shared_intermediate_dirs: for include_dir in include_dirs: include_dir = include_dir.replace( "$SHARED_INTERMEDIATE_DIR", shared_intermediate_dir ) if not os.path.isabs(include_dir): base_dir = os.path.dirname(target_name) include_dir = base_dir + "/" + include_dir include_dir = os.path.abspath(include_dir) gyp_includes_set.add(include_dir) # Generate a list that has all the include dirs. all_includes_list = list(gyp_includes_set) all_includes_list.sort() for compiler_include in compiler_includes_list: if compiler_include not in gyp_includes_set: all_includes_list.append(compiler_include) # All done. return all_includes_list def GetCompilerPath(target_list, data, options): """Determine a command that can be used to invoke the compiler. Returns: If this is a gyp project that has explicit make settings, try to determine the compiler from that. Otherwise, see if a compiler was specified via the CC_target environment variable. """ # First, see if the compiler is configured in make's settings. build_file, _, _ = gyp.common.ParseQualifiedTarget(target_list[0]) make_global_settings_dict = data[build_file].get("make_global_settings", {}) for key, value in make_global_settings_dict: if key in ["CC", "CXX"]: return os.path.join(options.toplevel_dir, value) # Check to see if the compiler was specified as an environment variable. for key in ["CC_target", "CC", "CXX"]: compiler = os.environ.get(key) if compiler: return compiler return "gcc" def GetAllDefines(target_list, target_dicts, data, config_name, params, compiler_path): """Calculate the defines for a project. Returns: A dict that includes explicit defines declared in gyp files along with all of the default defines that the compiler uses. """ # Get defines declared in the gyp files. all_defines = {} flavor = gyp.common.GetFlavor(params) if flavor == "win": generator_flags = params.get("generator_flags", {}) for target_name in target_list: target = target_dicts[target_name] if flavor == "win": msvs_settings = gyp.msvs_emulation.MsvsSettings(target, generator_flags) extra_defines = msvs_settings.GetComputedDefines(config_name) else: extra_defines = [] if config_name in target["configurations"]: config = target["configurations"][config_name] target_defines = config["defines"] else: target_defines = [] for define in target_defines + extra_defines: split_define = define.split("=", 1) if len(split_define) == 1: split_define.append("1") if split_define[0].strip() in all_defines: # Already defined continue all_defines[split_define[0].strip()] = split_define[1].strip() # Get default compiler defines (if possible). if flavor == "win": return all_defines # Default defines already processed in the loop above. if compiler_path: command = shlex.split(compiler_path) command.extend(["-E", "-dM", "-"]) cpp_proc = subprocess.Popen( args=command, cwd=".", stdin=subprocess.PIPE, stdout=subprocess.PIPE ) cpp_output = cpp_proc.communicate()[0].decode("utf-8") cpp_lines = cpp_output.split("\n") for cpp_line in cpp_lines: if not cpp_line.strip(): continue cpp_line_parts = cpp_line.split(" ", 2) key = cpp_line_parts[1] val = cpp_line_parts[2] if len(cpp_line_parts) >= 3 else "1" all_defines[key] = val return all_defines def WriteIncludePaths(out, eclipse_langs, include_dirs): """Write the includes section of a CDT settings export file.""" out.write( '
\n' ) out.write(' \n') for lang in eclipse_langs: out.write(' \n' % lang) for include_dir in include_dirs: out.write( ' %s\n' % include_dir ) out.write(" \n") out.write("
\n") def WriteMacros(out, eclipse_langs, defines): """Write the macros section of a CDT settings export file.""" out.write( '
\n' ) out.write(' \n') for lang in eclipse_langs: out.write(' \n' % lang) for key in sorted(defines): out.write( " %s%s\n" % (escape(key), escape(defines[key])) ) out.write(" \n") out.write("
\n") def GenerateOutputForConfig(target_list, target_dicts, data, params, config_name): options = params["options"] generator_flags = params.get("generator_flags", {}) # build_dir: relative path from source root to our output files. # e.g. "out/Debug" build_dir = os.path.join(generator_flags.get("output_dir", "out"), config_name) toplevel_build = os.path.join(options.toplevel_dir, build_dir) # Ninja uses out/Debug/gen while make uses out/Debug/obj/gen as the # SHARED_INTERMEDIATE_DIR. Include both possible locations. shared_intermediate_dirs = [ os.path.join(toplevel_build, "obj", "gen"), os.path.join(toplevel_build, "gen"), ] GenerateCdtSettingsFile( target_list, target_dicts, data, params, config_name, os.path.join(toplevel_build, "eclipse-cdt-settings.xml"), options, shared_intermediate_dirs, ) GenerateClasspathFile( target_list, target_dicts, options.toplevel_dir, toplevel_build, os.path.join(toplevel_build, "eclipse-classpath.xml"), ) def GenerateCdtSettingsFile( target_list, target_dicts, data, params, config_name, out_name, options, shared_intermediate_dirs, ): gyp.common.EnsureDirExists(out_name) with open(out_name, "w") as out: out.write('\n') out.write("\n") eclipse_langs = [ "C++ Source File", "C Source File", "Assembly Source File", "GNU C++", "GNU C", "Assembly", ] compiler_path = GetCompilerPath(target_list, data, options) include_dirs = GetAllIncludeDirectories( target_list, target_dicts, shared_intermediate_dirs, config_name, params, compiler_path, ) WriteIncludePaths(out, eclipse_langs, include_dirs) defines = GetAllDefines( target_list, target_dicts, data, config_name, params, compiler_path ) WriteMacros(out, eclipse_langs, defines) out.write("\n") def GenerateClasspathFile( target_list, target_dicts, toplevel_dir, toplevel_build, out_name ): """Generates a classpath file suitable for symbol navigation and code completion of Java code (such as in Android projects) by finding all .java and .jar files used as action inputs.""" gyp.common.EnsureDirExists(out_name) result = ET.Element("classpath") def AddElements(kind, paths): # First, we need to normalize the paths so they are all relative to the # toplevel dir. rel_paths = set() for path in paths: if os.path.isabs(path): rel_paths.add(os.path.relpath(path, toplevel_dir)) else: rel_paths.add(path) for path in sorted(rel_paths): entry_element = ET.SubElement(result, "classpathentry") entry_element.set("kind", kind) entry_element.set("path", path) AddElements("lib", GetJavaJars(target_list, target_dicts, toplevel_dir)) AddElements("src", GetJavaSourceDirs(target_list, target_dicts, toplevel_dir)) # Include the standard JRE container and a dummy out folder AddElements("con", ["org.eclipse.jdt.launching.JRE_CONTAINER"]) # Include a dummy out folder so that Eclipse doesn't use the default /bin # folder in the root of the project. AddElements("output", [os.path.join(toplevel_build, ".eclipse-java-build")]) ET.ElementTree(result).write(out_name) def GetJavaJars(target_list, target_dicts, toplevel_dir): """Generates a sequence of all .jars used as inputs.""" for target_name in target_list: target = target_dicts[target_name] for action in target.get("actions", []): for input_ in action["inputs"]: if os.path.splitext(input_)[1] == ".jar" and not input_.startswith("$"): if os.path.isabs(input_): yield input_ else: yield os.path.join(os.path.dirname(target_name), input_) def GetJavaSourceDirs(target_list, target_dicts, toplevel_dir): """Generates a sequence of all likely java package root directories.""" for target_name in target_list: target = target_dicts[target_name] for action in target.get("actions", []): for input_ in action["inputs"]: if os.path.splitext(input_)[1] == ".java" and not input_.startswith( "$" ): dir_ = os.path.dirname( os.path.join(os.path.dirname(target_name), input_) ) # If there is a parent 'src' or 'java' folder, navigate up to it - # these are canonical package root names in Chromium. This will # break if 'src' or 'java' exists in the package structure. This # could be further improved by inspecting the java file for the # package name if this proves to be too fragile in practice. parent_search = dir_ while os.path.basename(parent_search) not in ["src", "java"]: parent_search, _ = os.path.split(parent_search) if not parent_search or parent_search == toplevel_dir: # Didn't find a known root, just return the original path yield dir_ break else: yield parent_search def GenerateOutput(target_list, target_dicts, data, params): """Generate an XML settings file that can be imported into a CDT project.""" if params["options"].generator_output: raise NotImplementedError("--generator_output not implemented for eclipse") user_config = params.get("generator_flags", {}).get("config", None) if user_config: GenerateOutputForConfig(target_list, target_dicts, data, params, user_config) else: config_names = target_dicts[target_list[0]]["configurations"] for config_name in config_names: GenerateOutputForConfig( target_list, target_dicts, data, params, config_name ) PK ~\,node-gyp/gyp/pylib/gyp/generator/__init__.pynu[PK ~\BlMlM(node-gyp/gyp/pylib/gyp/generator/msvs.pynu[# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import ntpath import os import posixpath import re import subprocess import sys from collections import OrderedDict import gyp.common import gyp.easy_xml as easy_xml import gyp.generator.ninja as ninja_generator import gyp.MSVSNew as MSVSNew import gyp.MSVSProject as MSVSProject import gyp.MSVSSettings as MSVSSettings import gyp.MSVSToolFile as MSVSToolFile import gyp.MSVSUserFile as MSVSUserFile import gyp.MSVSUtil as MSVSUtil import gyp.MSVSVersion as MSVSVersion from gyp.common import GypError from gyp.common import OrderedSet # Regular expression for validating Visual Studio GUIDs. If the GUID # contains lowercase hex letters, MSVS will be fine. However, # IncrediBuild BuildConsole will parse the solution file, but then # silently skip building the target causing hard to track down errors. # Note that this only happens with the BuildConsole, and does not occur # if IncrediBuild is executed from inside Visual Studio. This regex # validates that the string looks like a GUID with all uppercase hex # letters. VALID_MSVS_GUID_CHARS = re.compile(r"^[A-F0-9\-]+$") generator_supports_multiple_toolsets = gyp.common.CrossCompileRequested() generator_default_variables = { "DRIVER_PREFIX": "", "DRIVER_SUFFIX": ".sys", "EXECUTABLE_PREFIX": "", "EXECUTABLE_SUFFIX": ".exe", "STATIC_LIB_PREFIX": "", "SHARED_LIB_PREFIX": "", "STATIC_LIB_SUFFIX": ".lib", "SHARED_LIB_SUFFIX": ".dll", "INTERMEDIATE_DIR": "$(IntDir)", "SHARED_INTERMEDIATE_DIR": "$(OutDir)/obj/global_intermediate", "OS": "win", "PRODUCT_DIR": "$(OutDir)", "LIB_DIR": "$(OutDir)lib", "RULE_INPUT_ROOT": "$(InputName)", "RULE_INPUT_DIRNAME": "$(InputDir)", "RULE_INPUT_EXT": "$(InputExt)", "RULE_INPUT_NAME": "$(InputFileName)", "RULE_INPUT_PATH": "$(InputPath)", "CONFIGURATION_NAME": "$(ConfigurationName)", } # The msvs specific sections that hold paths generator_additional_path_sections = [ "msvs_cygwin_dirs", "msvs_props", ] generator_additional_non_configuration_keys = [ "msvs_cygwin_dirs", "msvs_cygwin_shell", "msvs_large_pdb", "msvs_shard", "msvs_external_builder", "msvs_external_builder_out_dir", "msvs_external_builder_build_cmd", "msvs_external_builder_clean_cmd", "msvs_external_builder_clcompile_cmd", "msvs_enable_winrt", "msvs_requires_importlibrary", "msvs_enable_winphone", "msvs_application_type_revision", "msvs_target_platform_version", "msvs_target_platform_minversion", ] generator_filelist_paths = None # List of precompiled header related keys. precomp_keys = [ "msvs_precompiled_header", "msvs_precompiled_source", ] cached_username = None cached_domain = None # TODO(gspencer): Switch the os.environ calls to be # win32api.GetDomainName() and win32api.GetUserName() once the # python version in depot_tools has been updated to work on Vista # 64-bit. def _GetDomainAndUserName(): if sys.platform not in ("win32", "cygwin"): return ("DOMAIN", "USERNAME") global cached_username global cached_domain if not cached_domain or not cached_username: domain = os.environ.get("USERDOMAIN") username = os.environ.get("USERNAME") if not domain or not username: call = subprocess.Popen( ["net", "config", "Workstation"], stdout=subprocess.PIPE ) config = call.communicate()[0].decode("utf-8") username_re = re.compile(r"^User name\s+(\S+)", re.MULTILINE) username_match = username_re.search(config) if username_match: username = username_match.group(1) domain_re = re.compile(r"^Logon domain\s+(\S+)", re.MULTILINE) domain_match = domain_re.search(config) if domain_match: domain = domain_match.group(1) cached_domain = domain cached_username = username return (cached_domain, cached_username) fixpath_prefix = None def _NormalizedSource(source): """Normalize the path. But not if that gets rid of a variable, as this may expand to something larger than one directory. Arguments: source: The path to be normalize.d Returns: The normalized path. """ normalized = os.path.normpath(source) if source.count("$") == normalized.count("$"): source = normalized return source def _FixPath(path, separator="\\"): """Convert paths to a form that will make sense in a vcproj file. Arguments: path: The path to convert, may contain / etc. Returns: The path with all slashes made into backslashes. """ if ( fixpath_prefix and path and not os.path.isabs(path) and path[0] != "$" and not _IsWindowsAbsPath(path) ): path = os.path.join(fixpath_prefix, path) if separator == "\\": path = path.replace("/", "\\") path = _NormalizedSource(path) if separator == "/": path = path.replace("\\", "/") if path and path[-1] == separator: path = path[:-1] return path def _IsWindowsAbsPath(path): """ On Cygwin systems Python needs a little help determining if a path is an absolute Windows path or not, so that it does not treat those as relative, which results in bad paths like: '..\\C:\\\\some_source_code_file.cc' """ return path.startswith("c:") or path.startswith("C:") def _FixPaths(paths, separator="\\"): """Fix each of the paths of the list.""" return [_FixPath(i, separator) for i in paths] def _ConvertSourcesToFilterHierarchy( sources, prefix=None, excluded=None, list_excluded=True, msvs_version=None ): """Converts a list split source file paths into a vcproj folder hierarchy. Arguments: sources: A list of source file paths split. prefix: A list of source file path layers meant to apply to each of sources. excluded: A set of excluded files. msvs_version: A MSVSVersion object. Returns: A hierarchy of filenames and MSVSProject.Filter objects that matches the layout of the source tree. For example: _ConvertSourcesToFilterHierarchy([['a', 'bob1.c'], ['b', 'bob2.c']], prefix=['joe']) --> [MSVSProject.Filter('a', contents=['joe\\a\\bob1.c']), MSVSProject.Filter('b', contents=['joe\\b\\bob2.c'])] """ if not prefix: prefix = [] result = [] excluded_result = [] folders = OrderedDict() # Gather files into the final result, excluded, or folders. for s in sources: if len(s) == 1: filename = _NormalizedSource("\\".join(prefix + s)) if filename in excluded: excluded_result.append(filename) else: result.append(filename) elif msvs_version and not msvs_version.UsesVcxproj(): # For MSVS 2008 and earlier, we need to process all files before walking # the sub folders. if not folders.get(s[0]): folders[s[0]] = [] folders[s[0]].append(s[1:]) else: contents = _ConvertSourcesToFilterHierarchy( [s[1:]], prefix + [s[0]], excluded=excluded, list_excluded=list_excluded, msvs_version=msvs_version, ) contents = MSVSProject.Filter(s[0], contents=contents) result.append(contents) # Add a folder for excluded files. if excluded_result and list_excluded: excluded_folder = MSVSProject.Filter( "_excluded_files", contents=excluded_result ) result.append(excluded_folder) if msvs_version and msvs_version.UsesVcxproj(): return result # Populate all the folders. for f in folders: contents = _ConvertSourcesToFilterHierarchy( folders[f], prefix=prefix + [f], excluded=excluded, list_excluded=list_excluded, msvs_version=msvs_version, ) contents = MSVSProject.Filter(f, contents=contents) result.append(contents) return result def _ToolAppend(tools, tool_name, setting, value, only_if_unset=False): if not value: return _ToolSetOrAppend(tools, tool_name, setting, value, only_if_unset) def _ToolSetOrAppend(tools, tool_name, setting, value, only_if_unset=False): # TODO(bradnelson): ugly hack, fix this more generally!!! if "Directories" in setting or "Dependencies" in setting: if type(value) == str: value = value.replace("/", "\\") else: value = [i.replace("/", "\\") for i in value] if not tools.get(tool_name): tools[tool_name] = {} tool = tools[tool_name] if setting == "CompileAsWinRT": return if tool.get(setting): if only_if_unset: return if type(tool[setting]) == list and type(value) == list: tool[setting] += value else: raise TypeError( 'Appending "%s" to a non-list setting "%s" for tool "%s" is ' "not allowed, previous value: %s" % (value, setting, tool_name, str(tool[setting])) ) else: tool[setting] = value def _ConfigTargetVersion(config_data): return config_data.get("msvs_target_version", "Windows7") def _ConfigPlatform(config_data): return config_data.get("msvs_configuration_platform", "Win32") def _ConfigBaseName(config_name, platform_name): if config_name.endswith("_" + platform_name): return config_name[0 : -len(platform_name) - 1] else: return config_name def _ConfigFullName(config_name, config_data): platform_name = _ConfigPlatform(config_data) return f"{_ConfigBaseName(config_name, platform_name)}|{platform_name}" def _ConfigWindowsTargetPlatformVersion(config_data, version): target_ver = config_data.get("msvs_windows_target_platform_version") if target_ver and re.match(r"^\d+", target_ver): return target_ver config_ver = config_data.get("msvs_windows_sdk_version") vers = [config_ver] if config_ver else version.compatible_sdks for ver in vers: for key in [ r"HKLM\Software\Microsoft\Microsoft SDKs\Windows\%s", r"HKLM\Software\Wow6432Node\Microsoft\Microsoft SDKs\Windows\%s", ]: sdk_dir = MSVSVersion._RegistryGetValue(key % ver, "InstallationFolder") if not sdk_dir: continue version = MSVSVersion._RegistryGetValue(key % ver, "ProductVersion") or "" # Find a matching entry in sdk_dir\include. expected_sdk_dir = r"%s\include" % sdk_dir names = sorted( ( x for x in ( os.listdir(expected_sdk_dir) if os.path.isdir(expected_sdk_dir) else [] ) if x.startswith(version) ), reverse=True, ) if names: return names[0] else: print( "Warning: No include files found for detected " "Windows SDK version %s" % (version), file=sys.stdout, ) def _BuildCommandLineForRuleRaw( spec, cmd, cygwin_shell, has_input_path, quote_cmd, do_setup_env ): if [x for x in cmd if "$(InputDir)" in x]: input_dir_preamble = ( "set INPUTDIR=$(InputDir)\n" "if NOT DEFINED INPUTDIR set INPUTDIR=.\\\n" "set INPUTDIR=%INPUTDIR:~0,-1%\n" ) else: input_dir_preamble = "" if cygwin_shell: # Find path to cygwin. cygwin_dir = _FixPath(spec.get("msvs_cygwin_dirs", ["."])[0]) # Prepare command. direct_cmd = cmd direct_cmd = [ i.replace("$(IntDir)", '`cygpath -m "${INTDIR}"`') for i in direct_cmd ] direct_cmd = [ i.replace("$(OutDir)", '`cygpath -m "${OUTDIR}"`') for i in direct_cmd ] direct_cmd = [ i.replace("$(InputDir)", '`cygpath -m "${INPUTDIR}"`') for i in direct_cmd ] if has_input_path: direct_cmd = [ i.replace("$(InputPath)", '`cygpath -m "${INPUTPATH}"`') for i in direct_cmd ] direct_cmd = ['\\"%s\\"' % i.replace('"', '\\\\\\"') for i in direct_cmd] # direct_cmd = gyp.common.EncodePOSIXShellList(direct_cmd) direct_cmd = " ".join(direct_cmd) # TODO(quote): regularize quoting path names throughout the module cmd = "" if do_setup_env: cmd += 'call "$(ProjectDir)%(cygwin_dir)s\\setup_env.bat" && ' cmd += "set CYGWIN=nontsec&& " if direct_cmd.find("NUMBER_OF_PROCESSORS") >= 0: cmd += "set /a NUMBER_OF_PROCESSORS_PLUS_1=%%NUMBER_OF_PROCESSORS%%+1&& " if direct_cmd.find("INTDIR") >= 0: cmd += "set INTDIR=$(IntDir)&& " if direct_cmd.find("OUTDIR") >= 0: cmd += "set OUTDIR=$(OutDir)&& " if has_input_path and direct_cmd.find("INPUTPATH") >= 0: cmd += "set INPUTPATH=$(InputPath) && " cmd += 'bash -c "%(cmd)s"' cmd = cmd % {"cygwin_dir": cygwin_dir, "cmd": direct_cmd} return input_dir_preamble + cmd else: # Convert cat --> type to mimic unix. command = ["type"] if cmd[0] == "cat" else [cmd[0].replace("/", "\\")] # Add call before command to ensure that commands can be tied together one # after the other without aborting in Incredibuild, since IB makes a bat # file out of the raw command string, and some commands (like python) are # actually batch files themselves. command.insert(0, "call") # Fix the paths # TODO(quote): This is a really ugly heuristic, and will miss path fixing # for arguments like "--arg=path", arg=path, or "/opt:path". # If the argument starts with a slash or dash, or contains an equal sign, # it's probably a command line switch. # Return the path with forward slashes because the command using it might # not support backslashes. arguments = [ i if (i[:1] in "/-" or "=" in i) else _FixPath(i, "/") for i in cmd[1:] ] arguments = [i.replace("$(InputDir)", "%INPUTDIR%") for i in arguments] arguments = [MSVSSettings.FixVCMacroSlashes(i) for i in arguments] if quote_cmd: # Support a mode for using cmd directly. # Convert any paths to native form (first element is used directly). # TODO(quote): regularize quoting path names throughout the module command[1] = '"%s"' % command[1] arguments = ['"%s"' % i for i in arguments] # Collapse into a single command. return input_dir_preamble + " ".join(command + arguments) def _BuildCommandLineForRule(spec, rule, has_input_path, do_setup_env): # Currently this weird argument munging is used to duplicate the way a # python script would need to be run as part of the chrome tree. # Eventually we should add some sort of rule_default option to set this # per project. For now the behavior chrome needs is the default. mcs = rule.get("msvs_cygwin_shell") if mcs is None: mcs = int(spec.get("msvs_cygwin_shell", 1)) elif isinstance(mcs, str): mcs = int(mcs) quote_cmd = int(rule.get("msvs_quote_cmd", 1)) return _BuildCommandLineForRuleRaw( spec, rule["action"], mcs, has_input_path, quote_cmd, do_setup_env=do_setup_env ) def _AddActionStep(actions_dict, inputs, outputs, description, command): """Merge action into an existing list of actions. Care must be taken so that actions which have overlapping inputs either don't get assigned to the same input, or get collapsed into one. Arguments: actions_dict: dictionary keyed on input name, which maps to a list of dicts describing the actions attached to that input file. inputs: list of inputs outputs: list of outputs description: description of the action command: command line to execute """ # Require there to be at least one input (call sites will ensure this). assert inputs action = { "inputs": inputs, "outputs": outputs, "description": description, "command": command, } # Pick where to stick this action. # While less than optimal in terms of build time, attach them to the first # input for now. chosen_input = inputs[0] # Add it there. if chosen_input not in actions_dict: actions_dict[chosen_input] = [] actions_dict[chosen_input].append(action) def _AddCustomBuildToolForMSVS( p, spec, primary_input, inputs, outputs, description, cmd ): """Add a custom build tool to execute something. Arguments: p: the target project spec: the target project dict primary_input: input file to attach the build tool to inputs: list of inputs outputs: list of outputs description: description of the action cmd: command line to execute """ inputs = _FixPaths(inputs) outputs = _FixPaths(outputs) tool = MSVSProject.Tool( "VCCustomBuildTool", { "Description": description, "AdditionalDependencies": ";".join(inputs), "Outputs": ";".join(outputs), "CommandLine": cmd, }, ) # Add to the properties of primary input for each config. for config_name, c_data in spec["configurations"].items(): p.AddFileConfig( _FixPath(primary_input), _ConfigFullName(config_name, c_data), tools=[tool] ) def _AddAccumulatedActionsToMSVS(p, spec, actions_dict): """Add actions accumulated into an actions_dict, merging as needed. Arguments: p: the target project spec: the target project dict actions_dict: dictionary keyed on input name, which maps to a list of dicts describing the actions attached to that input file. """ for primary_input in actions_dict: inputs = OrderedSet() outputs = OrderedSet() descriptions = [] commands = [] for action in actions_dict[primary_input]: inputs.update(OrderedSet(action["inputs"])) outputs.update(OrderedSet(action["outputs"])) descriptions.append(action["description"]) commands.append(action["command"]) # Add the custom build step for one input file. description = ", and also ".join(descriptions) command = "\r\n".join(commands) _AddCustomBuildToolForMSVS( p, spec, primary_input=primary_input, inputs=inputs, outputs=outputs, description=description, cmd=command, ) def _RuleExpandPath(path, input_file): """Given the input file to which a rule applied, string substitute a path. Arguments: path: a path to string expand input_file: the file to which the rule applied. Returns: The string substituted path. """ path = path.replace( "$(InputName)", os.path.splitext(os.path.split(input_file)[1])[0] ) path = path.replace("$(InputDir)", os.path.dirname(input_file)) path = path.replace( "$(InputExt)", os.path.splitext(os.path.split(input_file)[1])[1] ) path = path.replace("$(InputFileName)", os.path.split(input_file)[1]) path = path.replace("$(InputPath)", input_file) return path def _FindRuleTriggerFiles(rule, sources): """Find the list of files which a particular rule applies to. Arguments: rule: the rule in question sources: the set of all known source files for this project Returns: The list of sources that trigger a particular rule. """ return rule.get("rule_sources", []) def _RuleInputsAndOutputs(rule, trigger_file): """Find the inputs and outputs generated by a rule. Arguments: rule: the rule in question. trigger_file: the main trigger for this rule. Returns: The pair of (inputs, outputs) involved in this rule. """ raw_inputs = _FixPaths(rule.get("inputs", [])) raw_outputs = _FixPaths(rule.get("outputs", [])) inputs = OrderedSet() outputs = OrderedSet() inputs.add(trigger_file) for i in raw_inputs: inputs.add(_RuleExpandPath(i, trigger_file)) for o in raw_outputs: outputs.add(_RuleExpandPath(o, trigger_file)) return (inputs, outputs) def _GenerateNativeRulesForMSVS(p, rules, output_dir, spec, options): """Generate a native rules file. Arguments: p: the target project rules: the set of rules to include output_dir: the directory in which the project/gyp resides spec: the project dict options: global generator options """ rules_filename = "{}{}.rules".format(spec["target_name"], options.suffix) rules_file = MSVSToolFile.Writer( os.path.join(output_dir, rules_filename), spec["target_name"] ) # Add each rule. for r in rules: rule_name = r["rule_name"] rule_ext = r["extension"] inputs = _FixPaths(r.get("inputs", [])) outputs = _FixPaths(r.get("outputs", [])) # Skip a rule with no action and no inputs. if "action" not in r and not r.get("rule_sources", []): continue cmd = _BuildCommandLineForRule(spec, r, has_input_path=True, do_setup_env=True) rules_file.AddCustomBuildRule( name=rule_name, description=r.get("message", rule_name), extensions=[rule_ext], additional_dependencies=inputs, outputs=outputs, cmd=cmd, ) # Write out rules file. rules_file.WriteIfChanged() # Add rules file to project. p.AddToolFile(rules_filename) def _Cygwinify(path): path = path.replace("$(OutDir)", "$(OutDirCygwin)") path = path.replace("$(IntDir)", "$(IntDirCygwin)") return path def _GenerateExternalRules(rules, output_dir, spec, sources, options, actions_to_add): """Generate an external makefile to do a set of rules. Arguments: rules: the list of rules to include output_dir: path containing project and gyp files spec: project specification data sources: set of sources known options: global generator options actions_to_add: The list of actions we will add to. """ filename = "{}_rules{}.mk".format(spec["target_name"], options.suffix) mk_file = gyp.common.WriteOnDiff(os.path.join(output_dir, filename)) # Find cygwin style versions of some paths. mk_file.write('OutDirCygwin:=$(shell cygpath -u "$(OutDir)")\n') mk_file.write('IntDirCygwin:=$(shell cygpath -u "$(IntDir)")\n') # Gather stuff needed to emit all: target. all_inputs = OrderedSet() all_outputs = OrderedSet() all_output_dirs = OrderedSet() first_outputs = [] for rule in rules: trigger_files = _FindRuleTriggerFiles(rule, sources) for tf in trigger_files: inputs, outputs = _RuleInputsAndOutputs(rule, tf) all_inputs.update(OrderedSet(inputs)) all_outputs.update(OrderedSet(outputs)) # Only use one target from each rule as the dependency for # 'all' so we don't try to build each rule multiple times. first_outputs.append(next(iter(outputs))) # Get the unique output directories for this rule. output_dirs = [os.path.split(i)[0] for i in outputs] for od in output_dirs: all_output_dirs.add(od) first_outputs_cyg = [_Cygwinify(i) for i in first_outputs] # Write out all: target, including mkdir for each output directory. mk_file.write("all: %s\n" % " ".join(first_outputs_cyg)) for od in all_output_dirs: if od: mk_file.write('\tmkdir -p `cygpath -u "%s"`\n' % od) mk_file.write("\n") # Define how each output is generated. for rule in rules: trigger_files = _FindRuleTriggerFiles(rule, sources) for tf in trigger_files: # Get all the inputs and outputs for this rule for this trigger file. inputs, outputs = _RuleInputsAndOutputs(rule, tf) inputs = [_Cygwinify(i) for i in inputs] outputs = [_Cygwinify(i) for i in outputs] # Prepare the command line for this rule. cmd = [_RuleExpandPath(c, tf) for c in rule["action"]] cmd = ['"%s"' % i for i in cmd] cmd = " ".join(cmd) # Add it to the makefile. mk_file.write("{}: {}\n".format(" ".join(outputs), " ".join(inputs))) mk_file.write("\t%s\n\n" % cmd) # Close up the file. mk_file.close() # Add makefile to list of sources. sources.add(filename) # Add a build action to call makefile. cmd = [ "make", "OutDir=$(OutDir)", "IntDir=$(IntDir)", "-j", "${NUMBER_OF_PROCESSORS_PLUS_1}", "-f", filename, ] cmd = _BuildCommandLineForRuleRaw(spec, cmd, True, False, True, True) # Insert makefile as 0'th input, so it gets the action attached there, # as this is easier to understand from in the IDE. all_inputs = list(all_inputs) all_inputs.insert(0, filename) _AddActionStep( actions_to_add, inputs=_FixPaths(all_inputs), outputs=_FixPaths(all_outputs), description="Running external rules for %s" % spec["target_name"], command=cmd, ) def _EscapeEnvironmentVariableExpansion(s): """Escapes % characters. Escapes any % characters so that Windows-style environment variable expansions will leave them alone. See http://connect.microsoft.com/VisualStudio/feedback/details/106127/cl-d-name-text-containing-percentage-characters-doesnt-compile to understand why we have to do this. Args: s: The string to be escaped. Returns: The escaped string. """ s = s.replace("%", "%%") return s quote_replacer_regex = re.compile(r'(\\*)"') def _EscapeCommandLineArgumentForMSVS(s): """Escapes a Windows command-line argument. So that the Win32 CommandLineToArgv function will turn the escaped result back into the original string. See http://msdn.microsoft.com/en-us/library/17w5ykft.aspx ("Parsing C++ Command-Line Arguments") to understand why we have to do this. Args: s: the string to be escaped. Returns: the escaped string. """ def _Replace(match): # For a literal quote, CommandLineToArgv requires an odd number of # backslashes preceding it, and it produces half as many literal backslashes # (rounded down). So we need to produce 2n+1 backslashes. return 2 * match.group(1) + '\\"' # Escape all quotes so that they are interpreted literally. s = quote_replacer_regex.sub(_Replace, s) # Now add unescaped quotes so that any whitespace is interpreted literally. s = '"' + s + '"' return s delimiters_replacer_regex = re.compile(r"(\\*)([,;]+)") def _EscapeVCProjCommandLineArgListItem(s): """Escapes command line arguments for MSVS. The VCProj format stores string lists in a single string using commas and semi-colons as separators, which must be quoted if they are to be interpreted literally. However, command-line arguments may already have quotes, and the VCProj parser is ignorant of the backslash escaping convention used by CommandLineToArgv, so the command-line quotes and the VCProj quotes may not be the same quotes. So to store a general command-line argument in a VCProj list, we need to parse the existing quoting according to VCProj's convention and quote any delimiters that are not already quoted by that convention. The quotes that we add will also be seen by CommandLineToArgv, so if backslashes precede them then we also have to escape those backslashes according to the CommandLineToArgv convention. Args: s: the string to be escaped. Returns: the escaped string. """ def _Replace(match): # For a non-literal quote, CommandLineToArgv requires an even number of # backslashes preceding it, and it produces half as many literal # backslashes. So we need to produce 2n backslashes. return 2 * match.group(1) + '"' + match.group(2) + '"' segments = s.split('"') # The unquoted segments are at the even-numbered indices. for i in range(0, len(segments), 2): segments[i] = delimiters_replacer_regex.sub(_Replace, segments[i]) # Concatenate back into a single string s = '"'.join(segments) if len(segments) % 2 == 0: # String ends while still quoted according to VCProj's convention. This # means the delimiter and the next list item that follow this one in the # .vcproj file will be misinterpreted as part of this item. There is nothing # we can do about this. Adding an extra quote would correct the problem in # the VCProj but cause the same problem on the final command-line. Moving # the item to the end of the list does works, but that's only possible if # there's only one such item. Let's just warn the user. print( "Warning: MSVS may misinterpret the odd number of " + "quotes in " + s, file=sys.stderr, ) return s def _EscapeCppDefineForMSVS(s): """Escapes a CPP define so that it will reach the compiler unaltered.""" s = _EscapeEnvironmentVariableExpansion(s) s = _EscapeCommandLineArgumentForMSVS(s) s = _EscapeVCProjCommandLineArgListItem(s) # cl.exe replaces literal # characters with = in preprocessor definitions for # some reason. Octal-encode to work around that. s = s.replace("#", "\\%03o" % ord("#")) return s quote_replacer_regex2 = re.compile(r'(\\+)"') def _EscapeCommandLineArgumentForMSBuild(s): """Escapes a Windows command-line argument for use by MSBuild.""" def _Replace(match): return (len(match.group(1)) / 2 * 4) * "\\" + '\\"' # Escape all quotes so that they are interpreted literally. s = quote_replacer_regex2.sub(_Replace, s) return s def _EscapeMSBuildSpecialCharacters(s): escape_dictionary = { "%": "%25", "$": "%24", "@": "%40", "'": "%27", ";": "%3B", "?": "%3F", "*": "%2A", } result = "".join([escape_dictionary.get(c, c) for c in s]) return result def _EscapeCppDefineForMSBuild(s): """Escapes a CPP define so that it will reach the compiler unaltered.""" s = _EscapeEnvironmentVariableExpansion(s) s = _EscapeCommandLineArgumentForMSBuild(s) s = _EscapeMSBuildSpecialCharacters(s) # cl.exe replaces literal # characters with = in preprocessor definitions for # some reason. Octal-encode to work around that. s = s.replace("#", "\\%03o" % ord("#")) return s def _GenerateRulesForMSVS( p, output_dir, options, spec, sources, excluded_sources, actions_to_add ): """Generate all the rules for a particular project. Arguments: p: the project output_dir: directory to emit rules to options: global options passed to the generator spec: the specification for this project sources: the set of all known source files in this project excluded_sources: the set of sources excluded from normal processing actions_to_add: deferred list of actions to add in """ rules = spec.get("rules", []) rules_native = [r for r in rules if not int(r.get("msvs_external_rule", 0))] rules_external = [r for r in rules if int(r.get("msvs_external_rule", 0))] # Handle rules that use a native rules file. if rules_native: _GenerateNativeRulesForMSVS(p, rules_native, output_dir, spec, options) # Handle external rules (non-native rules). if rules_external: _GenerateExternalRules( rules_external, output_dir, spec, sources, options, actions_to_add ) _AdjustSourcesForRules(rules, sources, excluded_sources, False) def _AdjustSourcesForRules(rules, sources, excluded_sources, is_msbuild): # Add outputs generated by each rule (if applicable). for rule in rules: # Add in the outputs from this rule. trigger_files = _FindRuleTriggerFiles(rule, sources) for trigger_file in trigger_files: # Remove trigger_file from excluded_sources to let the rule be triggered # (e.g. rule trigger ax_enums.idl is added to excluded_sources # because it's also in an action's inputs in the same project) excluded_sources.discard(_FixPath(trigger_file)) # Done if not processing outputs as sources. if int(rule.get("process_outputs_as_sources", False)): inputs, outputs = _RuleInputsAndOutputs(rule, trigger_file) inputs = OrderedSet(_FixPaths(inputs)) outputs = OrderedSet(_FixPaths(outputs)) inputs.remove(_FixPath(trigger_file)) sources.update(inputs) if not is_msbuild: excluded_sources.update(inputs) sources.update(outputs) def _FilterActionsFromExcluded(excluded_sources, actions_to_add): """Take inputs with actions attached out of the list of exclusions. Arguments: excluded_sources: list of source files not to be built. actions_to_add: dict of actions keyed on source file they're attached to. Returns: excluded_sources with files that have actions attached removed. """ must_keep = OrderedSet(_FixPaths(actions_to_add.keys())) return [s for s in excluded_sources if s not in must_keep] def _GetDefaultConfiguration(spec): return spec["configurations"][spec["default_configuration"]] def _GetGuidOfProject(proj_path, spec): """Get the guid for the project. Arguments: proj_path: Path of the vcproj or vcxproj file to generate. spec: The target dictionary containing the properties of the target. Returns: the guid. Raises: ValueError: if the specified GUID is invalid. """ # Pluck out the default configuration. default_config = _GetDefaultConfiguration(spec) # Decide the guid of the project. guid = default_config.get("msvs_guid") if guid: if VALID_MSVS_GUID_CHARS.match(guid) is None: raise ValueError( 'Invalid MSVS guid: "%s". Must match regex: "%s".' % (guid, VALID_MSVS_GUID_CHARS.pattern) ) guid = "{%s}" % guid guid = guid or MSVSNew.MakeGuid(proj_path) return guid def _GetMsbuildToolsetOfProject(proj_path, spec, version): """Get the platform toolset for the project. Arguments: proj_path: Path of the vcproj or vcxproj file to generate. spec: The target dictionary containing the properties of the target. version: The MSVSVersion object. Returns: the platform toolset string or None. """ # Pluck out the default configuration. default_config = _GetDefaultConfiguration(spec) toolset = default_config.get("msbuild_toolset") if not toolset and version.DefaultToolset(): toolset = version.DefaultToolset() if spec["type"] == "windows_driver": toolset = "WindowsKernelModeDriver10.0" return toolset def _GenerateProject(project, options, version, generator_flags, spec): """Generates a vcproj file. Arguments: project: the MSVSProject object. options: global generator options. version: the MSVSVersion object. generator_flags: dict of generator-specific flags. Returns: A list of source files that cannot be found on disk. """ default_config = _GetDefaultConfiguration(project.spec) # Skip emitting anything if told to with msvs_existing_vcproj option. if default_config.get("msvs_existing_vcproj"): return [] if version.UsesVcxproj(): return _GenerateMSBuildProject(project, options, version, generator_flags, spec) else: return _GenerateMSVSProject(project, options, version, generator_flags) def _GenerateMSVSProject(project, options, version, generator_flags): """Generates a .vcproj file. It may create .rules and .user files too. Arguments: project: The project object we will generate the file for. options: Global options passed to the generator. version: The VisualStudioVersion object. generator_flags: dict of generator-specific flags. """ spec = project.spec gyp.common.EnsureDirExists(project.path) platforms = _GetUniquePlatforms(spec) p = MSVSProject.Writer( project.path, version, spec["target_name"], project.guid, platforms ) # Get directory project file is in. project_dir = os.path.split(project.path)[0] gyp_path = _NormalizedSource(project.build_file) relative_path_of_gyp_file = gyp.common.RelativePath(gyp_path, project_dir) config_type = _GetMSVSConfigurationType(spec, project.build_file) for config_name, config in spec["configurations"].items(): _AddConfigurationToMSVSProject(p, spec, config_type, config_name, config) # Prepare list of sources and excluded sources. gyp_file = os.path.split(project.build_file)[1] sources, excluded_sources = _PrepareListOfSources(spec, generator_flags, gyp_file) # Add rules. actions_to_add = {} _GenerateRulesForMSVS( p, project_dir, options, spec, sources, excluded_sources, actions_to_add ) list_excluded = generator_flags.get("msvs_list_excluded_files", True) sources, excluded_sources, excluded_idl = _AdjustSourcesAndConvertToFilterHierarchy( spec, options, project_dir, sources, excluded_sources, list_excluded, version ) # Add in files. missing_sources = _VerifySourcesExist(sources, project_dir) p.AddFiles(sources) _AddToolFilesToMSVS(p, spec) _HandlePreCompiledHeaders(p, sources, spec) _AddActions(actions_to_add, spec, relative_path_of_gyp_file) _AddCopies(actions_to_add, spec) _WriteMSVSUserFile(project.path, version, spec) # NOTE: this stanza must appear after all actions have been decided. # Don't excluded sources with actions attached, or they won't run. excluded_sources = _FilterActionsFromExcluded(excluded_sources, actions_to_add) _ExcludeFilesFromBeingBuilt(p, spec, excluded_sources, excluded_idl, list_excluded) _AddAccumulatedActionsToMSVS(p, spec, actions_to_add) # Write it out. p.WriteIfChanged() return missing_sources def _GetUniquePlatforms(spec): """Returns the list of unique platforms for this spec, e.g ['win32', ...]. Arguments: spec: The target dictionary containing the properties of the target. Returns: The MSVSUserFile object created. """ # Gather list of unique platforms. platforms = OrderedSet() for configuration in spec["configurations"]: platforms.add(_ConfigPlatform(spec["configurations"][configuration])) platforms = list(platforms) return platforms def _CreateMSVSUserFile(proj_path, version, spec): """Generates a .user file for the user running this Gyp program. Arguments: proj_path: The path of the project file being created. The .user file shares the same path (with an appropriate suffix). version: The VisualStudioVersion object. spec: The target dictionary containing the properties of the target. Returns: The MSVSUserFile object created. """ (domain, username) = _GetDomainAndUserName() vcuser_filename = ".".join([proj_path, domain, username, "user"]) user_file = MSVSUserFile.Writer(vcuser_filename, version, spec["target_name"]) return user_file def _GetMSVSConfigurationType(spec, build_file): """Returns the configuration type for this project. It's a number defined by Microsoft. May raise an exception. Args: spec: The target dictionary containing the properties of the target. build_file: The path of the gyp file. Returns: An integer, the configuration type. """ try: config_type = { "executable": "1", # .exe "shared_library": "2", # .dll "loadable_module": "2", # .dll "static_library": "4", # .lib "windows_driver": "5", # .sys "none": "10", # Utility type }[spec["type"]] except KeyError: if spec.get("type"): raise GypError( "Target type %s is not a valid target type for " "target %s in %s." % (spec["type"], spec["target_name"], build_file) ) else: raise GypError( "Missing type field for target %s in %s." % (spec["target_name"], build_file) ) return config_type def _AddConfigurationToMSVSProject(p, spec, config_type, config_name, config): """Adds a configuration to the MSVS project. Many settings in a vcproj file are specific to a configuration. This function the main part of the vcproj file that's configuration specific. Arguments: p: The target project being generated. spec: The target dictionary containing the properties of the target. config_type: The configuration type, a number as defined by Microsoft. config_name: The name of the configuration. config: The dictionary that defines the special processing to be done for this configuration. """ # Get the information for this configuration include_dirs, midl_include_dirs, resource_include_dirs = _GetIncludeDirs(config) libraries = _GetLibraries(spec) library_dirs = _GetLibraryDirs(config) out_file, vc_tool, _ = _GetOutputFilePathAndTool(spec, msbuild=False) defines = _GetDefines(config) defines = [_EscapeCppDefineForMSVS(d) for d in defines] disabled_warnings = _GetDisabledWarnings(config) prebuild = config.get("msvs_prebuild") postbuild = config.get("msvs_postbuild") def_file = _GetModuleDefinition(spec) precompiled_header = config.get("msvs_precompiled_header") # Prepare the list of tools as a dictionary. tools = {} # Add in user specified msvs_settings. msvs_settings = config.get("msvs_settings", {}) MSVSSettings.ValidateMSVSSettings(msvs_settings) # Prevent default library inheritance from the environment. _ToolAppend(tools, "VCLinkerTool", "AdditionalDependencies", ["$(NOINHERIT)"]) for tool in msvs_settings: settings = config["msvs_settings"][tool] for setting in settings: _ToolAppend(tools, tool, setting, settings[setting]) # Add the information to the appropriate tool _ToolAppend(tools, "VCCLCompilerTool", "AdditionalIncludeDirectories", include_dirs) _ToolAppend(tools, "VCMIDLTool", "AdditionalIncludeDirectories", midl_include_dirs) _ToolAppend( tools, "VCResourceCompilerTool", "AdditionalIncludeDirectories", resource_include_dirs, ) # Add in libraries. _ToolAppend(tools, "VCLinkerTool", "AdditionalDependencies", libraries) _ToolAppend(tools, "VCLinkerTool", "AdditionalLibraryDirectories", library_dirs) if out_file: _ToolAppend(tools, vc_tool, "OutputFile", out_file, only_if_unset=True) # Add defines. _ToolAppend(tools, "VCCLCompilerTool", "PreprocessorDefinitions", defines) _ToolAppend(tools, "VCResourceCompilerTool", "PreprocessorDefinitions", defines) # Change program database directory to prevent collisions. _ToolAppend( tools, "VCCLCompilerTool", "ProgramDataBaseFileName", "$(IntDir)$(ProjectName)\\vc80.pdb", only_if_unset=True, ) # Add disabled warnings. _ToolAppend(tools, "VCCLCompilerTool", "DisableSpecificWarnings", disabled_warnings) # Add Pre-build. _ToolAppend(tools, "VCPreBuildEventTool", "CommandLine", prebuild) # Add Post-build. _ToolAppend(tools, "VCPostBuildEventTool", "CommandLine", postbuild) # Turn on precompiled headers if appropriate. if precompiled_header: precompiled_header = os.path.split(precompiled_header)[1] _ToolAppend(tools, "VCCLCompilerTool", "UsePrecompiledHeader", "2") _ToolAppend( tools, "VCCLCompilerTool", "PrecompiledHeaderThrough", precompiled_header ) _ToolAppend(tools, "VCCLCompilerTool", "ForcedIncludeFiles", precompiled_header) # Loadable modules don't generate import libraries; # tell dependent projects to not expect one. if spec["type"] == "loadable_module": _ToolAppend(tools, "VCLinkerTool", "IgnoreImportLibrary", "true") # Set the module definition file if any. if def_file: _ToolAppend(tools, "VCLinkerTool", "ModuleDefinitionFile", def_file) _AddConfigurationToMSVS(p, spec, tools, config, config_type, config_name) def _GetIncludeDirs(config): """Returns the list of directories to be used for #include directives. Arguments: config: The dictionary that defines the special processing to be done for this configuration. Returns: The list of directory paths. """ # TODO(bradnelson): include_dirs should really be flexible enough not to # require this sort of thing. include_dirs = config.get("include_dirs", []) + config.get( "msvs_system_include_dirs", [] ) midl_include_dirs = config.get("midl_include_dirs", []) + config.get( "msvs_system_include_dirs", [] ) resource_include_dirs = config.get("resource_include_dirs", include_dirs) include_dirs = _FixPaths(include_dirs) midl_include_dirs = _FixPaths(midl_include_dirs) resource_include_dirs = _FixPaths(resource_include_dirs) return include_dirs, midl_include_dirs, resource_include_dirs def _GetLibraryDirs(config): """Returns the list of directories to be used for library search paths. Arguments: config: The dictionary that defines the special processing to be done for this configuration. Returns: The list of directory paths. """ library_dirs = config.get("library_dirs", []) library_dirs = _FixPaths(library_dirs) return library_dirs def _GetLibraries(spec): """Returns the list of libraries for this configuration. Arguments: spec: The target dictionary containing the properties of the target. Returns: The list of directory paths. """ libraries = spec.get("libraries", []) # Strip out -l, as it is not used on windows (but is needed so we can pass # in libraries that are assumed to be in the default library path). # Also remove duplicate entries, leaving only the last duplicate, while # preserving order. found = OrderedSet() unique_libraries_list = [] for entry in reversed(libraries): library = re.sub(r"^\-l", "", entry) if not os.path.splitext(library)[1]: library += ".lib" if library not in found: found.add(library) unique_libraries_list.append(library) unique_libraries_list.reverse() return unique_libraries_list def _GetOutputFilePathAndTool(spec, msbuild): """Returns the path and tool to use for this target. Figures out the path of the file this spec will create and the name of the VC tool that will create it. Arguments: spec: The target dictionary containing the properties of the target. Returns: A triple of (file path, name of the vc tool, name of the msbuild tool) """ # Select a name for the output file. out_file = "" vc_tool = "" msbuild_tool = "" output_file_map = { "executable": ("VCLinkerTool", "Link", "$(OutDir)", ".exe"), "shared_library": ("VCLinkerTool", "Link", "$(OutDir)", ".dll"), "loadable_module": ("VCLinkerTool", "Link", "$(OutDir)", ".dll"), "windows_driver": ("VCLinkerTool", "Link", "$(OutDir)", ".sys"), "static_library": ("VCLibrarianTool", "Lib", "$(OutDir)lib\\", ".lib"), } output_file_props = output_file_map.get(spec["type"]) if output_file_props and int(spec.get("msvs_auto_output_file", 1)): vc_tool, msbuild_tool, out_dir, suffix = output_file_props if spec.get("standalone_static_library", 0): out_dir = "$(OutDir)" out_dir = spec.get("product_dir", out_dir) product_extension = spec.get("product_extension") if product_extension: suffix = "." + product_extension elif msbuild: suffix = "$(TargetExt)" prefix = spec.get("product_prefix", "") product_name = spec.get("product_name", "$(ProjectName)") out_file = ntpath.join(out_dir, prefix + product_name + suffix) return out_file, vc_tool, msbuild_tool def _GetOutputTargetExt(spec): """Returns the extension for this target, including the dot If product_extension is specified, set target_extension to this to avoid MSB8012, returns None otherwise. Ignores any target_extension settings in the input files. Arguments: spec: The target dictionary containing the properties of the target. Returns: A string with the extension, or None """ target_extension = spec.get("product_extension") if target_extension: return "." + target_extension return None def _GetDefines(config): """Returns the list of preprocessor definitions for this configuration. Arguments: config: The dictionary that defines the special processing to be done for this configuration. Returns: The list of preprocessor definitions. """ defines = [] for d in config.get("defines", []): fd = "=".join([str(dpart) for dpart in d]) if isinstance(d, list) else str(d) defines.append(fd) return defines def _GetDisabledWarnings(config): return [str(i) for i in config.get("msvs_disabled_warnings", [])] def _GetModuleDefinition(spec): def_file = "" if spec["type"] in [ "shared_library", "loadable_module", "executable", "windows_driver", ]: def_files = [s for s in spec.get("sources", []) if s.endswith(".def")] if len(def_files) == 1: def_file = _FixPath(def_files[0]) elif def_files: raise ValueError( "Multiple module definition files in one target, target %s lists " "multiple .def files: %s" % (spec["target_name"], " ".join(def_files)) ) return def_file def _ConvertToolsToExpectedForm(tools): """Convert tools to a form expected by Visual Studio. Arguments: tools: A dictionary of settings; the tool name is the key. Returns: A list of Tool objects. """ tool_list = [] for tool, settings in tools.items(): # Collapse settings with lists. settings_fixed = {} for setting, value in settings.items(): if type(value) == list: if ( tool == "VCLinkerTool" and setting == "AdditionalDependencies" ) or setting == "AdditionalOptions": settings_fixed[setting] = " ".join(value) else: settings_fixed[setting] = ";".join(value) else: settings_fixed[setting] = value # Add in this tool. tool_list.append(MSVSProject.Tool(tool, settings_fixed)) return tool_list def _AddConfigurationToMSVS(p, spec, tools, config, config_type, config_name): """Add to the project file the configuration specified by config. Arguments: p: The target project being generated. spec: the target project dict. tools: A dictionary of settings; the tool name is the key. config: The dictionary that defines the special processing to be done for this configuration. config_type: The configuration type, a number as defined by Microsoft. config_name: The name of the configuration. """ attributes = _GetMSVSAttributes(spec, config, config_type) # Add in this configuration. tool_list = _ConvertToolsToExpectedForm(tools) p.AddConfig(_ConfigFullName(config_name, config), attrs=attributes, tools=tool_list) def _GetMSVSAttributes(spec, config, config_type): # Prepare configuration attributes. prepared_attrs = {} source_attrs = config.get("msvs_configuration_attributes", {}) for a in source_attrs: prepared_attrs[a] = source_attrs[a] # Add props files. vsprops_dirs = config.get("msvs_props", []) vsprops_dirs = _FixPaths(vsprops_dirs) if vsprops_dirs: prepared_attrs["InheritedPropertySheets"] = ";".join(vsprops_dirs) # Set configuration type. prepared_attrs["ConfigurationType"] = config_type output_dir = prepared_attrs.get( "OutputDirectory", "$(SolutionDir)$(ConfigurationName)" ) prepared_attrs["OutputDirectory"] = _FixPath(output_dir) + "\\" if "IntermediateDirectory" not in prepared_attrs: intermediate = "$(ConfigurationName)\\obj\\$(ProjectName)" prepared_attrs["IntermediateDirectory"] = _FixPath(intermediate) + "\\" else: intermediate = _FixPath(prepared_attrs["IntermediateDirectory"]) + "\\" intermediate = MSVSSettings.FixVCMacroSlashes(intermediate) prepared_attrs["IntermediateDirectory"] = intermediate return prepared_attrs def _AddNormalizedSources(sources_set, sources_array): sources_set.update(_NormalizedSource(s) for s in sources_array) def _PrepareListOfSources(spec, generator_flags, gyp_file): """Prepare list of sources and excluded sources. Besides the sources specified directly in the spec, adds the gyp file so that a change to it will cause a re-compile. Also adds appropriate sources for actions and copies. Assumes later stage will un-exclude files which have custom build steps attached. Arguments: spec: The target dictionary containing the properties of the target. gyp_file: The name of the gyp file. Returns: A pair of (list of sources, list of excluded sources). The sources will be relative to the gyp file. """ sources = OrderedSet() _AddNormalizedSources(sources, spec.get("sources", [])) excluded_sources = OrderedSet() # Add in the gyp file. if not generator_flags.get("standalone"): sources.add(gyp_file) # Add in 'action' inputs and outputs. for a in spec.get("actions", []): inputs = a["inputs"] inputs = [_NormalizedSource(i) for i in inputs] # Add all inputs to sources and excluded sources. inputs = OrderedSet(inputs) sources.update(inputs) if not spec.get("msvs_external_builder"): excluded_sources.update(inputs) if int(a.get("process_outputs_as_sources", False)): _AddNormalizedSources(sources, a.get("outputs", [])) # Add in 'copies' inputs and outputs. for cpy in spec.get("copies", []): _AddNormalizedSources(sources, cpy.get("files", [])) return (sources, excluded_sources) def _AdjustSourcesAndConvertToFilterHierarchy( spec, options, gyp_dir, sources, excluded_sources, list_excluded, version ): """Adjusts the list of sources and excluded sources. Also converts the sets to lists. Arguments: spec: The target dictionary containing the properties of the target. options: Global generator options. gyp_dir: The path to the gyp file being processed. sources: A set of sources to be included for this project. excluded_sources: A set of sources to be excluded for this project. version: A MSVSVersion object. Returns: A trio of (list of sources, list of excluded sources, path of excluded IDL file) """ # Exclude excluded sources coming into the generator. excluded_sources.update(OrderedSet(spec.get("sources_excluded", []))) # Add excluded sources into sources for good measure. sources.update(excluded_sources) # Convert to proper windows form. # NOTE: sources goes from being a set to a list here. # NOTE: excluded_sources goes from being a set to a list here. sources = _FixPaths(sources) # Convert to proper windows form. excluded_sources = _FixPaths(excluded_sources) excluded_idl = _IdlFilesHandledNonNatively(spec, sources) precompiled_related = _GetPrecompileRelatedFiles(spec) # Find the excluded ones, minus the precompiled header related ones. fully_excluded = [i for i in excluded_sources if i not in precompiled_related] # Convert to folders and the right slashes. sources = [i.split("\\") for i in sources] sources = _ConvertSourcesToFilterHierarchy( sources, excluded=fully_excluded, list_excluded=list_excluded, msvs_version=version, ) # Prune filters with a single child to flatten ugly directory structures # such as ../../src/modules/module1 etc. if version.UsesVcxproj(): while ( all(isinstance(s, MSVSProject.Filter) for s in sources) and len({s.name for s in sources}) == 1 ): assert all(len(s.contents) == 1 for s in sources) sources = [s.contents[0] for s in sources] else: while len(sources) == 1 and isinstance(sources[0], MSVSProject.Filter): sources = sources[0].contents return sources, excluded_sources, excluded_idl def _IdlFilesHandledNonNatively(spec, sources): # If any non-native rules use 'idl' as an extension exclude idl files. # Gather a list here to use later. using_idl = False for rule in spec.get("rules", []): if rule["extension"] == "idl" and int(rule.get("msvs_external_rule", 0)): using_idl = True break excluded_idl = [i for i in sources if i.endswith(".idl")] if using_idl else [] return excluded_idl def _GetPrecompileRelatedFiles(spec): # Gather a list of precompiled header related sources. precompiled_related = [] for _, config in spec["configurations"].items(): for k in precomp_keys: f = config.get(k) if f: precompiled_related.append(_FixPath(f)) return precompiled_related def _ExcludeFilesFromBeingBuilt(p, spec, excluded_sources, excluded_idl, list_excluded): exclusions = _GetExcludedFilesFromBuild(spec, excluded_sources, excluded_idl) for file_name, excluded_configs in exclusions.items(): if not list_excluded and len(excluded_configs) == len(spec["configurations"]): # If we're not listing excluded files, then they won't appear in the # project, so don't try to configure them to be excluded. pass else: for config_name, config in excluded_configs: p.AddFileConfig( file_name, _ConfigFullName(config_name, config), {"ExcludedFromBuild": "true"}, ) def _GetExcludedFilesFromBuild(spec, excluded_sources, excluded_idl): exclusions = {} # Exclude excluded sources from being built. for f in excluded_sources: excluded_configs = [] for config_name, config in spec["configurations"].items(): precomped = [_FixPath(config.get(i, "")) for i in precomp_keys] # Don't do this for ones that are precompiled header related. if f not in precomped: excluded_configs.append((config_name, config)) exclusions[f] = excluded_configs # If any non-native rules use 'idl' as an extension exclude idl files. # Exclude them now. for f in excluded_idl: excluded_configs = [] for config_name, config in spec["configurations"].items(): excluded_configs.append((config_name, config)) exclusions[f] = excluded_configs return exclusions def _AddToolFilesToMSVS(p, spec): # Add in tool files (rules). tool_files = OrderedSet() for _, config in spec["configurations"].items(): for f in config.get("msvs_tool_files", []): tool_files.add(f) for f in tool_files: p.AddToolFile(f) def _HandlePreCompiledHeaders(p, sources, spec): # Pre-compiled header source stubs need a different compiler flag # (generate precompiled header) and any source file not of the same # kind (i.e. C vs. C++) as the precompiled header source stub needs # to have use of precompiled headers disabled. extensions_excluded_from_precompile = [] for config_name, config in spec["configurations"].items(): source = config.get("msvs_precompiled_source") if source: source = _FixPath(source) # UsePrecompiledHeader=1 for if using precompiled headers. tool = MSVSProject.Tool("VCCLCompilerTool", {"UsePrecompiledHeader": "1"}) p.AddFileConfig( source, _ConfigFullName(config_name, config), {}, tools=[tool] ) basename, extension = os.path.splitext(source) if extension == ".c": extensions_excluded_from_precompile = [".cc", ".cpp", ".cxx"] else: extensions_excluded_from_precompile = [".c"] def DisableForSourceTree(source_tree): for source in source_tree: if isinstance(source, MSVSProject.Filter): DisableForSourceTree(source.contents) else: basename, extension = os.path.splitext(source) if extension in extensions_excluded_from_precompile: for config_name, config in spec["configurations"].items(): tool = MSVSProject.Tool( "VCCLCompilerTool", { "UsePrecompiledHeader": "0", "ForcedIncludeFiles": "$(NOINHERIT)", }, ) p.AddFileConfig( _FixPath(source), _ConfigFullName(config_name, config), {}, tools=[tool], ) # Do nothing if there was no precompiled source. if extensions_excluded_from_precompile: DisableForSourceTree(sources) def _AddActions(actions_to_add, spec, relative_path_of_gyp_file): # Add actions. actions = spec.get("actions", []) # Don't setup_env every time. When all the actions are run together in one # batch file in VS, the PATH will grow too long. # Membership in this set means that the cygwin environment has been set up, # and does not need to be set up again. have_setup_env = set() for a in actions: # Attach actions to the gyp file if nothing else is there. inputs = a.get("inputs") or [relative_path_of_gyp_file] attached_to = inputs[0] need_setup_env = attached_to not in have_setup_env cmd = _BuildCommandLineForRule( spec, a, has_input_path=False, do_setup_env=need_setup_env ) have_setup_env.add(attached_to) # Add the action. _AddActionStep( actions_to_add, inputs=inputs, outputs=a.get("outputs", []), description=a.get("message", a["action_name"]), command=cmd, ) def _WriteMSVSUserFile(project_path, version, spec): # Add run_as and test targets. if "run_as" in spec: run_as = spec["run_as"] action = run_as.get("action", []) environment = run_as.get("environment", []) working_directory = run_as.get("working_directory", ".") elif int(spec.get("test", 0)): action = ["$(TargetPath)", "--gtest_print_time"] environment = [] working_directory = "." else: return # Nothing to add # Write out the user file. user_file = _CreateMSVSUserFile(project_path, version, spec) for config_name, c_data in spec["configurations"].items(): user_file.AddDebugSettings( _ConfigFullName(config_name, c_data), action, environment, working_directory ) user_file.WriteIfChanged() def _AddCopies(actions_to_add, spec): copies = _GetCopies(spec) for inputs, outputs, cmd, description in copies: _AddActionStep( actions_to_add, inputs=inputs, outputs=outputs, description=description, command=cmd, ) def _GetCopies(spec): copies = [] # Add copies. for cpy in spec.get("copies", []): for src in cpy.get("files", []): dst = os.path.join(cpy["destination"], os.path.basename(src)) # _AddCustomBuildToolForMSVS() will call _FixPath() on the inputs and # outputs, so do the same for our generated command line. if src.endswith("/"): src_bare = src[:-1] base_dir = posixpath.split(src_bare)[0] outer_dir = posixpath.split(src_bare)[1] fixed_dst = _FixPath(dst) full_dst = f'"{fixed_dst}\\{outer_dir}\\"' cmd = ( f'mkdir {full_dst} 2>nul & cd "{_FixPath(base_dir)}" && ' f'xcopy /e /f /y "{outer_dir}" {full_dst}' ) copies.append( ( [src], ["dummy_copies", dst], cmd, f"Copying {src} to {fixed_dst}", ) ) else: fix_dst = _FixPath(cpy["destination"]) cmd = ( f'mkdir "{fix_dst}" 2>nul & set ERRORLEVEL=0 & ' f'copy /Y "{_FixPath(src)}" "{_FixPath(dst)}"' ) copies.append(([src], [dst], cmd, f"Copying {src} to {fix_dst}")) return copies def _GetPathDict(root, path): # |path| will eventually be empty (in the recursive calls) if it was initially # relative; otherwise it will eventually end up as '\', 'D:\', etc. if not path or path.endswith(os.sep): return root parent, folder = os.path.split(path) parent_dict = _GetPathDict(root, parent) if folder not in parent_dict: parent_dict[folder] = {} return parent_dict[folder] def _DictsToFolders(base_path, bucket, flat): # Convert to folders recursively. children = [] for folder, contents in bucket.items(): if type(contents) == dict: folder_children = _DictsToFolders( os.path.join(base_path, folder), contents, flat ) if flat: children += folder_children else: folder_children = MSVSNew.MSVSFolder( os.path.join(base_path, folder), name="(" + folder + ")", entries=folder_children, ) children.append(folder_children) else: children.append(contents) return children def _CollapseSingles(parent, node): # Recursively explorer the tree of dicts looking for projects which are # the sole item in a folder which has the same name as the project. Bring # such projects up one level. if type(node) == dict and len(node) == 1 and next(iter(node)) == parent + ".vcproj": return node[next(iter(node))] if type(node) != dict: return node for child in node: node[child] = _CollapseSingles(child, node[child]) return node def _GatherSolutionFolders(sln_projects, project_objects, flat): root = {} # Convert into a tree of dicts on path. for p in sln_projects: gyp_file, target = gyp.common.ParseQualifiedTarget(p)[0:2] if p.endswith("#host"): target += "_host" gyp_dir = os.path.dirname(gyp_file) path_dict = _GetPathDict(root, gyp_dir) path_dict[target + ".vcproj"] = project_objects[p] # Walk down from the top until we hit a folder that has more than one entry. # In practice, this strips the top-level "src/" dir from the hierarchy in # the solution. while len(root) == 1 and type(root[next(iter(root))]) == dict: root = root[next(iter(root))] # Collapse singles. root = _CollapseSingles("", root) # Merge buckets until everything is a root entry. return _DictsToFolders("", root, flat) def _GetPathOfProject(qualified_target, spec, options, msvs_version): default_config = _GetDefaultConfiguration(spec) proj_filename = default_config.get("msvs_existing_vcproj") if not proj_filename: proj_filename = spec["target_name"] if spec["toolset"] == "host": proj_filename += "_host" proj_filename = proj_filename + options.suffix + msvs_version.ProjectExtension() build_file = gyp.common.BuildFile(qualified_target) proj_path = os.path.join(os.path.dirname(build_file), proj_filename) fix_prefix = None if options.generator_output: project_dir_path = os.path.dirname(os.path.abspath(proj_path)) proj_path = os.path.join(options.generator_output, proj_path) fix_prefix = gyp.common.RelativePath( project_dir_path, os.path.dirname(proj_path) ) return proj_path, fix_prefix def _GetPlatformOverridesOfProject(spec): # Prepare a dict indicating which project configurations are used for which # solution configurations for this target. config_platform_overrides = {} for config_name, c in spec["configurations"].items(): config_fullname = _ConfigFullName(config_name, c) platform = c.get("msvs_target_platform", _ConfigPlatform(c)) fixed_config_fullname = ( f"{_ConfigBaseName(config_name, _ConfigPlatform(c))}|{platform}" ) if spec["toolset"] == "host" and generator_supports_multiple_toolsets: fixed_config_fullname = f"{config_name}|x64" config_platform_overrides[config_fullname] = fixed_config_fullname return config_platform_overrides def _CreateProjectObjects(target_list, target_dicts, options, msvs_version): """Create a MSVSProject object for the targets found in target list. Arguments: target_list: the list of targets to generate project objects for. target_dicts: the dictionary of specifications. options: global generator options. msvs_version: the MSVSVersion object. Returns: A set of created projects, keyed by target. """ global fixpath_prefix # Generate each project. projects = {} for qualified_target in target_list: spec = target_dicts[qualified_target] proj_path, fixpath_prefix = _GetPathOfProject( qualified_target, spec, options, msvs_version ) guid = _GetGuidOfProject(proj_path, spec) overrides = _GetPlatformOverridesOfProject(spec) build_file = gyp.common.BuildFile(qualified_target) # Create object for this project. target_name = spec["target_name"] if spec["toolset"] == "host": target_name += "_host" obj = MSVSNew.MSVSProject( proj_path, name=target_name, guid=guid, spec=spec, build_file=build_file, config_platform_overrides=overrides, fixpath_prefix=fixpath_prefix, ) # Set project toolset if any (MS build only) if msvs_version.UsesVcxproj(): obj.set_msbuild_toolset( _GetMsbuildToolsetOfProject(proj_path, spec, msvs_version) ) projects[qualified_target] = obj # Set all the dependencies, but not if we are using an external builder like # ninja for project in projects.values(): if not project.spec.get("msvs_external_builder"): deps = project.spec.get("dependencies", []) deps = [projects[d] for d in deps] project.set_dependencies(deps) return projects def _InitNinjaFlavor(params, target_list, target_dicts): """Initialize targets for the ninja flavor. This sets up the necessary variables in the targets to generate msvs projects that use ninja as an external builder. The variables in the spec are only set if they have not been set. This allows individual specs to override the default values initialized here. Arguments: params: Params provided to the generator. target_list: List of target pairs: 'base/base.gyp:base'. target_dicts: Dict of target properties keyed on target pair. """ for qualified_target in target_list: spec = target_dicts[qualified_target] if spec.get("msvs_external_builder"): # The spec explicitly defined an external builder, so don't change it. continue path_to_ninja = spec.get("msvs_path_to_ninja", "ninja.exe") spec["msvs_external_builder"] = "ninja" if not spec.get("msvs_external_builder_out_dir"): gyp_file, _, _ = gyp.common.ParseQualifiedTarget(qualified_target) gyp_dir = os.path.dirname(gyp_file) configuration = "$(Configuration)" if params.get("target_arch") == "x64": configuration += "_x64" if params.get("target_arch") == "arm64": configuration += "_arm64" spec["msvs_external_builder_out_dir"] = os.path.join( gyp.common.RelativePath(params["options"].toplevel_dir, gyp_dir), ninja_generator.ComputeOutputDir(params), configuration, ) if not spec.get("msvs_external_builder_build_cmd"): spec["msvs_external_builder_build_cmd"] = [ path_to_ninja, "-C", "$(OutDir)", "$(ProjectName)", ] if not spec.get("msvs_external_builder_clean_cmd"): spec["msvs_external_builder_clean_cmd"] = [ path_to_ninja, "-C", "$(OutDir)", "-tclean", "$(ProjectName)", ] def CalculateVariables(default_variables, params): """Generated variables that require params to be known.""" generator_flags = params.get("generator_flags", {}) # Select project file format version (if unset, default to auto detecting). msvs_version = MSVSVersion.SelectVisualStudioVersion( generator_flags.get("msvs_version", "auto") ) # Stash msvs_version for later (so we don't have to probe the system twice). params["msvs_version"] = msvs_version # Set a variable so conditions can be based on msvs_version. default_variables["MSVS_VERSION"] = msvs_version.ShortName() # To determine processor word size on Windows, in addition to checking # PROCESSOR_ARCHITECTURE (which reflects the word size of the current # process), it is also necessary to check PROCESSOR_ARCITEW6432 (which # contains the actual word size of the system when running thru WOW64). if ( os.environ.get("PROCESSOR_ARCHITECTURE", "").find("64") >= 0 or os.environ.get("PROCESSOR_ARCHITEW6432", "").find("64") >= 0 ): default_variables["MSVS_OS_BITS"] = 64 else: default_variables["MSVS_OS_BITS"] = 32 if gyp.common.GetFlavor(params) == "ninja": default_variables["SHARED_INTERMEDIATE_DIR"] = "$(OutDir)gen" def PerformBuild(data, configurations, params): options = params["options"] msvs_version = params["msvs_version"] devenv = os.path.join(msvs_version.path, "Common7", "IDE", "devenv.com") for build_file, build_file_dict in data.items(): (build_file_root, build_file_ext) = os.path.splitext(build_file) if build_file_ext != ".gyp": continue sln_path = build_file_root + options.suffix + ".sln" if options.generator_output: sln_path = os.path.join(options.generator_output, sln_path) for config in configurations: arguments = [devenv, sln_path, "/Build", config] print(f"Building [{config}]: {arguments}") subprocess.check_call(arguments) def CalculateGeneratorInputInfo(params): if params.get("flavor") == "ninja": toplevel = params["options"].toplevel_dir qualified_out_dir = os.path.normpath( os.path.join( toplevel, ninja_generator.ComputeOutputDir(params), "gypfiles-msvs-ninja", ) ) global generator_filelist_paths generator_filelist_paths = { "toplevel": toplevel, "qualified_out_dir": qualified_out_dir, } def GenerateOutput(target_list, target_dicts, data, params): """Generate .sln and .vcproj files. This is the entry point for this generator. Arguments: target_list: List of target pairs: 'base/base.gyp:base'. target_dicts: Dict of target properties keyed on target pair. data: Dictionary containing per .gyp data. """ global fixpath_prefix options = params["options"] # Get the project file format version back out of where we stashed it in # GeneratorCalculatedVariables. msvs_version = params["msvs_version"] generator_flags = params.get("generator_flags", {}) # Optionally shard targets marked with 'msvs_shard': SHARD_COUNT. (target_list, target_dicts) = MSVSUtil.ShardTargets(target_list, target_dicts) # Optionally use the large PDB workaround for targets marked with # 'msvs_large_pdb': 1. (target_list, target_dicts) = MSVSUtil.InsertLargePdbShims( target_list, target_dicts, generator_default_variables ) # Optionally configure each spec to use ninja as the external builder. if params.get("flavor") == "ninja": _InitNinjaFlavor(params, target_list, target_dicts) # Prepare the set of configurations. configs = set() for qualified_target in target_list: spec = target_dicts[qualified_target] for config_name, config in spec["configurations"].items(): config_name = _ConfigFullName(config_name, config) configs.add(config_name) if config_name == "Release|arm64": configs.add("Release|x64") configs = list(configs) # Figure out all the projects that will be generated and their guids project_objects = _CreateProjectObjects( target_list, target_dicts, options, msvs_version ) # Generate each project. missing_sources = [] for project in project_objects.values(): fixpath_prefix = project.fixpath_prefix missing_sources.extend( _GenerateProject(project, options, msvs_version, generator_flags, spec) ) fixpath_prefix = None for build_file in data: # Validate build_file extension target_only_configs = configs if generator_supports_multiple_toolsets: target_only_configs = [i for i in configs if i.endswith("arm64")] if not build_file.endswith(".gyp"): continue sln_path = os.path.splitext(build_file)[0] + options.suffix + ".sln" if options.generator_output: sln_path = os.path.join(options.generator_output, sln_path) # Get projects in the solution, and their dependents. sln_projects = gyp.common.BuildFileTargets(target_list, build_file) sln_projects += gyp.common.DeepDependencyTargets(target_dicts, sln_projects) # Create folder hierarchy. root_entries = _GatherSolutionFolders( sln_projects, project_objects, flat=msvs_version.FlatSolution() ) # Create solution. sln = MSVSNew.MSVSSolution( sln_path, entries=root_entries, variants=target_only_configs, websiteProperties=False, version=msvs_version, ) sln.Write() if missing_sources: error_message = "Missing input files:\n" + "\n".join(set(missing_sources)) if generator_flags.get("msvs_error_on_missing_sources", False): raise GypError(error_message) else: print("Warning: " + error_message, file=sys.stdout) def _GenerateMSBuildFiltersFile( filters_path, source_files, rule_dependencies, extension_to_rule_name, platforms, toolset, ): """Generate the filters file. This file is used by Visual Studio to organize the presentation of source files into folders. Arguments: filters_path: The path of the file to be created. source_files: The hierarchical structure of all the sources. extension_to_rule_name: A dictionary mapping file extensions to rules. """ filter_group = [] source_group = [] _AppendFiltersForMSBuild( "", source_files, rule_dependencies, extension_to_rule_name, platforms, toolset, filter_group, source_group, ) if filter_group: content = [ "Project", { "ToolsVersion": "4.0", "xmlns": "http://schemas.microsoft.com/developer/msbuild/2003", }, ["ItemGroup"] + filter_group, ["ItemGroup"] + source_group, ] easy_xml.WriteXmlIfChanged(content, filters_path, pretty=True, win32=True) elif os.path.exists(filters_path): # We don't need this filter anymore. Delete the old filter file. os.unlink(filters_path) def _AppendFiltersForMSBuild( parent_filter_name, sources, rule_dependencies, extension_to_rule_name, platforms, toolset, filter_group, source_group, ): """Creates the list of filters and sources to be added in the filter file. Args: parent_filter_name: The name of the filter under which the sources are found. sources: The hierarchy of filters and sources to process. extension_to_rule_name: A dictionary mapping file extensions to rules. filter_group: The list to which filter entries will be appended. source_group: The list to which source entries will be appended. """ for source in sources: if isinstance(source, MSVSProject.Filter): # We have a sub-filter. Create the name of that sub-filter. if not parent_filter_name: filter_name = source.name else: filter_name = f"{parent_filter_name}\\{source.name}" # Add the filter to the group. filter_group.append( [ "Filter", {"Include": filter_name}, ["UniqueIdentifier", MSVSNew.MakeGuid(source.name)], ] ) # Recurse and add its dependents. _AppendFiltersForMSBuild( filter_name, source.contents, rule_dependencies, extension_to_rule_name, platforms, toolset, filter_group, source_group, ) else: # It's a source. Create a source entry. _, element = _MapFileToMsBuildSourceType( source, rule_dependencies, extension_to_rule_name, platforms, toolset ) source_entry = [element, {"Include": source}] # Specify the filter it is part of, if any. if parent_filter_name: source_entry.append(["Filter", parent_filter_name]) source_group.append(source_entry) def _MapFileToMsBuildSourceType( source, rule_dependencies, extension_to_rule_name, platforms, toolset ): """Returns the group and element type of the source file. Arguments: source: The source file name. extension_to_rule_name: A dictionary mapping file extensions to rules. Returns: A pair of (group this file should be part of, the label of element) """ _, ext = os.path.splitext(source) ext = ext.lower() if ext in extension_to_rule_name: group = "rule" element = extension_to_rule_name[ext] elif ext in [".cc", ".cpp", ".c", ".cxx", ".mm"]: group = "compile" element = "ClCompile" elif ext in [".h", ".hxx"]: group = "include" element = "ClInclude" elif ext == ".rc": group = "resource" element = "ResourceCompile" elif ext in [".s", ".asm"]: group = "masm" element = "MASM" if "arm64" in platforms and toolset == "target": element = "MARMASM" elif ext == ".idl": group = "midl" element = "Midl" elif source in rule_dependencies: group = "rule_dependency" element = "CustomBuild" else: group = "none" element = "None" return (group, element) def _GenerateRulesForMSBuild( output_dir, options, spec, sources, excluded_sources, props_files_of_rules, targets_files_of_rules, actions_to_add, rule_dependencies, extension_to_rule_name, ): # MSBuild rules are implemented using three files: an XML file, a .targets # file and a .props file. # For more details see: # https://devblogs.microsoft.com/cppblog/quick-help-on-vs2010-custom-build-rule/ rules = spec.get("rules", []) rules_native = [r for r in rules if not int(r.get("msvs_external_rule", 0))] rules_external = [r for r in rules if int(r.get("msvs_external_rule", 0))] msbuild_rules = [] for rule in rules_native: # Skip a rule with no action and no inputs. if "action" not in rule and not rule.get("rule_sources", []): continue msbuild_rule = MSBuildRule(rule, spec) msbuild_rules.append(msbuild_rule) rule_dependencies.update(msbuild_rule.additional_dependencies.split(";")) extension_to_rule_name[msbuild_rule.extension] = msbuild_rule.rule_name if msbuild_rules: base = spec["target_name"] + options.suffix props_name = base + ".props" targets_name = base + ".targets" xml_name = base + ".xml" props_files_of_rules.add(props_name) targets_files_of_rules.add(targets_name) props_path = os.path.join(output_dir, props_name) targets_path = os.path.join(output_dir, targets_name) xml_path = os.path.join(output_dir, xml_name) _GenerateMSBuildRulePropsFile(props_path, msbuild_rules) _GenerateMSBuildRuleTargetsFile(targets_path, msbuild_rules) _GenerateMSBuildRuleXmlFile(xml_path, msbuild_rules) if rules_external: _GenerateExternalRules( rules_external, output_dir, spec, sources, options, actions_to_add ) _AdjustSourcesForRules(rules, sources, excluded_sources, True) class MSBuildRule: """Used to store information used to generate an MSBuild rule. Attributes: rule_name: The rule name, sanitized to use in XML. target_name: The name of the target. after_targets: The name of the AfterTargets element. before_targets: The name of the BeforeTargets element. depends_on: The name of the DependsOn element. compute_output: The name of the ComputeOutput element. dirs_to_make: The name of the DirsToMake element. inputs: The name of the _inputs element. tlog: The name of the _tlog element. extension: The extension this rule applies to. description: The message displayed when this rule is invoked. additional_dependencies: A string listing additional dependencies. outputs: The outputs of this rule. command: The command used to run the rule. """ def __init__(self, rule, spec): self.display_name = rule["rule_name"] # Assure that the rule name is only characters and numbers self.rule_name = re.sub(r"\W", "_", self.display_name) # Create the various element names, following the example set by the # Visual Studio 2008 to 2010 conversion. I don't know if VS2010 # is sensitive to the exact names. self.target_name = "_" + self.rule_name self.after_targets = self.rule_name + "AfterTargets" self.before_targets = self.rule_name + "BeforeTargets" self.depends_on = self.rule_name + "DependsOn" self.compute_output = "Compute%sOutput" % self.rule_name self.dirs_to_make = self.rule_name + "DirsToMake" self.inputs = self.rule_name + "_inputs" self.tlog = self.rule_name + "_tlog" self.extension = rule["extension"] if not self.extension.startswith("."): self.extension = "." + self.extension self.description = MSVSSettings.ConvertVCMacrosToMSBuild( rule.get("message", self.rule_name) ) old_additional_dependencies = _FixPaths(rule.get("inputs", [])) self.additional_dependencies = ";".join( [ MSVSSettings.ConvertVCMacrosToMSBuild(i) for i in old_additional_dependencies ] ) old_outputs = _FixPaths(rule.get("outputs", [])) self.outputs = ";".join( [MSVSSettings.ConvertVCMacrosToMSBuild(i) for i in old_outputs] ) old_command = _BuildCommandLineForRule( spec, rule, has_input_path=True, do_setup_env=True ) self.command = MSVSSettings.ConvertVCMacrosToMSBuild(old_command) def _GenerateMSBuildRulePropsFile(props_path, msbuild_rules): """Generate the .props file.""" content = [ "Project", {"xmlns": "http://schemas.microsoft.com/developer/msbuild/2003"}, ] for rule in msbuild_rules: content.extend( [ [ "PropertyGroup", { "Condition": "'$(%s)' == '' and '$(%s)' == '' and " "'$(ConfigurationType)' != 'Makefile'" % (rule.before_targets, rule.after_targets) }, [rule.before_targets, "Midl"], [rule.after_targets, "CustomBuild"], ], [ "PropertyGroup", [ rule.depends_on, {"Condition": "'$(ConfigurationType)' != 'Makefile'"}, "_SelectedFiles;$(%s)" % rule.depends_on, ], ], [ "ItemDefinitionGroup", [ rule.rule_name, ["CommandLineTemplate", rule.command], ["Outputs", rule.outputs], ["ExecutionDescription", rule.description], ["AdditionalDependencies", rule.additional_dependencies], ], ], ] ) easy_xml.WriteXmlIfChanged(content, props_path, pretty=True, win32=True) def _GenerateMSBuildRuleTargetsFile(targets_path, msbuild_rules): """Generate the .targets file.""" content = [ "Project", {"xmlns": "http://schemas.microsoft.com/developer/msbuild/2003"}, ] item_group = [ "ItemGroup", [ "PropertyPageSchema", {"Include": "$(MSBuildThisFileDirectory)$(MSBuildThisFileName).xml"}, ], ] for rule in msbuild_rules: item_group.append( [ "AvailableItemName", {"Include": rule.rule_name}, ["Targets", rule.target_name], ] ) content.append(item_group) for rule in msbuild_rules: content.append( [ "UsingTask", { "TaskName": rule.rule_name, "TaskFactory": "XamlTaskFactory", "AssemblyName": "Microsoft.Build.Tasks.v4.0", }, ["Task", "$(MSBuildThisFileDirectory)$(MSBuildThisFileName).xml"], ] ) for rule in msbuild_rules: rule_name = rule.rule_name target_outputs = "%%(%s.Outputs)" % rule_name target_inputs = ( "%%(%s.Identity);%%(%s.AdditionalDependencies);" "$(MSBuildProjectFile)" ) % (rule_name, rule_name) rule_inputs = "%%(%s.Identity)" % rule_name extension_condition = ( "'%(Extension)'=='.obj' or " "'%(Extension)'=='.res' or " "'%(Extension)'=='.rsc' or " "'%(Extension)'=='.lib'" ) remove_section = [ "ItemGroup", {"Condition": "'@(SelectedFiles)' != ''"}, [ rule_name, { "Remove": "@(%s)" % rule_name, "Condition": "'%(Identity)' != '@(SelectedFiles)'", }, ], ] inputs_section = [ "ItemGroup", [rule.inputs, {"Include": "%%(%s.AdditionalDependencies)" % rule_name}], ] logging_section = [ "ItemGroup", [ rule.tlog, { "Include": "%%(%s.Outputs)" % rule_name, "Condition": ( "'%%(%s.Outputs)' != '' and " "'%%(%s.ExcludedFromBuild)' != 'true'" % (rule_name, rule_name) ), }, ["Source", "@(%s, '|')" % rule_name], ["Inputs", "@(%s -> '%%(Fullpath)', ';')" % rule.inputs], ], ] message_section = [ "Message", {"Importance": "High", "Text": "%%(%s.ExecutionDescription)" % rule_name}, ] write_tlog_section = [ "WriteLinesToFile", { "Condition": "'@(%s)' != '' and '%%(%s.ExcludedFromBuild)' != " "'true'" % (rule.tlog, rule.tlog), "File": "$(IntDir)$(ProjectName).write.1.tlog", "Lines": "^%%(%s.Source);@(%s->'%%(Fullpath)')" % (rule.tlog, rule.tlog), }, ] read_tlog_section = [ "WriteLinesToFile", { "Condition": "'@(%s)' != '' and '%%(%s.ExcludedFromBuild)' != " "'true'" % (rule.tlog, rule.tlog), "File": "$(IntDir)$(ProjectName).read.1.tlog", "Lines": f"^%({rule.tlog}.Source);%({rule.tlog}.Inputs)", }, ] command_and_input_section = [ rule_name, { "Condition": "'@(%s)' != '' and '%%(%s.ExcludedFromBuild)' != " "'true'" % (rule_name, rule_name), "EchoOff": "true", "StandardOutputImportance": "High", "StandardErrorImportance": "High", "CommandLineTemplate": "%%(%s.CommandLineTemplate)" % rule_name, "AdditionalOptions": "%%(%s.AdditionalOptions)" % rule_name, "Inputs": rule_inputs, }, ] content.extend( [ [ "Target", { "Name": rule.target_name, "BeforeTargets": "$(%s)" % rule.before_targets, "AfterTargets": "$(%s)" % rule.after_targets, "Condition": "'@(%s)' != ''" % rule_name, "DependsOnTargets": "$(%s);%s" % (rule.depends_on, rule.compute_output), "Outputs": target_outputs, "Inputs": target_inputs, }, remove_section, inputs_section, logging_section, message_section, write_tlog_section, read_tlog_section, command_and_input_section, ], [ "PropertyGroup", [ "ComputeLinkInputsTargets", "$(ComputeLinkInputsTargets);", "%s;" % rule.compute_output, ], [ "ComputeLibInputsTargets", "$(ComputeLibInputsTargets);", "%s;" % rule.compute_output, ], ], [ "Target", { "Name": rule.compute_output, "Condition": "'@(%s)' != ''" % rule_name, }, [ "ItemGroup", [ rule.dirs_to_make, { "Condition": "'@(%s)' != '' and " "'%%(%s.ExcludedFromBuild)' != 'true'" % (rule_name, rule_name), "Include": "%%(%s.Outputs)" % rule_name, }, ], [ "Link", { "Include": "%%(%s.Identity)" % rule.dirs_to_make, "Condition": extension_condition, }, ], [ "Lib", { "Include": "%%(%s.Identity)" % rule.dirs_to_make, "Condition": extension_condition, }, ], [ "ImpLib", { "Include": "%%(%s.Identity)" % rule.dirs_to_make, "Condition": extension_condition, }, ], ], [ "MakeDir", { "Directories": ( "@(%s->'%%(RootDir)%%(Directory)')" % rule.dirs_to_make ) }, ], ], ] ) easy_xml.WriteXmlIfChanged(content, targets_path, pretty=True, win32=True) def _GenerateMSBuildRuleXmlFile(xml_path, msbuild_rules): # Generate the .xml file content = [ "ProjectSchemaDefinitions", { "xmlns": ( "clr-namespace:Microsoft.Build.Framework.XamlTypes;" "assembly=Microsoft.Build.Framework" ), "xmlns:x": "http://schemas.microsoft.com/winfx/2006/xaml", "xmlns:sys": "clr-namespace:System;assembly=mscorlib", "xmlns:transformCallback": "Microsoft.Cpp.Dev10.ConvertPropertyCallback", }, ] for rule in msbuild_rules: content.extend( [ [ "Rule", { "Name": rule.rule_name, "PageTemplate": "tool", "DisplayName": rule.display_name, "Order": "200", }, [ "Rule.DataSource", [ "DataSource", {"Persistence": "ProjectFile", "ItemType": rule.rule_name}, ], ], [ "Rule.Categories", [ "Category", {"Name": "General"}, ["Category.DisplayName", ["sys:String", "General"]], ], [ "Category", {"Name": "Command Line", "Subtype": "CommandLine"}, ["Category.DisplayName", ["sys:String", "Command Line"]], ], ], [ "StringListProperty", { "Name": "Inputs", "Category": "Command Line", "IsRequired": "true", "Switch": " ", }, [ "StringListProperty.DataSource", [ "DataSource", { "Persistence": "ProjectFile", "ItemType": rule.rule_name, "SourceType": "Item", }, ], ], ], [ "StringProperty", { "Name": "CommandLineTemplate", "DisplayName": "Command Line", "Visible": "False", "IncludeInCommandLine": "False", }, ], [ "DynamicEnumProperty", { "Name": rule.before_targets, "Category": "General", "EnumProvider": "Targets", "IncludeInCommandLine": "False", }, [ "DynamicEnumProperty.DisplayName", ["sys:String", "Execute Before"], ], [ "DynamicEnumProperty.Description", [ "sys:String", "Specifies the targets for the build customization" " to run before.", ], ], [ "DynamicEnumProperty.ProviderSettings", [ "NameValuePair", { "Name": "Exclude", "Value": "^%s|^Compute" % rule.before_targets, }, ], ], [ "DynamicEnumProperty.DataSource", [ "DataSource", { "Persistence": "ProjectFile", "HasConfigurationCondition": "true", }, ], ], ], [ "DynamicEnumProperty", { "Name": rule.after_targets, "Category": "General", "EnumProvider": "Targets", "IncludeInCommandLine": "False", }, [ "DynamicEnumProperty.DisplayName", ["sys:String", "Execute After"], ], [ "DynamicEnumProperty.Description", [ "sys:String", ( "Specifies the targets for the build customization" " to run after." ), ], ], [ "DynamicEnumProperty.ProviderSettings", [ "NameValuePair", { "Name": "Exclude", "Value": "^%s|^Compute" % rule.after_targets, }, ], ], [ "DynamicEnumProperty.DataSource", [ "DataSource", { "Persistence": "ProjectFile", "ItemType": "", "HasConfigurationCondition": "true", }, ], ], ], [ "StringListProperty", { "Name": "Outputs", "DisplayName": "Outputs", "Visible": "False", "IncludeInCommandLine": "False", }, ], [ "StringProperty", { "Name": "ExecutionDescription", "DisplayName": "Execution Description", "Visible": "False", "IncludeInCommandLine": "False", }, ], [ "StringListProperty", { "Name": "AdditionalDependencies", "DisplayName": "Additional Dependencies", "IncludeInCommandLine": "False", "Visible": "false", }, ], [ "StringProperty", { "Subtype": "AdditionalOptions", "Name": "AdditionalOptions", "Category": "Command Line", }, [ "StringProperty.DisplayName", ["sys:String", "Additional Options"], ], [ "StringProperty.Description", ["sys:String", "Additional Options"], ], ], ], [ "ItemType", {"Name": rule.rule_name, "DisplayName": rule.display_name}, ], [ "FileExtension", {"Name": "*" + rule.extension, "ContentType": rule.rule_name}, ], [ "ContentType", { "Name": rule.rule_name, "DisplayName": "", "ItemType": rule.rule_name, }, ], ] ) easy_xml.WriteXmlIfChanged(content, xml_path, pretty=True, win32=True) def _GetConfigurationAndPlatform(name, settings, spec): configuration = name.rsplit("_", 1)[0] platform = settings.get("msvs_configuration_platform", "Win32") if spec["toolset"] == "host" and platform == "arm64": platform = "x64" # Host-only tools are always built for x64 return (configuration, platform) def _GetConfigurationCondition(name, settings, spec): return r"'$(Configuration)|$(Platform)'=='%s|%s'" % _GetConfigurationAndPlatform( name, settings, spec ) def _GetMSBuildProjectConfigurations(configurations, spec): group = ["ItemGroup", {"Label": "ProjectConfigurations"}] for (name, settings) in sorted(configurations.items()): configuration, platform = _GetConfigurationAndPlatform(name, settings, spec) designation = f"{configuration}|{platform}" group.append( [ "ProjectConfiguration", {"Include": designation}, ["Configuration", configuration], ["Platform", platform], ] ) return [group] def _GetMSBuildGlobalProperties(spec, version, guid, gyp_file_name): namespace = os.path.splitext(gyp_file_name)[0] properties = [ [ "PropertyGroup", {"Label": "Globals"}, ["ProjectGuid", guid], ["Keyword", "Win32Proj"], ["RootNamespace", namespace], ["IgnoreWarnCompileDuplicatedFilename", "true"], ] ] if ( os.environ.get("PROCESSOR_ARCHITECTURE") == "AMD64" or os.environ.get("PROCESSOR_ARCHITEW6432") == "AMD64" ): properties[0].append(["PreferredToolArchitecture", "x64"]) if spec.get("msvs_target_platform_version"): target_platform_version = spec.get("msvs_target_platform_version") properties[0].append(["WindowsTargetPlatformVersion", target_platform_version]) if spec.get("msvs_target_platform_minversion"): target_platform_minversion = spec.get("msvs_target_platform_minversion") properties[0].append( ["WindowsTargetPlatformMinVersion", target_platform_minversion] ) else: properties[0].append( ["WindowsTargetPlatformMinVersion", target_platform_version] ) if spec.get("msvs_enable_winrt"): properties[0].append(["DefaultLanguage", "en-US"]) properties[0].append(["AppContainerApplication", "true"]) if spec.get("msvs_application_type_revision"): app_type_revision = spec.get("msvs_application_type_revision") properties[0].append(["ApplicationTypeRevision", app_type_revision]) else: properties[0].append(["ApplicationTypeRevision", "8.1"]) if spec.get("msvs_enable_winphone"): properties[0].append(["ApplicationType", "Windows Phone"]) else: properties[0].append(["ApplicationType", "Windows Store"]) platform_name = None msvs_windows_sdk_version = None for configuration in spec["configurations"].values(): platform_name = platform_name or _ConfigPlatform(configuration) msvs_windows_sdk_version = ( msvs_windows_sdk_version or _ConfigWindowsTargetPlatformVersion(configuration, version) ) if platform_name and msvs_windows_sdk_version: break if msvs_windows_sdk_version: properties[0].append( ["WindowsTargetPlatformVersion", str(msvs_windows_sdk_version)] ) elif version.compatible_sdks: raise GypError( "%s requires any SDK of %s version, but none were found" % (version.description, version.compatible_sdks) ) if platform_name == "ARM": properties[0].append(["WindowsSDKDesktopARMSupport", "true"]) return properties def _GetMSBuildConfigurationDetails(spec, build_file): properties = {} for name, settings in spec["configurations"].items(): msbuild_attributes = _GetMSBuildAttributes(spec, settings, build_file) condition = _GetConfigurationCondition(name, settings, spec) character_set = msbuild_attributes.get("CharacterSet") vctools_version = msbuild_attributes.get("VCToolsVersion") config_type = msbuild_attributes.get("ConfigurationType") _AddConditionalProperty(properties, condition, "ConfigurationType", config_type) spectre_mitigation = msbuild_attributes.get('SpectreMitigation') if spectre_mitigation: _AddConditionalProperty(properties, condition, "SpectreMitigation", spectre_mitigation) if config_type == "Driver": _AddConditionalProperty(properties, condition, "DriverType", "WDM") _AddConditionalProperty( properties, condition, "TargetVersion", _ConfigTargetVersion(settings) ) if character_set and "msvs_enable_winrt" not in spec: _AddConditionalProperty( properties, condition, "CharacterSet", character_set ) if vctools_version and "msvs_enable_winrt" not in spec: _AddConditionalProperty( properties, condition, "VCToolsVersion", vctools_version ) return _GetMSBuildPropertyGroup(spec, "Configuration", properties) def _GetMSBuildLocalProperties(msbuild_toolset): # Currently the only local property we support is PlatformToolset properties = {} if msbuild_toolset: properties = [ [ "PropertyGroup", {"Label": "Locals"}, ["PlatformToolset", msbuild_toolset], ] ] return properties def _GetMSBuildPropertySheets(configurations, spec): user_props = r"$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" additional_props = {} props_specified = False for name, settings in sorted(configurations.items()): configuration = _GetConfigurationCondition(name, settings, spec) if "msbuild_props" in settings: additional_props[configuration] = _FixPaths(settings["msbuild_props"]) props_specified = True else: additional_props[configuration] = "" if not props_specified: return [ [ "ImportGroup", {"Label": "PropertySheets"}, [ "Import", { "Project": user_props, "Condition": "exists('%s')" % user_props, "Label": "LocalAppDataPlatform", }, ], ] ] else: sheets = [] for condition, props in additional_props.items(): import_group = [ "ImportGroup", {"Label": "PropertySheets", "Condition": condition}, [ "Import", { "Project": user_props, "Condition": "exists('%s')" % user_props, "Label": "LocalAppDataPlatform", }, ], ] for props_file in props: import_group.append(["Import", {"Project": props_file}]) sheets.append(import_group) return sheets def _ConvertMSVSBuildAttributes(spec, config, build_file): config_type = _GetMSVSConfigurationType(spec, build_file) msvs_attributes = _GetMSVSAttributes(spec, config, config_type) msbuild_attributes = {} for a in msvs_attributes: if a in ["IntermediateDirectory", "OutputDirectory"]: directory = MSVSSettings.ConvertVCMacrosToMSBuild(msvs_attributes[a]) if not directory.endswith("\\"): directory += "\\" msbuild_attributes[a] = directory elif a == "CharacterSet": msbuild_attributes[a] = _ConvertMSVSCharacterSet(msvs_attributes[a]) elif a == "ConfigurationType": msbuild_attributes[a] = _ConvertMSVSConfigurationType(msvs_attributes[a]) elif a == "SpectreMitigation": msbuild_attributes[a] = msvs_attributes[a] elif a == "VCToolsVersion": msbuild_attributes[a] = msvs_attributes[a] else: print("Warning: Do not know how to convert MSVS attribute " + a) return msbuild_attributes def _ConvertMSVSCharacterSet(char_set): if char_set.isdigit(): char_set = {"0": "MultiByte", "1": "Unicode", "2": "MultiByte"}[char_set] return char_set def _ConvertMSVSConfigurationType(config_type): if config_type.isdigit(): config_type = { "1": "Application", "2": "DynamicLibrary", "4": "StaticLibrary", "5": "Driver", "10": "Utility", }[config_type] return config_type def _GetMSBuildAttributes(spec, config, build_file): if "msbuild_configuration_attributes" not in config: msbuild_attributes = _ConvertMSVSBuildAttributes(spec, config, build_file) else: config_type = _GetMSVSConfigurationType(spec, build_file) config_type = _ConvertMSVSConfigurationType(config_type) msbuild_attributes = config.get("msbuild_configuration_attributes", {}) msbuild_attributes.setdefault("ConfigurationType", config_type) output_dir = msbuild_attributes.get( "OutputDirectory", "$(SolutionDir)$(Configuration)" ) msbuild_attributes["OutputDirectory"] = _FixPath(output_dir) + "\\" if "IntermediateDirectory" not in msbuild_attributes: intermediate = _FixPath("$(Configuration)") + "\\" msbuild_attributes["IntermediateDirectory"] = intermediate if "CharacterSet" in msbuild_attributes: msbuild_attributes["CharacterSet"] = _ConvertMSVSCharacterSet( msbuild_attributes["CharacterSet"] ) if "TargetName" not in msbuild_attributes: prefix = spec.get("product_prefix", "") product_name = spec.get("product_name", "$(ProjectName)") target_name = prefix + product_name msbuild_attributes["TargetName"] = target_name if "TargetExt" not in msbuild_attributes and "product_extension" in spec: ext = spec.get("product_extension") msbuild_attributes["TargetExt"] = "." + ext if spec.get("msvs_external_builder"): external_out_dir = spec.get("msvs_external_builder_out_dir", ".") msbuild_attributes["OutputDirectory"] = _FixPath(external_out_dir) + "\\" # Make sure that 'TargetPath' matches 'Lib.OutputFile' or 'Link.OutputFile' # (depending on the tool used) to avoid MSB8012 warning. msbuild_tool_map = { "executable": "Link", "shared_library": "Link", "loadable_module": "Link", "windows_driver": "Link", "static_library": "Lib", } msbuild_tool = msbuild_tool_map.get(spec["type"]) if msbuild_tool: msbuild_settings = config["finalized_msbuild_settings"] out_file = msbuild_settings[msbuild_tool].get("OutputFile") if out_file: msbuild_attributes["TargetPath"] = _FixPath(out_file) target_ext = msbuild_settings[msbuild_tool].get("TargetExt") if target_ext: msbuild_attributes["TargetExt"] = target_ext return msbuild_attributes def _GetMSBuildConfigurationGlobalProperties(spec, configurations, build_file): # TODO(jeanluc) We could optimize out the following and do it only if # there are actions. # TODO(jeanluc) Handle the equivalent of setting 'CYGWIN=nontsec'. new_paths = [] cygwin_dirs = spec.get("msvs_cygwin_dirs", ["."])[0] if cygwin_dirs: cyg_path = "$(MSBuildProjectDirectory)\\%s\\bin\\" % _FixPath(cygwin_dirs) new_paths.append(cyg_path) # TODO(jeanluc) Change the convention to have both a cygwin_dir and a # python_dir. python_path = cyg_path.replace("cygwin\\bin", "python_26") new_paths.append(python_path) if new_paths: new_paths = "$(ExecutablePath);" + ";".join(new_paths) properties = {} for (name, configuration) in sorted(configurations.items()): condition = _GetConfigurationCondition(name, configuration, spec) attributes = _GetMSBuildAttributes(spec, configuration, build_file) msbuild_settings = configuration["finalized_msbuild_settings"] _AddConditionalProperty( properties, condition, "IntDir", attributes["IntermediateDirectory"] ) _AddConditionalProperty( properties, condition, "OutDir", attributes["OutputDirectory"] ) _AddConditionalProperty( properties, condition, "TargetName", attributes["TargetName"] ) if "TargetExt" in attributes: _AddConditionalProperty( properties, condition, "TargetExt", attributes["TargetExt"] ) if attributes.get("TargetPath"): _AddConditionalProperty( properties, condition, "TargetPath", attributes["TargetPath"] ) if attributes.get("TargetExt"): _AddConditionalProperty( properties, condition, "TargetExt", attributes["TargetExt"] ) if new_paths: _AddConditionalProperty(properties, condition, "ExecutablePath", new_paths) tool_settings = msbuild_settings.get("", {}) for name, value in sorted(tool_settings.items()): formatted_value = _GetValueFormattedForMSBuild("", name, value) _AddConditionalProperty(properties, condition, name, formatted_value) return _GetMSBuildPropertyGroup(spec, None, properties) def _AddConditionalProperty(properties, condition, name, value): """Adds a property / conditional value pair to a dictionary. Arguments: properties: The dictionary to be modified. The key is the name of the property. The value is itself a dictionary; its key is the value and the value a list of condition for which this value is true. condition: The condition under which the named property has the value. name: The name of the property. value: The value of the property. """ if name not in properties: properties[name] = {} values = properties[name] if value not in values: values[value] = [] conditions = values[value] conditions.append(condition) # Regex for msvs variable references ( i.e. $(FOO) ). MSVS_VARIABLE_REFERENCE = re.compile(r"\$\(([a-zA-Z_][a-zA-Z0-9_]*)\)") def _GetMSBuildPropertyGroup(spec, label, properties): """Returns a PropertyGroup definition for the specified properties. Arguments: spec: The target project dict. label: An optional label for the PropertyGroup. properties: The dictionary to be converted. The key is the name of the property. The value is itself a dictionary; its key is the value and the value a list of condition for which this value is true. """ group = ["PropertyGroup"] if label: group.append({"Label": label}) num_configurations = len(spec["configurations"]) def GetEdges(node): # Use a definition of edges such that user_of_variable -> used_varible. # This happens to be easier in this case, since a variable's # definition contains all variables it references in a single string. edges = set() for value in sorted(properties[node].keys()): # Add to edges all $(...) references to variables. # # Variable references that refer to names not in properties are excluded # These can exist for instance to refer built in definitions like # $(SolutionDir). # # Self references are ignored. Self reference is used in a few places to # append to the default value. I.e. PATH=$(PATH);other_path edges.update( { v for v in MSVS_VARIABLE_REFERENCE.findall(value) if v in properties and v != node } ) return edges properties_ordered = gyp.common.TopologicallySorted(properties.keys(), GetEdges) # Walk properties in the reverse of a topological sort on # user_of_variable -> used_variable as this ensures variables are # defined before they are used. # NOTE: reverse(topsort(DAG)) = topsort(reverse_edges(DAG)) for name in reversed(properties_ordered): values = properties[name] for value, conditions in sorted(values.items()): if len(conditions) == num_configurations: # If the value is the same all configurations, # just add one unconditional entry. group.append([name, value]) else: for condition in conditions: group.append([name, {"Condition": condition}, value]) return [group] def _GetMSBuildToolSettingsSections(spec, configurations): groups = [] for (name, configuration) in sorted(configurations.items()): msbuild_settings = configuration["finalized_msbuild_settings"] group = [ "ItemDefinitionGroup", {"Condition": _GetConfigurationCondition(name, configuration, spec)}, ] for tool_name, tool_settings in sorted(msbuild_settings.items()): # Skip the tool named '' which is a holder of global settings handled # by _GetMSBuildConfigurationGlobalProperties. if tool_name and tool_settings: tool = [tool_name] for name, value in sorted(tool_settings.items()): formatted_value = _GetValueFormattedForMSBuild( tool_name, name, value ) tool.append([name, formatted_value]) group.append(tool) groups.append(group) return groups def _FinalizeMSBuildSettings(spec, configuration): if "msbuild_settings" in configuration: converted = False msbuild_settings = configuration["msbuild_settings"] MSVSSettings.ValidateMSBuildSettings(msbuild_settings) else: converted = True msvs_settings = configuration.get("msvs_settings", {}) msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(msvs_settings) include_dirs, midl_include_dirs, resource_include_dirs = _GetIncludeDirs( configuration ) libraries = _GetLibraries(spec) library_dirs = _GetLibraryDirs(configuration) out_file, _, msbuild_tool = _GetOutputFilePathAndTool(spec, msbuild=True) target_ext = _GetOutputTargetExt(spec) defines = _GetDefines(configuration) if converted: # Visual Studio 2010 has TR1 defines = [d for d in defines if d != "_HAS_TR1=0"] # Warn of ignored settings ignored_settings = ["msvs_tool_files"] for ignored_setting in ignored_settings: value = configuration.get(ignored_setting) if value: print( "Warning: The automatic conversion to MSBuild does not handle " "%s. Ignoring setting of %s" % (ignored_setting, str(value)) ) defines = [_EscapeCppDefineForMSBuild(d) for d in defines] disabled_warnings = _GetDisabledWarnings(configuration) prebuild = configuration.get("msvs_prebuild") postbuild = configuration.get("msvs_postbuild") def_file = _GetModuleDefinition(spec) precompiled_header = configuration.get("msvs_precompiled_header") # Add the information to the appropriate tool # TODO(jeanluc) We could optimize and generate these settings only if # the corresponding files are found, e.g. don't generate ResourceCompile # if you don't have any resources. _ToolAppend( msbuild_settings, "ClCompile", "AdditionalIncludeDirectories", include_dirs ) _ToolAppend( msbuild_settings, "Midl", "AdditionalIncludeDirectories", midl_include_dirs ) _ToolAppend( msbuild_settings, "ResourceCompile", "AdditionalIncludeDirectories", resource_include_dirs, ) # Add in libraries, note that even for empty libraries, we want this # set, to prevent inheriting default libraries from the environment. _ToolSetOrAppend(msbuild_settings, "Link", "AdditionalDependencies", libraries) _ToolAppend(msbuild_settings, "Link", "AdditionalLibraryDirectories", library_dirs) if out_file: _ToolAppend( msbuild_settings, msbuild_tool, "OutputFile", out_file, only_if_unset=True ) if target_ext: _ToolAppend( msbuild_settings, msbuild_tool, "TargetExt", target_ext, only_if_unset=True ) # Add defines. _ToolAppend(msbuild_settings, "ClCompile", "PreprocessorDefinitions", defines) _ToolAppend(msbuild_settings, "ResourceCompile", "PreprocessorDefinitions", defines) # Add disabled warnings. _ToolAppend( msbuild_settings, "ClCompile", "DisableSpecificWarnings", disabled_warnings ) # Turn on precompiled headers if appropriate. if precompiled_header: precompiled_header = os.path.split(precompiled_header)[1] _ToolAppend(msbuild_settings, "ClCompile", "PrecompiledHeader", "Use") _ToolAppend( msbuild_settings, "ClCompile", "PrecompiledHeaderFile", precompiled_header ) _ToolAppend( msbuild_settings, "ClCompile", "ForcedIncludeFiles", [precompiled_header] ) else: _ToolAppend(msbuild_settings, "ClCompile", "PrecompiledHeader", "NotUsing") # Turn off WinRT compilation _ToolAppend(msbuild_settings, "ClCompile", "CompileAsWinRT", "false") # Turn on import libraries if appropriate if spec.get("msvs_requires_importlibrary"): _ToolAppend(msbuild_settings, "", "IgnoreImportLibrary", "false") # Loadable modules don't generate import libraries; # tell dependent projects to not expect one. if spec["type"] == "loadable_module": _ToolAppend(msbuild_settings, "", "IgnoreImportLibrary", "true") # Set the module definition file if any. if def_file: _ToolAppend(msbuild_settings, "Link", "ModuleDefinitionFile", def_file) configuration["finalized_msbuild_settings"] = msbuild_settings if prebuild: _ToolAppend(msbuild_settings, "PreBuildEvent", "Command", prebuild) if postbuild: _ToolAppend(msbuild_settings, "PostBuildEvent", "Command", postbuild) def _GetValueFormattedForMSBuild(tool_name, name, value): if type(value) == list: # For some settings, VS2010 does not automatically extends the settings # TODO(jeanluc) Is this what we want? if name in [ "AdditionalIncludeDirectories", "AdditionalLibraryDirectories", "AdditionalOptions", "DelayLoadDLLs", "DisableSpecificWarnings", "PreprocessorDefinitions", ]: value.append("%%(%s)" % name) # For most tools, entries in a list should be separated with ';' but some # settings use a space. Check for those first. exceptions = { "ClCompile": ["AdditionalOptions"], "Link": ["AdditionalOptions"], "Lib": ["AdditionalOptions"], } char = " " if name in exceptions.get(tool_name, []) else ";" formatted_value = char.join( [MSVSSettings.ConvertVCMacrosToMSBuild(i) for i in value] ) else: formatted_value = MSVSSettings.ConvertVCMacrosToMSBuild(value) return formatted_value def _VerifySourcesExist(sources, root_dir): """Verifies that all source files exist on disk. Checks that all regular source files, i.e. not created at run time, exist on disk. Missing files cause needless recompilation but no otherwise visible errors. Arguments: sources: A recursive list of Filter/file names. root_dir: The root directory for the relative path names. Returns: A list of source files that cannot be found on disk. """ missing_sources = [] for source in sources: if isinstance(source, MSVSProject.Filter): missing_sources.extend(_VerifySourcesExist(source.contents, root_dir)) else: if "$" not in source: full_path = os.path.join(root_dir, source) if not os.path.exists(full_path): missing_sources.append(full_path) return missing_sources def _GetMSBuildSources( spec, sources, exclusions, rule_dependencies, extension_to_rule_name, actions_spec, sources_handled_by_action, list_excluded, ): groups = [ "none", "masm", "midl", "include", "compile", "resource", "rule", "rule_dependency", ] grouped_sources = {} for g in groups: grouped_sources[g] = [] _AddSources2( spec, sources, exclusions, grouped_sources, rule_dependencies, extension_to_rule_name, sources_handled_by_action, list_excluded, ) sources = [] for g in groups: if grouped_sources[g]: sources.append(["ItemGroup"] + grouped_sources[g]) if actions_spec: sources.append(["ItemGroup"] + actions_spec) return sources def _AddSources2( spec, sources, exclusions, grouped_sources, rule_dependencies, extension_to_rule_name, sources_handled_by_action, list_excluded, ): extensions_excluded_from_precompile = [] for source in sources: if isinstance(source, MSVSProject.Filter): _AddSources2( spec, source.contents, exclusions, grouped_sources, rule_dependencies, extension_to_rule_name, sources_handled_by_action, list_excluded, ) else: if source not in sources_handled_by_action: detail = [] excluded_configurations = exclusions.get(source, []) if len(excluded_configurations) == len(spec["configurations"]): detail.append(["ExcludedFromBuild", "true"]) else: for config_name, configuration in sorted(excluded_configurations): condition = _GetConfigurationCondition( config_name, configuration ) detail.append( ["ExcludedFromBuild", {"Condition": condition}, "true"] ) # Add precompile if needed for config_name, configuration in spec["configurations"].items(): precompiled_source = configuration.get( "msvs_precompiled_source", "" ) if precompiled_source != "": precompiled_source = _FixPath(precompiled_source) if not extensions_excluded_from_precompile: # If the precompiled header is generated by a C source, # we must not try to use it for C++ sources, # and vice versa. basename, extension = os.path.splitext(precompiled_source) if extension == ".c": extensions_excluded_from_precompile = [ ".cc", ".cpp", ".cxx", ] else: extensions_excluded_from_precompile = [".c"] if precompiled_source == source: condition = _GetConfigurationCondition( config_name, configuration, spec ) detail.append( ["PrecompiledHeader", {"Condition": condition}, "Create"] ) else: # Turn off precompiled header usage for source files of a # different type than the file that generated the # precompiled header. for extension in extensions_excluded_from_precompile: if source.endswith(extension): detail.append(["PrecompiledHeader", ""]) detail.append(["ForcedIncludeFiles", ""]) group, element = _MapFileToMsBuildSourceType( source, rule_dependencies, extension_to_rule_name, _GetUniquePlatforms(spec), spec["toolset"], ) if group == "compile" and not os.path.isabs(source): # Add an value to support duplicate source # file basenames, except for absolute paths to avoid paths # with more than 260 characters. file_name = os.path.splitext(source)[0] + ".obj" if file_name.startswith("..\\"): file_name = re.sub(r"^(\.\.\\)+", "", file_name) elif file_name.startswith("$("): file_name = re.sub(r"^\$\([^)]+\)\\", "", file_name) detail.append(["ObjectFileName", "$(IntDir)\\" + file_name]) grouped_sources[group].append([element, {"Include": source}] + detail) def _GetMSBuildProjectReferences(project): references = [] if project.dependencies: group = ["ItemGroup"] added_dependency_set = set() for dependency in project.dependencies: dependency_spec = dependency.spec should_skip_dep = False if project.spec["toolset"] == "target": if dependency_spec["toolset"] == "host": if dependency_spec["type"] == "static_library": should_skip_dep = True if dependency.name.startswith("run_"): should_skip_dep = False if should_skip_dep: continue canonical_name = dependency.name.replace("_host", "") added_dependency_set.add(canonical_name) guid = dependency.guid project_dir = os.path.split(project.path)[0] relative_path = gyp.common.RelativePath(dependency.path, project_dir) project_ref = [ "ProjectReference", {"Include": relative_path}, ["Project", guid], ["ReferenceOutputAssembly", "false"], ] for config in dependency.spec.get("configurations", {}).values(): if config.get("msvs_use_library_dependency_inputs", 0): project_ref.append(["UseLibraryDependencyInputs", "true"]) break # If it's disabled in any config, turn it off in the reference. if config.get("msvs_2010_disable_uldi_when_referenced", 0): project_ref.append(["UseLibraryDependencyInputs", "false"]) break group.append(project_ref) references.append(group) return references def _GenerateMSBuildProject(project, options, version, generator_flags, spec): spec = project.spec configurations = spec["configurations"] toolset = spec["toolset"] project_dir, project_file_name = os.path.split(project.path) gyp.common.EnsureDirExists(project.path) # Prepare list of sources and excluded sources. gyp_file = os.path.split(project.build_file)[1] sources, excluded_sources = _PrepareListOfSources(spec, generator_flags, gyp_file) # Add rules. actions_to_add = {} props_files_of_rules = set() targets_files_of_rules = set() rule_dependencies = set() extension_to_rule_name = {} list_excluded = generator_flags.get("msvs_list_excluded_files", True) platforms = _GetUniquePlatforms(spec) # Don't generate rules if we are using an external builder like ninja. if not spec.get("msvs_external_builder"): _GenerateRulesForMSBuild( project_dir, options, spec, sources, excluded_sources, props_files_of_rules, targets_files_of_rules, actions_to_add, rule_dependencies, extension_to_rule_name, ) else: rules = spec.get("rules", []) _AdjustSourcesForRules(rules, sources, excluded_sources, True) sources, excluded_sources, excluded_idl = _AdjustSourcesAndConvertToFilterHierarchy( spec, options, project_dir, sources, excluded_sources, list_excluded, version ) # Don't add actions if we are using an external builder like ninja. if not spec.get("msvs_external_builder"): _AddActions(actions_to_add, spec, project.build_file) _AddCopies(actions_to_add, spec) # NOTE: this stanza must appear after all actions have been decided. # Don't excluded sources with actions attached, or they won't run. excluded_sources = _FilterActionsFromExcluded(excluded_sources, actions_to_add) exclusions = _GetExcludedFilesFromBuild(spec, excluded_sources, excluded_idl) actions_spec, sources_handled_by_action = _GenerateActionsForMSBuild( spec, actions_to_add ) _GenerateMSBuildFiltersFile( project.path + ".filters", sources, rule_dependencies, extension_to_rule_name, platforms, toolset, ) missing_sources = _VerifySourcesExist(sources, project_dir) for configuration in configurations.values(): _FinalizeMSBuildSettings(spec, configuration) # Add attributes to root element import_default_section = [ ["Import", {"Project": r"$(VCTargetsPath)\Microsoft.Cpp.Default.props"}] ] import_cpp_props_section = [ ["Import", {"Project": r"$(VCTargetsPath)\Microsoft.Cpp.props"}] ] import_cpp_targets_section = [ ["Import", {"Project": r"$(VCTargetsPath)\Microsoft.Cpp.targets"}] ] import_masm_props_section = [ ["Import", {"Project": r"$(VCTargetsPath)\BuildCustomizations\masm.props"}] ] import_masm_targets_section = [ ["Import", {"Project": r"$(VCTargetsPath)\BuildCustomizations\masm.targets"}] ] import_marmasm_props_section = [ ["Import", {"Project": r"$(VCTargetsPath)\BuildCustomizations\marmasm.props"}] ] import_marmasm_targets_section = [ ["Import", {"Project": r"$(VCTargetsPath)\BuildCustomizations\marmasm.targets"}] ] macro_section = [["PropertyGroup", {"Label": "UserMacros"}]] content = [ "Project", { "xmlns": "http://schemas.microsoft.com/developer/msbuild/2003", "ToolsVersion": version.ProjectVersion(), "DefaultTargets": "Build", }, ] content += _GetMSBuildProjectConfigurations(configurations, spec) content += _GetMSBuildGlobalProperties( spec, version, project.guid, project_file_name ) content += import_default_section content += _GetMSBuildConfigurationDetails(spec, project.build_file) if spec.get("msvs_enable_winphone"): content += _GetMSBuildLocalProperties("v120_wp81") else: content += _GetMSBuildLocalProperties(project.msbuild_toolset) content += import_cpp_props_section content += import_masm_props_section if "arm64" in platforms and toolset == "target": content += import_marmasm_props_section content += _GetMSBuildExtensions(props_files_of_rules) content += _GetMSBuildPropertySheets(configurations, spec) content += macro_section content += _GetMSBuildConfigurationGlobalProperties( spec, configurations, project.build_file ) content += _GetMSBuildToolSettingsSections(spec, configurations) content += _GetMSBuildSources( spec, sources, exclusions, rule_dependencies, extension_to_rule_name, actions_spec, sources_handled_by_action, list_excluded, ) content += _GetMSBuildProjectReferences(project) content += import_cpp_targets_section content += import_masm_targets_section if "arm64" in platforms and toolset == "target": content += import_marmasm_targets_section content += _GetMSBuildExtensionTargets(targets_files_of_rules) if spec.get("msvs_external_builder"): content += _GetMSBuildExternalBuilderTargets(spec) # TODO(jeanluc) File a bug to get rid of runas. We had in MSVS: # has_run_as = _WriteMSVSUserFile(project.path, version, spec) easy_xml.WriteXmlIfChanged(content, project.path, pretty=True, win32=True) return missing_sources def _GetMSBuildExternalBuilderTargets(spec): """Return a list of MSBuild targets for external builders. The "Build" and "Clean" targets are always generated. If the spec contains 'msvs_external_builder_clcompile_cmd', then the "ClCompile" target will also be generated, to support building selected C/C++ files. Arguments: spec: The gyp target spec. Returns: List of MSBuild 'Target' specs. """ build_cmd = _BuildCommandLineForRuleRaw( spec, spec["msvs_external_builder_build_cmd"], False, False, False, False ) build_target = ["Target", {"Name": "Build"}] build_target.append(["Exec", {"Command": build_cmd}]) clean_cmd = _BuildCommandLineForRuleRaw( spec, spec["msvs_external_builder_clean_cmd"], False, False, False, False ) clean_target = ["Target", {"Name": "Clean"}] clean_target.append(["Exec", {"Command": clean_cmd}]) targets = [build_target, clean_target] if spec.get("msvs_external_builder_clcompile_cmd"): clcompile_cmd = _BuildCommandLineForRuleRaw( spec, spec["msvs_external_builder_clcompile_cmd"], False, False, False, False, ) clcompile_target = ["Target", {"Name": "ClCompile"}] clcompile_target.append(["Exec", {"Command": clcompile_cmd}]) targets.append(clcompile_target) return targets def _GetMSBuildExtensions(props_files_of_rules): extensions = ["ImportGroup", {"Label": "ExtensionSettings"}] for props_file in props_files_of_rules: extensions.append(["Import", {"Project": props_file}]) return [extensions] def _GetMSBuildExtensionTargets(targets_files_of_rules): targets_node = ["ImportGroup", {"Label": "ExtensionTargets"}] for targets_file in sorted(targets_files_of_rules): targets_node.append(["Import", {"Project": targets_file}]) return [targets_node] def _GenerateActionsForMSBuild(spec, actions_to_add): """Add actions accumulated into an actions_to_add, merging as needed. Arguments: spec: the target project dict actions_to_add: dictionary keyed on input name, which maps to a list of dicts describing the actions attached to that input file. Returns: A pair of (action specification, the sources handled by this action). """ sources_handled_by_action = OrderedSet() actions_spec = [] for primary_input, actions in actions_to_add.items(): if generator_supports_multiple_toolsets: primary_input = primary_input.replace(".exe", "_host.exe") inputs = OrderedSet() outputs = OrderedSet() descriptions = [] commands = [] for action in actions: def fixup_host_exe(i): if "$(OutDir)" in i: i = i.replace(".exe", "_host.exe") return i if generator_supports_multiple_toolsets: action["inputs"] = [fixup_host_exe(i) for i in action["inputs"]] inputs.update(OrderedSet(action["inputs"])) outputs.update(OrderedSet(action["outputs"])) descriptions.append(action["description"]) cmd = action["command"] if generator_supports_multiple_toolsets: cmd = cmd.replace(".exe", "_host.exe") # For most actions, add 'call' so that actions that invoke batch files # return and continue executing. msbuild_use_call provides a way to # disable this but I have not seen any adverse effect from doing that # for everything. if action.get("msbuild_use_call", True): cmd = "call " + cmd commands.append(cmd) # Add the custom build action for one input file. description = ", and also ".join(descriptions) # We can't join the commands simply with && because the command line will # get too long. See also _AddActions: cygwin's setup_env mustn't be called # for every invocation or the command that sets the PATH will grow too # long. command = "\r\n".join( [c + "\r\nif %errorlevel% neq 0 exit /b %errorlevel%" for c in commands] ) _AddMSBuildAction( spec, primary_input, inputs, outputs, command, description, sources_handled_by_action, actions_spec, ) return actions_spec, sources_handled_by_action def _AddMSBuildAction( spec, primary_input, inputs, outputs, cmd, description, sources_handled_by_action, actions_spec, ): command = MSVSSettings.ConvertVCMacrosToMSBuild(cmd) primary_input = _FixPath(primary_input) inputs_array = _FixPaths(inputs) outputs_array = _FixPaths(outputs) additional_inputs = ";".join([i for i in inputs_array if i != primary_input]) outputs = ";".join(outputs_array) sources_handled_by_action.add(primary_input) action_spec = ["CustomBuild", {"Include": primary_input}] action_spec.extend( # TODO(jeanluc) 'Document' for all or just if as_sources? [ ["FileType", "Document"], ["Command", command], ["Message", description], ["Outputs", outputs], ] ) if additional_inputs: action_spec.append(["AdditionalInputs", additional_inputs]) actions_spec.append(action_spec) PK ~\,-node-gyp/gyp/pylib/gyp/generator/msvs_test.pynu[#!/usr/bin/env python3 # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Unit tests for the msvs.py file. """ import gyp.generator.msvs as msvs import unittest from io import StringIO class TestSequenceFunctions(unittest.TestCase): def setUp(self): self.stderr = StringIO() def test_GetLibraries(self): self.assertEqual(msvs._GetLibraries({}), []) self.assertEqual(msvs._GetLibraries({"libraries": []}), []) self.assertEqual( msvs._GetLibraries({"other": "foo", "libraries": ["a.lib"]}), ["a.lib"] ) self.assertEqual(msvs._GetLibraries({"libraries": ["-la"]}), ["a.lib"]) self.assertEqual( msvs._GetLibraries( { "libraries": [ "a.lib", "b.lib", "c.lib", "-lb.lib", "-lb.lib", "d.lib", "a.lib", ] } ), ["c.lib", "b.lib", "d.lib", "a.lib"], ) if __name__ == "__main__": unittest.main() PK ~\.node-gyp/gyp/pylib/gyp/generator/xcode_test.pynu[#!/usr/bin/env python3 # Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Unit tests for the xcode.py file. """ import gyp.generator.xcode as xcode import unittest import sys class TestEscapeXcodeDefine(unittest.TestCase): if sys.platform == "darwin": def test_InheritedRemainsUnescaped(self): self.assertEqual(xcode.EscapeXcodeDefine("$(inherited)"), "$(inherited)") def test_Escaping(self): self.assertEqual(xcode.EscapeXcodeDefine('a b"c\\'), 'a\\ b\\"c\\\\') if __name__ == "__main__": unittest.main() PK ~\ vv.node-gyp/gyp/pylib/gyp/generator/ninja_test.pynu[#!/usr/bin/env python3 # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Unit tests for the ninja.py file. """ import sys import unittest import gyp.generator.ninja as ninja class TestPrefixesAndSuffixes(unittest.TestCase): def test_BinaryNamesWindows(self): # These cannot run on non-Windows as they require a VS installation to # correctly handle variable expansion. if sys.platform.startswith("win"): writer = ninja.NinjaWriter( "foo", "wee", ".", ".", "build.ninja", ".", "build.ninja", "win" ) spec = {"target_name": "wee"} self.assertTrue( writer.ComputeOutputFileName(spec, "executable").endswith(".exe") ) self.assertTrue( writer.ComputeOutputFileName(spec, "shared_library").endswith(".dll") ) self.assertTrue( writer.ComputeOutputFileName(spec, "static_library").endswith(".lib") ) def test_BinaryNamesLinux(self): writer = ninja.NinjaWriter( "foo", "wee", ".", ".", "build.ninja", ".", "build.ninja", "linux" ) spec = {"target_name": "wee"} self.assertTrue("." not in writer.ComputeOutputFileName(spec, "executable")) self.assertTrue( writer.ComputeOutputFileName(spec, "shared_library").startswith("lib") ) self.assertTrue( writer.ComputeOutputFileName(spec, "static_library").startswith("lib") ) self.assertTrue( writer.ComputeOutputFileName(spec, "shared_library").endswith(".so") ) self.assertTrue( writer.ComputeOutputFileName(spec, "static_library").endswith(".a") ) if __name__ == "__main__": unittest.main() PK ~\ ``9node-gyp/gyp/pylib/gyp/generator/compile_commands_json.pynu[# Copyright (c) 2016 Ben Noordhuis . All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import gyp.common import gyp.xcode_emulation import json import os generator_additional_non_configuration_keys = [] generator_additional_path_sections = [] generator_extra_sources_for_rules = [] generator_filelist_paths = None generator_supports_multiple_toolsets = True generator_wants_sorted_dependencies = False # Lifted from make.py. The actual values don't matter much. generator_default_variables = { "CONFIGURATION_NAME": "$(BUILDTYPE)", "EXECUTABLE_PREFIX": "", "EXECUTABLE_SUFFIX": "", "INTERMEDIATE_DIR": "$(obj).$(TOOLSET)/$(TARGET)/geni", "PRODUCT_DIR": "$(builddir)", "RULE_INPUT_DIRNAME": "%(INPUT_DIRNAME)s", "RULE_INPUT_EXT": "$(suffix $<)", "RULE_INPUT_NAME": "$(notdir $<)", "RULE_INPUT_PATH": "$(abspath $<)", "RULE_INPUT_ROOT": "%(INPUT_ROOT)s", "SHARED_INTERMEDIATE_DIR": "$(obj)/gen", "SHARED_LIB_PREFIX": "lib", "STATIC_LIB_PREFIX": "lib", "STATIC_LIB_SUFFIX": ".a", } def IsMac(params): return gyp.common.GetFlavor(params) == "mac" def CalculateVariables(default_variables, params): default_variables.setdefault("OS", gyp.common.GetFlavor(params)) def AddCommandsForTarget(cwd, target, params, per_config_commands): output_dir = params["generator_flags"].get("output_dir", "out") for configuration_name, configuration in target["configurations"].items(): if IsMac(params): xcode_settings = gyp.xcode_emulation.XcodeSettings(target) cflags = xcode_settings.GetCflags(configuration_name) cflags_c = xcode_settings.GetCflagsC(configuration_name) cflags_cc = xcode_settings.GetCflagsCC(configuration_name) else: cflags = configuration.get("cflags", []) cflags_c = configuration.get("cflags_c", []) cflags_cc = configuration.get("cflags_cc", []) cflags_c = cflags + cflags_c cflags_cc = cflags + cflags_cc defines = configuration.get("defines", []) defines = ["-D" + s for s in defines] # TODO(bnoordhuis) Handle generated source files. extensions = (".c", ".cc", ".cpp", ".cxx") sources = [s for s in target.get("sources", []) if s.endswith(extensions)] def resolve(filename): return os.path.abspath(os.path.join(cwd, filename)) # TODO(bnoordhuis) Handle generated header files. include_dirs = configuration.get("include_dirs", []) include_dirs = [s for s in include_dirs if not s.startswith("$(obj)")] includes = ["-I" + resolve(s) for s in include_dirs] defines = gyp.common.EncodePOSIXShellList(defines) includes = gyp.common.EncodePOSIXShellList(includes) cflags_c = gyp.common.EncodePOSIXShellList(cflags_c) cflags_cc = gyp.common.EncodePOSIXShellList(cflags_cc) commands = per_config_commands.setdefault(configuration_name, []) for source in sources: file = resolve(source) isc = source.endswith(".c") cc = "cc" if isc else "c++" cflags = cflags_c if isc else cflags_cc command = " ".join( ( cc, defines, includes, cflags, "-c", gyp.common.EncodePOSIXShellArgument(file), ) ) commands.append({"command": command, "directory": output_dir, "file": file}) def GenerateOutput(target_list, target_dicts, data, params): per_config_commands = {} for qualified_target, target in target_dicts.items(): build_file, target_name, toolset = gyp.common.ParseQualifiedTarget( qualified_target ) if IsMac(params): settings = data[build_file] gyp.xcode_emulation.MergeGlobalXcodeSettingsToSpec(settings, target) cwd = os.path.dirname(build_file) AddCommandsForTarget(cwd, target, params, per_config_commands) try: output_dir = params["options"].generator_output except (AttributeError, KeyError): output_dir = params["generator_flags"].get("output_dir", "out") for configuration_name, commands in per_config_commands.items(): filename = os.path.join(output_dir, configuration_name, "compile_commands.json") gyp.common.EnsureDirExists(filename) fp = open(filename, "w") json.dump(commands, fp=fp, indent=0, check_circular=False) def PerformBuild(data, configurations, params): pass PK ~\])node-gyp/gyp/pylib/gyp/generator/xcode.pynu[# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import filecmp import gyp.common import gyp.xcodeproj_file import gyp.xcode_ninja import errno import os import sys import posixpath import re import shutil import subprocess import tempfile # Project files generated by this module will use _intermediate_var as a # custom Xcode setting whose value is a DerivedSources-like directory that's # project-specific and configuration-specific. The normal choice, # DERIVED_FILE_DIR, is target-specific, which is thought to be too restrictive # as it is likely that multiple targets within a single project file will want # to access the same set of generated files. The other option, # PROJECT_DERIVED_FILE_DIR, is unsuitable because while it is project-specific, # it is not configuration-specific. INTERMEDIATE_DIR is defined as # $(PROJECT_DERIVED_FILE_DIR)/$(CONFIGURATION). _intermediate_var = "INTERMEDIATE_DIR" # SHARED_INTERMEDIATE_DIR is the same, except that it is shared among all # targets that share the same BUILT_PRODUCTS_DIR. _shared_intermediate_var = "SHARED_INTERMEDIATE_DIR" _library_search_paths_var = "LIBRARY_SEARCH_PATHS" generator_default_variables = { "EXECUTABLE_PREFIX": "", "EXECUTABLE_SUFFIX": "", "STATIC_LIB_PREFIX": "lib", "SHARED_LIB_PREFIX": "lib", "STATIC_LIB_SUFFIX": ".a", "SHARED_LIB_SUFFIX": ".dylib", # INTERMEDIATE_DIR is a place for targets to build up intermediate products. # It is specific to each build environment. It is only guaranteed to exist # and be constant within the context of a project, corresponding to a single # input file. Some build environments may allow their intermediate directory # to be shared on a wider scale, but this is not guaranteed. "INTERMEDIATE_DIR": "$(%s)" % _intermediate_var, "OS": "mac", "PRODUCT_DIR": "$(BUILT_PRODUCTS_DIR)", "LIB_DIR": "$(BUILT_PRODUCTS_DIR)", "RULE_INPUT_ROOT": "$(INPUT_FILE_BASE)", "RULE_INPUT_EXT": "$(INPUT_FILE_SUFFIX)", "RULE_INPUT_NAME": "$(INPUT_FILE_NAME)", "RULE_INPUT_PATH": "$(INPUT_FILE_PATH)", "RULE_INPUT_DIRNAME": "$(INPUT_FILE_DIRNAME)", "SHARED_INTERMEDIATE_DIR": "$(%s)" % _shared_intermediate_var, "CONFIGURATION_NAME": "$(CONFIGURATION)", } # The Xcode-specific sections that hold paths. generator_additional_path_sections = [ "mac_bundle_resources", "mac_framework_headers", "mac_framework_private_headers", # 'mac_framework_dirs', input already handles _dirs endings. ] # The Xcode-specific keys that exist on targets and aren't moved down to # configurations. generator_additional_non_configuration_keys = [ "ios_app_extension", "ios_watch_app", "ios_watchkit_extension", "mac_bundle", "mac_bundle_resources", "mac_framework_headers", "mac_framework_private_headers", "mac_xctest_bundle", "mac_xcuitest_bundle", "xcode_create_dependents_test_runner", ] # We want to let any rules apply to files that are resources also. generator_extra_sources_for_rules = [ "mac_bundle_resources", "mac_framework_headers", "mac_framework_private_headers", ] generator_filelist_paths = None # Xcode's standard set of library directories, which don't need to be duplicated # in LIBRARY_SEARCH_PATHS. This list is not exhaustive, but that's okay. xcode_standard_library_dirs = frozenset( ["$(SDKROOT)/usr/lib", "$(SDKROOT)/usr/local/lib"] ) def CreateXCConfigurationList(configuration_names): xccl = gyp.xcodeproj_file.XCConfigurationList({"buildConfigurations": []}) if len(configuration_names) == 0: configuration_names = ["Default"] for configuration_name in configuration_names: xcbc = gyp.xcodeproj_file.XCBuildConfiguration({"name": configuration_name}) xccl.AppendProperty("buildConfigurations", xcbc) xccl.SetProperty("defaultConfigurationName", configuration_names[0]) return xccl class XcodeProject: def __init__(self, gyp_path, path, build_file_dict): self.gyp_path = gyp_path self.path = path self.project = gyp.xcodeproj_file.PBXProject(path=path) projectDirPath = gyp.common.RelativePath( os.path.dirname(os.path.abspath(self.gyp_path)), os.path.dirname(path) or ".", ) self.project.SetProperty("projectDirPath", projectDirPath) self.project_file = gyp.xcodeproj_file.XCProjectFile( {"rootObject": self.project} ) self.build_file_dict = build_file_dict # TODO(mark): add destructor that cleans up self.path if created_dir is # True and things didn't complete successfully. Or do something even # better with "try"? self.created_dir = False try: os.makedirs(self.path) self.created_dir = True except OSError as e: if e.errno != errno.EEXIST: raise def Finalize1(self, xcode_targets, serialize_all_tests): # Collect a list of all of the build configuration names used by the # various targets in the file. It is very heavily advised to keep each # target in an entire project (even across multiple project files) using # the same set of configuration names. configurations = [] for xct in self.project.GetProperty("targets"): xccl = xct.GetProperty("buildConfigurationList") xcbcs = xccl.GetProperty("buildConfigurations") for xcbc in xcbcs: name = xcbc.GetProperty("name") if name not in configurations: configurations.append(name) # Replace the XCConfigurationList attached to the PBXProject object with # a new one specifying all of the configuration names used by the various # targets. try: xccl = CreateXCConfigurationList(configurations) self.project.SetProperty("buildConfigurationList", xccl) except Exception: sys.stderr.write("Problem with gyp file %s\n" % self.gyp_path) raise # The need for this setting is explained above where _intermediate_var is # defined. The comments below about wanting to avoid project-wide build # settings apply here too, but this needs to be set on a project-wide basis # so that files relative to the _intermediate_var setting can be displayed # properly in the Xcode UI. # # Note that for configuration-relative files such as anything relative to # _intermediate_var, for the purposes of UI tree view display, Xcode will # only resolve the configuration name once, when the project file is # opened. If the active build configuration is changed, the project file # must be closed and reopened if it is desired for the tree view to update. # This is filed as Apple radar 6588391. xccl.SetBuildSetting( _intermediate_var, "$(PROJECT_DERIVED_FILE_DIR)/$(CONFIGURATION)" ) xccl.SetBuildSetting( _shared_intermediate_var, "$(SYMROOT)/DerivedSources/$(CONFIGURATION)" ) # Set user-specified project-wide build settings and config files. This # is intended to be used very sparingly. Really, almost everything should # go into target-specific build settings sections. The project-wide # settings are only intended to be used in cases where Xcode attempts to # resolve variable references in a project context as opposed to a target # context, such as when resolving sourceTree references while building up # the tree tree view for UI display. # Any values set globally are applied to all configurations, then any # per-configuration values are applied. for xck, xcv in self.build_file_dict.get("xcode_settings", {}).items(): xccl.SetBuildSetting(xck, xcv) if "xcode_config_file" in self.build_file_dict: config_ref = self.project.AddOrGetFileInRootGroup( self.build_file_dict["xcode_config_file"] ) xccl.SetBaseConfiguration(config_ref) build_file_configurations = self.build_file_dict.get("configurations", {}) if build_file_configurations: for config_name in configurations: build_file_configuration_named = build_file_configurations.get( config_name, {} ) if build_file_configuration_named: xcc = xccl.ConfigurationNamed(config_name) for xck, xcv in build_file_configuration_named.get( "xcode_settings", {} ).items(): xcc.SetBuildSetting(xck, xcv) if "xcode_config_file" in build_file_configuration_named: config_ref = self.project.AddOrGetFileInRootGroup( build_file_configurations[config_name]["xcode_config_file"] ) xcc.SetBaseConfiguration(config_ref) # Sort the targets based on how they appeared in the input. # TODO(mark): Like a lot of other things here, this assumes internal # knowledge of PBXProject - in this case, of its "targets" property. # ordinary_targets are ordinary targets that are already in the project # file. run_test_targets are the targets that run unittests and should be # used for the Run All Tests target. support_targets are the action/rule # targets used by GYP file targets, just kept for the assert check. ordinary_targets = [] run_test_targets = [] support_targets = [] # targets is full list of targets in the project. targets = [] # does the it define it's own "all"? has_custom_all = False # targets_for_all is the list of ordinary_targets that should be listed # in this project's "All" target. It includes each non_runtest_target # that does not have suppress_wildcard set. targets_for_all = [] for target in self.build_file_dict["targets"]: target_name = target["target_name"] toolset = target["toolset"] qualified_target = gyp.common.QualifiedTarget( self.gyp_path, target_name, toolset ) xcode_target = xcode_targets[qualified_target] # Make sure that the target being added to the sorted list is already in # the unsorted list. assert xcode_target in self.project._properties["targets"] targets.append(xcode_target) ordinary_targets.append(xcode_target) if xcode_target.support_target: support_targets.append(xcode_target.support_target) targets.append(xcode_target.support_target) if not int(target.get("suppress_wildcard", False)): targets_for_all.append(xcode_target) if target_name.lower() == "all": has_custom_all = True # If this target has a 'run_as' attribute, add its target to the # targets, and add it to the test targets. if target.get("run_as"): # Make a target to run something. It should have one # dependency, the parent xcode target. xccl = CreateXCConfigurationList(configurations) run_target = gyp.xcodeproj_file.PBXAggregateTarget( { "name": "Run " + target_name, "productName": xcode_target.GetProperty("productName"), "buildConfigurationList": xccl, }, parent=self.project, ) run_target.AddDependency(xcode_target) command = target["run_as"] script = "" if command.get("working_directory"): script = ( script + 'cd "%s"\n' % gyp.xcodeproj_file.ConvertVariablesToShellSyntax( command.get("working_directory") ) ) if command.get("environment"): script = ( script + "\n".join( [ 'export %s="%s"' % ( key, gyp.xcodeproj_file.ConvertVariablesToShellSyntax( val ), ) for (key, val) in command.get("environment").items() ] ) + "\n" ) # Some test end up using sockets, files on disk, etc. and can get # confused if more then one test runs at a time. The generator # flag 'xcode_serialize_all_test_runs' controls the forcing of all # tests serially. It defaults to True. To get serial runs this # little bit of python does the same as the linux flock utility to # make sure only one runs at a time. command_prefix = "" if serialize_all_tests: command_prefix = """python -c "import fcntl, subprocess, sys file = open('$TMPDIR/GYP_serialize_test_runs', 'a') fcntl.flock(file.fileno(), fcntl.LOCK_EX) sys.exit(subprocess.call(sys.argv[1:]))" """ # If we were unable to exec for some reason, we want to exit # with an error, and fixup variable references to be shell # syntax instead of xcode syntax. script = ( script + "exec " + command_prefix + "%s\nexit 1\n" % gyp.xcodeproj_file.ConvertVariablesToShellSyntax( gyp.common.EncodePOSIXShellList(command.get("action")) ) ) ssbp = gyp.xcodeproj_file.PBXShellScriptBuildPhase( {"shellScript": script, "showEnvVarsInLog": 0} ) run_target.AppendProperty("buildPhases", ssbp) # Add the run target to the project file. targets.append(run_target) run_test_targets.append(run_target) xcode_target.test_runner = run_target # Make sure that the list of targets being replaced is the same length as # the one replacing it, but allow for the added test runner targets. assert len(self.project._properties["targets"]) == len(ordinary_targets) + len( support_targets ) self.project._properties["targets"] = targets # Get rid of unnecessary levels of depth in groups like the Source group. self.project.RootGroupsTakeOverOnlyChildren(True) # Sort the groups nicely. Do this after sorting the targets, because the # Products group is sorted based on the order of the targets. self.project.SortGroups() # Create an "All" target if there's more than one target in this project # file and the project didn't define its own "All" target. Put a generated # "All" target first so that people opening up the project for the first # time will build everything by default. if len(targets_for_all) > 1 and not has_custom_all: xccl = CreateXCConfigurationList(configurations) all_target = gyp.xcodeproj_file.PBXAggregateTarget( {"buildConfigurationList": xccl, "name": "All"}, parent=self.project ) for target in targets_for_all: all_target.AddDependency(target) # TODO(mark): This is evil because it relies on internal knowledge of # PBXProject._properties. It's important to get the "All" target first, # though. self.project._properties["targets"].insert(0, all_target) # The same, but for run_test_targets. if len(run_test_targets) > 1: xccl = CreateXCConfigurationList(configurations) run_all_tests_target = gyp.xcodeproj_file.PBXAggregateTarget( {"buildConfigurationList": xccl, "name": "Run All Tests"}, parent=self.project, ) for run_test_target in run_test_targets: run_all_tests_target.AddDependency(run_test_target) # Insert after the "All" target, which must exist if there is more than # one run_test_target. self.project._properties["targets"].insert(1, run_all_tests_target) def Finalize2(self, xcode_targets, xcode_target_to_target_dict): # Finalize2 needs to happen in a separate step because the process of # updating references to other projects depends on the ordering of targets # within remote project files. Finalize1 is responsible for sorting duty, # and once all project files are sorted, Finalize2 can come in and update # these references. # To support making a "test runner" target that will run all the tests # that are direct dependents of any given target, we look for # xcode_create_dependents_test_runner being set on an Aggregate target, # and generate a second target that will run the tests runners found under # the marked target. for bf_tgt in self.build_file_dict["targets"]: if int(bf_tgt.get("xcode_create_dependents_test_runner", 0)): tgt_name = bf_tgt["target_name"] toolset = bf_tgt["toolset"] qualified_target = gyp.common.QualifiedTarget( self.gyp_path, tgt_name, toolset ) xcode_target = xcode_targets[qualified_target] if isinstance(xcode_target, gyp.xcodeproj_file.PBXAggregateTarget): # Collect all the run test targets. all_run_tests = [] pbxtds = xcode_target.GetProperty("dependencies") for pbxtd in pbxtds: pbxcip = pbxtd.GetProperty("targetProxy") dependency_xct = pbxcip.GetProperty("remoteGlobalIDString") if hasattr(dependency_xct, "test_runner"): all_run_tests.append(dependency_xct.test_runner) # Directly depend on all the runners as they depend on the target # that builds them. if len(all_run_tests) > 0: run_all_target = gyp.xcodeproj_file.PBXAggregateTarget( { "name": "Run %s Tests" % tgt_name, "productName": tgt_name, }, parent=self.project, ) for run_test_target in all_run_tests: run_all_target.AddDependency(run_test_target) # Insert the test runner after the related target. idx = self.project._properties["targets"].index(xcode_target) self.project._properties["targets"].insert( idx + 1, run_all_target ) # Update all references to other projects, to make sure that the lists of # remote products are complete. Otherwise, Xcode will fill them in when # it opens the project file, which will result in unnecessary diffs. # TODO(mark): This is evil because it relies on internal knowledge of # PBXProject._other_pbxprojects. for other_pbxproject in self.project._other_pbxprojects: self.project.AddOrGetProjectReference(other_pbxproject) self.project.SortRemoteProductReferences() # Give everything an ID. self.project_file.ComputeIDs() # Make sure that no two objects in the project file have the same ID. If # multiple objects wind up with the same ID, upon loading the file, Xcode # will only recognize one object (the last one in the file?) and the # results are unpredictable. self.project_file.EnsureNoIDCollisions() def Write(self): # Write the project file to a temporary location first. Xcode watches for # changes to the project file and presents a UI sheet offering to reload # the project when it does change. However, in some cases, especially when # multiple projects are open or when Xcode is busy, things don't work so # seamlessly. Sometimes, Xcode is able to detect that a project file has # changed but can't unload it because something else is referencing it. # To mitigate this problem, and to avoid even having Xcode present the UI # sheet when an open project is rewritten for inconsequential changes, the # project file is written to a temporary file in the xcodeproj directory # first. The new temporary file is then compared to the existing project # file, if any. If they differ, the new file replaces the old; otherwise, # the new project file is simply deleted. Xcode properly detects a file # being renamed over an open project file as a change and so it remains # able to present the "project file changed" sheet under this system. # Writing to a temporary file first also avoids the possible problem of # Xcode rereading an incomplete project file. (output_fd, new_pbxproj_path) = tempfile.mkstemp( suffix=".tmp", prefix="project.pbxproj.gyp.", dir=self.path ) try: output_file = os.fdopen(output_fd, "w") self.project_file.Print(output_file) output_file.close() pbxproj_path = os.path.join(self.path, "project.pbxproj") same = False try: same = filecmp.cmp(pbxproj_path, new_pbxproj_path, False) except OSError as e: if e.errno != errno.ENOENT: raise if same: # The new file is identical to the old one, just get rid of the new # one. os.unlink(new_pbxproj_path) else: # The new file is different from the old one, or there is no old one. # Rename the new file to the permanent name. # # tempfile.mkstemp uses an overly restrictive mode, resulting in a # file that can only be read by the owner, regardless of the umask. # There's no reason to not respect the umask here, which means that # an extra hoop is required to fetch it and reset the new file's mode. # # No way to get the umask without setting a new one? Set a safe one # and then set it back to the old value. umask = os.umask(0o77) os.umask(umask) os.chmod(new_pbxproj_path, 0o666 & ~umask) os.rename(new_pbxproj_path, pbxproj_path) except Exception: # Don't leave turds behind. In fact, if this code was responsible for # creating the xcodeproj directory, get rid of that too. os.unlink(new_pbxproj_path) if self.created_dir: shutil.rmtree(self.path, True) raise def AddSourceToTarget(source, type, pbxp, xct): # TODO(mark): Perhaps source_extensions and library_extensions can be made a # little bit fancier. source_extensions = ["c", "cc", "cpp", "cxx", "m", "mm", "s", "swift"] # .o is conceptually more of a "source" than a "library," but Xcode thinks # of "sources" as things to compile and "libraries" (or "frameworks") as # things to link with. Adding an object file to an Xcode target's frameworks # phase works properly. library_extensions = ["a", "dylib", "framework", "o"] basename = posixpath.basename(source) (root, ext) = posixpath.splitext(basename) if ext: ext = ext[1:].lower() if ext in source_extensions and type != "none": xct.SourcesPhase().AddFile(source) elif ext in library_extensions and type != "none": xct.FrameworksPhase().AddFile(source) else: # Files that aren't added to a sources or frameworks build phase can still # go into the project file, just not as part of a build phase. pbxp.AddOrGetFileInRootGroup(source) def AddResourceToTarget(resource, pbxp, xct): # TODO(mark): Combine with AddSourceToTarget above? Or just inline this call # where it's used. xct.ResourcesPhase().AddFile(resource) def AddHeaderToTarget(header, pbxp, xct, is_public): # TODO(mark): Combine with AddSourceToTarget above? Or just inline this call # where it's used. settings = "{ATTRIBUTES = (%s, ); }" % ("Private", "Public")[is_public] xct.HeadersPhase().AddFile(header, settings) _xcode_variable_re = re.compile(r"(\$\((.*?)\))") def ExpandXcodeVariables(string, expansions): """Expands Xcode-style $(VARIABLES) in string per the expansions dict. In some rare cases, it is appropriate to expand Xcode variables when a project file is generated. For any substring $(VAR) in string, if VAR is a key in the expansions dict, $(VAR) will be replaced with expansions[VAR]. Any $(VAR) substring in string for which VAR is not a key in the expansions dict will remain in the returned string. """ matches = _xcode_variable_re.findall(string) if matches is None: return string matches.reverse() for match in matches: (to_replace, variable) = match if variable not in expansions: continue replacement = expansions[variable] string = re.sub(re.escape(to_replace), replacement, string) return string _xcode_define_re = re.compile(r"([\\\"\' ])") def EscapeXcodeDefine(s): """We must escape the defines that we give to XCode so that it knows not to split on spaces and to respect backslash and quote literals. However, we must not quote the define, or Xcode will incorrectly interpret variables especially $(inherited).""" return re.sub(_xcode_define_re, r"\\\1", s) def PerformBuild(data, configurations, params): options = params["options"] for build_file, build_file_dict in data.items(): (build_file_root, build_file_ext) = os.path.splitext(build_file) if build_file_ext != ".gyp": continue xcodeproj_path = build_file_root + options.suffix + ".xcodeproj" if options.generator_output: xcodeproj_path = os.path.join(options.generator_output, xcodeproj_path) for config in configurations: arguments = ["xcodebuild", "-project", xcodeproj_path] arguments += ["-configuration", config] print(f"Building [{config}]: {arguments}") subprocess.check_call(arguments) def CalculateGeneratorInputInfo(params): toplevel = params["options"].toplevel_dir if params.get("flavor") == "ninja": generator_dir = os.path.relpath(params["options"].generator_output or ".") output_dir = params.get("generator_flags", {}).get("output_dir", "out") output_dir = os.path.normpath(os.path.join(generator_dir, output_dir)) qualified_out_dir = os.path.normpath( os.path.join(toplevel, output_dir, "gypfiles-xcode-ninja") ) else: output_dir = os.path.normpath(os.path.join(toplevel, "xcodebuild")) qualified_out_dir = os.path.normpath( os.path.join(toplevel, output_dir, "gypfiles") ) global generator_filelist_paths generator_filelist_paths = { "toplevel": toplevel, "qualified_out_dir": qualified_out_dir, } def GenerateOutput(target_list, target_dicts, data, params): # Optionally configure each spec to use ninja as the external builder. ninja_wrapper = params.get("flavor") == "ninja" if ninja_wrapper: (target_list, target_dicts, data) = gyp.xcode_ninja.CreateWrapper( target_list, target_dicts, data, params ) options = params["options"] generator_flags = params.get("generator_flags", {}) parallel_builds = generator_flags.get("xcode_parallel_builds", True) serialize_all_tests = generator_flags.get("xcode_serialize_all_test_runs", True) upgrade_check_project_version = generator_flags.get( "xcode_upgrade_check_project_version", None ) # Format upgrade_check_project_version with leading zeros as needed. if upgrade_check_project_version: upgrade_check_project_version = str(upgrade_check_project_version) while len(upgrade_check_project_version) < 4: upgrade_check_project_version = "0" + upgrade_check_project_version skip_excluded_files = not generator_flags.get("xcode_list_excluded_files", True) xcode_projects = {} for build_file, build_file_dict in data.items(): (build_file_root, build_file_ext) = os.path.splitext(build_file) if build_file_ext != ".gyp": continue xcodeproj_path = build_file_root + options.suffix + ".xcodeproj" if options.generator_output: xcodeproj_path = os.path.join(options.generator_output, xcodeproj_path) xcp = XcodeProject(build_file, xcodeproj_path, build_file_dict) xcode_projects[build_file] = xcp pbxp = xcp.project # Set project-level attributes from multiple options project_attributes = {} if parallel_builds: project_attributes["BuildIndependentTargetsInParallel"] = "YES" if upgrade_check_project_version: project_attributes["LastUpgradeCheck"] = upgrade_check_project_version project_attributes[ "LastTestingUpgradeCheck" ] = upgrade_check_project_version project_attributes["LastSwiftUpdateCheck"] = upgrade_check_project_version pbxp.SetProperty("attributes", project_attributes) # Add gyp/gypi files to project if not generator_flags.get("standalone"): main_group = pbxp.GetProperty("mainGroup") build_group = gyp.xcodeproj_file.PBXGroup({"name": "Build"}) main_group.AppendChild(build_group) for included_file in build_file_dict["included_files"]: build_group.AddOrGetFileByPath(included_file, False) xcode_targets = {} xcode_target_to_target_dict = {} for qualified_target in target_list: [build_file, target_name, toolset] = gyp.common.ParseQualifiedTarget( qualified_target ) spec = target_dicts[qualified_target] if spec["toolset"] != "target": raise Exception( "Multiple toolsets not supported in xcode build (target %s)" % qualified_target ) configuration_names = [spec["default_configuration"]] for configuration_name in sorted(spec["configurations"].keys()): if configuration_name not in configuration_names: configuration_names.append(configuration_name) xcp = xcode_projects[build_file] pbxp = xcp.project # Set up the configurations for the target according to the list of names # supplied. xccl = CreateXCConfigurationList(configuration_names) # Create an XCTarget subclass object for the target. The type with # "+bundle" appended will be used if the target has "mac_bundle" set. # loadable_modules not in a mac_bundle are mapped to # com.googlecode.gyp.xcode.bundle, a pseudo-type that xcode.py interprets # to create a single-file mh_bundle. _types = { "executable": "com.apple.product-type.tool", "loadable_module": "com.googlecode.gyp.xcode.bundle", "shared_library": "com.apple.product-type.library.dynamic", "static_library": "com.apple.product-type.library.static", "mac_kernel_extension": "com.apple.product-type.kernel-extension", "executable+bundle": "com.apple.product-type.application", "loadable_module+bundle": "com.apple.product-type.bundle", "loadable_module+xctest": "com.apple.product-type.bundle.unit-test", "loadable_module+xcuitest": "com.apple.product-type.bundle.ui-testing", "shared_library+bundle": "com.apple.product-type.framework", "executable+extension+bundle": "com.apple.product-type.app-extension", "executable+watch+extension+bundle": "com.apple.product-type.watchkit-extension", "executable+watch+bundle": "com.apple.product-type.application.watchapp", "mac_kernel_extension+bundle": "com.apple.product-type.kernel-extension", } target_properties = { "buildConfigurationList": xccl, "name": target_name, } type = spec["type"] is_xctest = int(spec.get("mac_xctest_bundle", 0)) is_xcuitest = int(spec.get("mac_xcuitest_bundle", 0)) is_bundle = int(spec.get("mac_bundle", 0)) or is_xctest is_app_extension = int(spec.get("ios_app_extension", 0)) is_watchkit_extension = int(spec.get("ios_watchkit_extension", 0)) is_watch_app = int(spec.get("ios_watch_app", 0)) if type != "none": type_bundle_key = type if is_xcuitest: type_bundle_key += "+xcuitest" assert type == "loadable_module", ( "mac_xcuitest_bundle targets must have type loadable_module " "(target %s)" % target_name ) elif is_xctest: type_bundle_key += "+xctest" assert type == "loadable_module", ( "mac_xctest_bundle targets must have type loadable_module " "(target %s)" % target_name ) elif is_app_extension: assert is_bundle, ( "ios_app_extension flag requires mac_bundle " "(target %s)" % target_name ) type_bundle_key += "+extension+bundle" elif is_watchkit_extension: assert is_bundle, ( "ios_watchkit_extension flag requires mac_bundle " "(target %s)" % target_name ) type_bundle_key += "+watch+extension+bundle" elif is_watch_app: assert is_bundle, ( "ios_watch_app flag requires mac_bundle " "(target %s)" % target_name ) type_bundle_key += "+watch+bundle" elif is_bundle: type_bundle_key += "+bundle" xctarget_type = gyp.xcodeproj_file.PBXNativeTarget try: target_properties["productType"] = _types[type_bundle_key] except KeyError as e: gyp.common.ExceptionAppend( e, "-- unknown product type while " "writing target %s" % target_name, ) raise else: xctarget_type = gyp.xcodeproj_file.PBXAggregateTarget assert not is_bundle, ( 'mac_bundle targets cannot have type none (target "%s")' % target_name ) assert not is_xcuitest, ( 'mac_xcuitest_bundle targets cannot have type none (target "%s")' % target_name ) assert not is_xctest, ( 'mac_xctest_bundle targets cannot have type none (target "%s")' % target_name ) target_product_name = spec.get("product_name") if target_product_name is not None: target_properties["productName"] = target_product_name xct = xctarget_type( target_properties, parent=pbxp, force_outdir=spec.get("product_dir"), force_prefix=spec.get("product_prefix"), force_extension=spec.get("product_extension"), ) pbxp.AppendProperty("targets", xct) xcode_targets[qualified_target] = xct xcode_target_to_target_dict[xct] = spec spec_actions = spec.get("actions", []) spec_rules = spec.get("rules", []) # Xcode has some "issues" with checking dependencies for the "Compile # sources" step with any source files/headers generated by actions/rules. # To work around this, if a target is building anything directly (not # type "none"), then a second target is used to run the GYP actions/rules # and is made a dependency of this target. This way the work is done # before the dependency checks for what should be recompiled. support_xct = None # The Xcode "issues" don't affect xcode-ninja builds, since the dependency # logic all happens in ninja. Don't bother creating the extra targets in # that case. if type != "none" and (spec_actions or spec_rules) and not ninja_wrapper: support_xccl = CreateXCConfigurationList(configuration_names) support_target_suffix = generator_flags.get( "support_target_suffix", " Support" ) support_target_properties = { "buildConfigurationList": support_xccl, "name": target_name + support_target_suffix, } if target_product_name: support_target_properties["productName"] = ( target_product_name + " Support" ) support_xct = gyp.xcodeproj_file.PBXAggregateTarget( support_target_properties, parent=pbxp ) pbxp.AppendProperty("targets", support_xct) xct.AddDependency(support_xct) # Hang the support target off the main target so it can be tested/found # by the generator during Finalize. xct.support_target = support_xct prebuild_index = 0 # Add custom shell script phases for "actions" sections. for action in spec_actions: # There's no need to write anything into the script to ensure that the # output directories already exist, because Xcode will look at the # declared outputs and automatically ensure that they exist for us. # Do we have a message to print when this action runs? message = action.get("message") if message: message = "echo note: " + gyp.common.EncodePOSIXShellArgument(message) else: message = "" # Turn the list into a string that can be passed to a shell. action_string = gyp.common.EncodePOSIXShellList(action["action"]) # Convert Xcode-type variable references to sh-compatible environment # variable references. message_sh = gyp.xcodeproj_file.ConvertVariablesToShellSyntax(message) action_string_sh = gyp.xcodeproj_file.ConvertVariablesToShellSyntax( action_string ) script = "" # Include the optional message if message_sh: script += message_sh + "\n" # Be sure the script runs in exec, and that if exec fails, the script # exits signalling an error. script += "exec " + action_string_sh + "\nexit 1\n" ssbp = gyp.xcodeproj_file.PBXShellScriptBuildPhase( { "inputPaths": action["inputs"], "name": 'Action "' + action["action_name"] + '"', "outputPaths": action["outputs"], "shellScript": script, "showEnvVarsInLog": 0, } ) if support_xct: support_xct.AppendProperty("buildPhases", ssbp) else: # TODO(mark): this assumes too much knowledge of the internals of # xcodeproj_file; some of these smarts should move into xcodeproj_file # itself. xct._properties["buildPhases"].insert(prebuild_index, ssbp) prebuild_index = prebuild_index + 1 # TODO(mark): Should verify that at most one of these is specified. if int(action.get("process_outputs_as_sources", False)): for output in action["outputs"]: AddSourceToTarget(output, type, pbxp, xct) if int(action.get("process_outputs_as_mac_bundle_resources", False)): for output in action["outputs"]: AddResourceToTarget(output, pbxp, xct) # tgt_mac_bundle_resources holds the list of bundle resources so # the rule processing can check against it. if is_bundle: tgt_mac_bundle_resources = spec.get("mac_bundle_resources", []) else: tgt_mac_bundle_resources = [] # Add custom shell script phases driving "make" for "rules" sections. # # Xcode's built-in rule support is almost powerful enough to use directly, # but there are a few significant deficiencies that render them unusable. # There are workarounds for some of its inadequacies, but in aggregate, # the workarounds added complexity to the generator, and some workarounds # actually require input files to be crafted more carefully than I'd like. # Consequently, until Xcode rules are made more capable, "rules" input # sections will be handled in Xcode output by shell script build phases # performed prior to the compilation phase. # # The following problems with Xcode rules were found. The numbers are # Apple radar IDs. I hope that these shortcomings are addressed, I really # liked having the rules handled directly in Xcode during the period that # I was prototyping this. # # 6588600 Xcode compiles custom script rule outputs too soon, compilation # fails. This occurs when rule outputs from distinct inputs are # interdependent. The only workaround is to put rules and their # inputs in a separate target from the one that compiles the rule # outputs. This requires input file cooperation and it means that # process_outputs_as_sources is unusable. # 6584932 Need to declare that custom rule outputs should be excluded from # compilation. A possible workaround is to lie to Xcode about a # rule's output, giving it a dummy file it doesn't know how to # compile. The rule action script would need to touch the dummy. # 6584839 I need a way to declare additional inputs to a custom rule. # A possible workaround is a shell script phase prior to # compilation that touches a rule's primary input files if any # would-be additional inputs are newer than the output. Modifying # the source tree - even just modification times - feels dirty. # 6564240 Xcode "custom script" build rules always dump all environment # variables. This is a low-prioroty problem and is not a # show-stopper. rules_by_ext = {} for rule in spec_rules: rules_by_ext[rule["extension"]] = rule # First, some definitions: # # A "rule source" is a file that was listed in a target's "sources" # list and will have a rule applied to it on the basis of matching the # rule's "extensions" attribute. Rule sources are direct inputs to # rules. # # Rule definitions may specify additional inputs in their "inputs" # attribute. These additional inputs are used for dependency tracking # purposes. # # A "concrete output" is a rule output with input-dependent variables # resolved. For example, given a rule with: # 'extension': 'ext', 'outputs': ['$(INPUT_FILE_BASE).cc'], # if the target's "sources" list contained "one.ext" and "two.ext", # the "concrete output" for rule input "two.ext" would be "two.cc". If # a rule specifies multiple outputs, each input file that the rule is # applied to will have the same number of concrete outputs. # # If any concrete outputs are outdated or missing relative to their # corresponding rule_source or to any specified additional input, the # rule action must be performed to generate the concrete outputs. # concrete_outputs_by_rule_source will have an item at the same index # as the rule['rule_sources'] that it corresponds to. Each item is a # list of all of the concrete outputs for the rule_source. concrete_outputs_by_rule_source = [] # concrete_outputs_all is a flat list of all concrete outputs that this # rule is able to produce, given the known set of input files # (rule_sources) that apply to it. concrete_outputs_all = [] # messages & actions are keyed by the same indices as rule['rule_sources'] # and concrete_outputs_by_rule_source. They contain the message and # action to perform after resolving input-dependent variables. The # message is optional, in which case None is stored for each rule source. messages = [] actions = [] for rule_source in rule.get("rule_sources", []): rule_source_dirname, rule_source_basename = posixpath.split(rule_source) (rule_source_root, rule_source_ext) = posixpath.splitext( rule_source_basename ) # These are the same variable names that Xcode uses for its own native # rule support. Because Xcode's rule engine is not being used, they # need to be expanded as they are written to the makefile. rule_input_dict = { "INPUT_FILE_BASE": rule_source_root, "INPUT_FILE_SUFFIX": rule_source_ext, "INPUT_FILE_NAME": rule_source_basename, "INPUT_FILE_PATH": rule_source, "INPUT_FILE_DIRNAME": rule_source_dirname, } concrete_outputs_for_this_rule_source = [] for output in rule.get("outputs", []): # Fortunately, Xcode and make both use $(VAR) format for their # variables, so the expansion is the only transformation necessary. # Any remaining $(VAR)-type variables in the string can be given # directly to make, which will pick up the correct settings from # what Xcode puts into the environment. concrete_output = ExpandXcodeVariables(output, rule_input_dict) concrete_outputs_for_this_rule_source.append(concrete_output) # Add all concrete outputs to the project. pbxp.AddOrGetFileInRootGroup(concrete_output) concrete_outputs_by_rule_source.append( concrete_outputs_for_this_rule_source ) concrete_outputs_all.extend(concrete_outputs_for_this_rule_source) # TODO(mark): Should verify that at most one of these is specified. if int(rule.get("process_outputs_as_sources", False)): for output in concrete_outputs_for_this_rule_source: AddSourceToTarget(output, type, pbxp, xct) # If the file came from the mac_bundle_resources list or if the rule # is marked to process outputs as bundle resource, do so. was_mac_bundle_resource = rule_source in tgt_mac_bundle_resources if was_mac_bundle_resource or int( rule.get("process_outputs_as_mac_bundle_resources", False) ): for output in concrete_outputs_for_this_rule_source: AddResourceToTarget(output, pbxp, xct) # Do we have a message to print when this rule runs? message = rule.get("message") if message: message = gyp.common.EncodePOSIXShellArgument(message) message = ExpandXcodeVariables(message, rule_input_dict) messages.append(message) # Turn the list into a string that can be passed to a shell. action_string = gyp.common.EncodePOSIXShellList(rule["action"]) action = ExpandXcodeVariables(action_string, rule_input_dict) actions.append(action) if len(concrete_outputs_all) > 0: # TODO(mark): There's a possibility for collision here. Consider # target "t" rule "A_r" and target "t_A" rule "r". makefile_name = "%s.make" % re.sub( "[^a-zA-Z0-9_]", "_", "{}_{}".format(target_name, rule["rule_name"]) ) makefile_path = os.path.join( xcode_projects[build_file].path, makefile_name ) # TODO(mark): try/close? Write to a temporary file and swap it only # if it's got changes? makefile = open(makefile_path, "w") # make will build the first target in the makefile by default. By # convention, it's called "all". List all (or at least one) # concrete output for each rule source as a prerequisite of the "all" # target. makefile.write("all: \\\n") for concrete_output_index, concrete_output_by_rule_source in enumerate( concrete_outputs_by_rule_source ): # Only list the first (index [0]) concrete output of each input # in the "all" target. Otherwise, a parallel make (-j > 1) would # attempt to process each input multiple times simultaneously. # Otherwise, "all" could just contain the entire list of # concrete_outputs_all. concrete_output = concrete_output_by_rule_source[0] if ( concrete_output_index == len(concrete_outputs_by_rule_source) - 1 ): eol = "" else: eol = " \\" makefile.write(f" {concrete_output}{eol}\n") for (rule_source, concrete_outputs, message, action) in zip( rule["rule_sources"], concrete_outputs_by_rule_source, messages, actions, ): makefile.write("\n") # Add a rule that declares it can build each concrete output of a # rule source. Collect the names of the directories that are # required. concrete_output_dirs = [] for concrete_output_index, concrete_output in enumerate( concrete_outputs ): bol = "" if concrete_output_index == 0 else " " makefile.write(f"{bol}{concrete_output} \\\n") concrete_output_dir = posixpath.dirname(concrete_output) if ( concrete_output_dir and concrete_output_dir not in concrete_output_dirs ): concrete_output_dirs.append(concrete_output_dir) makefile.write(" : \\\n") # The prerequisites for this rule are the rule source itself and # the set of additional rule inputs, if any. prerequisites = [rule_source] prerequisites.extend(rule.get("inputs", [])) for prerequisite_index, prerequisite in enumerate(prerequisites): if prerequisite_index == len(prerequisites) - 1: eol = "" else: eol = " \\" makefile.write(f" {prerequisite}{eol}\n") # Make sure that output directories exist before executing the rule # action. if len(concrete_output_dirs) > 0: makefile.write( '\t@mkdir -p "%s"\n' % '" "'.join(concrete_output_dirs) ) # The rule message and action have already had # the necessary variable substitutions performed. if message: # Mark it with note: so Xcode picks it up in build output. makefile.write("\t@echo note: %s\n" % message) makefile.write("\t%s\n" % action) makefile.close() # It might be nice to ensure that needed output directories exist # here rather than in each target in the Makefile, but that wouldn't # work if there ever was a concrete output that had an input-dependent # variable anywhere other than in the leaf position. # Don't declare any inputPaths or outputPaths. If they're present, # Xcode will provide a slight optimization by only running the script # phase if any output is missing or outdated relative to any input. # Unfortunately, it will also assume that all outputs are touched by # the script, and if the outputs serve as files in a compilation # phase, they will be unconditionally rebuilt. Since make might not # rebuild everything that could be declared here as an output, this # extra compilation activity is unnecessary. With inputPaths and # outputPaths not supplied, make will always be called, but it knows # enough to not do anything when everything is up-to-date. # To help speed things up, pass -j COUNT to make so it does some work # in parallel. Don't use ncpus because Xcode will build ncpus targets # in parallel and if each target happens to have a rules step, there # would be ncpus^2 things going. With a machine that has 2 quad-core # Xeons, a build can quickly run out of processes based on # scheduling/other tasks, and randomly failing builds are no good. script = ( """JOB_COUNT="$(/usr/sbin/sysctl -n hw.ncpu)" if [ "${JOB_COUNT}" -gt 4 ]; then JOB_COUNT=4 fi exec xcrun make -f "${PROJECT_FILE_PATH}/%s" -j "${JOB_COUNT}" exit 1 """ % makefile_name ) ssbp = gyp.xcodeproj_file.PBXShellScriptBuildPhase( { "name": 'Rule "' + rule["rule_name"] + '"', "shellScript": script, "showEnvVarsInLog": 0, } ) if support_xct: support_xct.AppendProperty("buildPhases", ssbp) else: # TODO(mark): this assumes too much knowledge of the internals of # xcodeproj_file; some of these smarts should move # into xcodeproj_file itself. xct._properties["buildPhases"].insert(prebuild_index, ssbp) prebuild_index = prebuild_index + 1 # Extra rule inputs also go into the project file. Concrete outputs were # already added when they were computed. groups = ["inputs", "inputs_excluded"] if skip_excluded_files: groups = [x for x in groups if not x.endswith("_excluded")] for group in groups: for item in rule.get(group, []): pbxp.AddOrGetFileInRootGroup(item) # Add "sources". for source in spec.get("sources", []): (source_root, source_extension) = posixpath.splitext(source) if source_extension[1:] not in rules_by_ext: # AddSourceToTarget will add the file to a root group if it's not # already there. AddSourceToTarget(source, type, pbxp, xct) else: pbxp.AddOrGetFileInRootGroup(source) # Add "mac_bundle_resources" and "mac_framework_private_headers" if # it's a bundle of any type. if is_bundle: for resource in tgt_mac_bundle_resources: (resource_root, resource_extension) = posixpath.splitext(resource) if resource_extension[1:] not in rules_by_ext: AddResourceToTarget(resource, pbxp, xct) else: pbxp.AddOrGetFileInRootGroup(resource) for header in spec.get("mac_framework_private_headers", []): AddHeaderToTarget(header, pbxp, xct, False) # Add "mac_framework_headers". These can be valid for both frameworks # and static libraries. if is_bundle or type == "static_library": for header in spec.get("mac_framework_headers", []): AddHeaderToTarget(header, pbxp, xct, True) # Add "copies". pbxcp_dict = {} for copy_group in spec.get("copies", []): dest = copy_group["destination"] if dest[0] not in ("/", "$"): # Relative paths are relative to $(SRCROOT). dest = "$(SRCROOT)/" + dest code_sign = int(copy_group.get("xcode_code_sign", 0)) settings = (None, "{ATTRIBUTES = (CodeSignOnCopy, ); }")[code_sign] # Coalesce multiple "copies" sections in the same target with the same # "destination" property into the same PBXCopyFilesBuildPhase, otherwise # they'll wind up with ID collisions. pbxcp = pbxcp_dict.get(dest, None) if pbxcp is None: pbxcp = gyp.xcodeproj_file.PBXCopyFilesBuildPhase( {"name": "Copy to " + copy_group["destination"]}, parent=xct ) pbxcp.SetDestination(dest) # TODO(mark): The usual comment about this knowing too much about # gyp.xcodeproj_file internals applies. xct._properties["buildPhases"].insert(prebuild_index, pbxcp) pbxcp_dict[dest] = pbxcp for file in copy_group["files"]: pbxcp.AddFile(file, settings) # Excluded files can also go into the project file. if not skip_excluded_files: for key in [ "sources", "mac_bundle_resources", "mac_framework_headers", "mac_framework_private_headers", ]: excluded_key = key + "_excluded" for item in spec.get(excluded_key, []): pbxp.AddOrGetFileInRootGroup(item) # So can "inputs" and "outputs" sections of "actions" groups. groups = ["inputs", "inputs_excluded", "outputs", "outputs_excluded"] if skip_excluded_files: groups = [x for x in groups if not x.endswith("_excluded")] for action in spec.get("actions", []): for group in groups: for item in action.get(group, []): # Exclude anything in BUILT_PRODUCTS_DIR. They're products, not # sources. if not item.startswith("$(BUILT_PRODUCTS_DIR)/"): pbxp.AddOrGetFileInRootGroup(item) for postbuild in spec.get("postbuilds", []): action_string_sh = gyp.common.EncodePOSIXShellList(postbuild["action"]) script = "exec " + action_string_sh + "\nexit 1\n" # Make the postbuild step depend on the output of ld or ar from this # target. Apparently putting the script step after the link step isn't # sufficient to ensure proper ordering in all cases. With an input # declared but no outputs, the script step should run every time, as # desired. ssbp = gyp.xcodeproj_file.PBXShellScriptBuildPhase( { "inputPaths": ["$(BUILT_PRODUCTS_DIR)/$(EXECUTABLE_PATH)"], "name": 'Postbuild "' + postbuild["postbuild_name"] + '"', "shellScript": script, "showEnvVarsInLog": 0, } ) xct.AppendProperty("buildPhases", ssbp) # Add dependencies before libraries, because adding a dependency may imply # adding a library. It's preferable to keep dependencies listed first # during a link phase so that they can override symbols that would # otherwise be provided by libraries, which will usually include system # libraries. On some systems, ld is finicky and even requires the # libraries to be ordered in such a way that unresolved symbols in # earlier-listed libraries may only be resolved by later-listed libraries. # The Mac linker doesn't work that way, but other platforms do, and so # their linker invocations need to be constructed in this way. There's # no compelling reason for Xcode's linker invocations to differ. if "dependencies" in spec: for dependency in spec["dependencies"]: xct.AddDependency(xcode_targets[dependency]) # The support project also gets the dependencies (in case they are # needed for the actions/rules to work). if support_xct: support_xct.AddDependency(xcode_targets[dependency]) if "libraries" in spec: for library in spec["libraries"]: xct.FrameworksPhase().AddFile(library) # Add the library's directory to LIBRARY_SEARCH_PATHS if necessary. # I wish Xcode handled this automatically. library_dir = posixpath.dirname(library) if library_dir not in xcode_standard_library_dirs and ( not xct.HasBuildSetting(_library_search_paths_var) or library_dir not in xct.GetBuildSetting(_library_search_paths_var) ): xct.AppendBuildSetting(_library_search_paths_var, library_dir) for configuration_name in configuration_names: configuration = spec["configurations"][configuration_name] xcbc = xct.ConfigurationNamed(configuration_name) for include_dir in configuration.get("mac_framework_dirs", []): xcbc.AppendBuildSetting("FRAMEWORK_SEARCH_PATHS", include_dir) for include_dir in configuration.get("include_dirs", []): xcbc.AppendBuildSetting("HEADER_SEARCH_PATHS", include_dir) for library_dir in configuration.get("library_dirs", []): if library_dir not in xcode_standard_library_dirs and ( not xcbc.HasBuildSetting(_library_search_paths_var) or library_dir not in xcbc.GetBuildSetting(_library_search_paths_var) ): xcbc.AppendBuildSetting(_library_search_paths_var, library_dir) if "defines" in configuration: for define in configuration["defines"]: set_define = EscapeXcodeDefine(define) xcbc.AppendBuildSetting("GCC_PREPROCESSOR_DEFINITIONS", set_define) if "xcode_settings" in configuration: for xck, xcv in configuration["xcode_settings"].items(): xcbc.SetBuildSetting(xck, xcv) if "xcode_config_file" in configuration: config_ref = pbxp.AddOrGetFileInRootGroup( configuration["xcode_config_file"] ) xcbc.SetBaseConfiguration(config_ref) build_files = [] for build_file, build_file_dict in data.items(): if build_file.endswith(".gyp"): build_files.append(build_file) for build_file in build_files: xcode_projects[build_file].Finalize1(xcode_targets, serialize_all_tests) for build_file in build_files: xcode_projects[build_file].Finalize2(xcode_targets, xcode_target_to_target_dict) for build_file in build_files: xcode_projects[build_file].Write() PK ~\Q?+node-gyp/gyp/pylib/gyp/generator/android.pynu[# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # Notes: # # This generates makefiles suitable for inclusion into the Android build system # via an Android.mk file. It is based on make.py, the standard makefile # generator. # # The code below generates a separate .mk file for each target, but # all are sourced by the top-level GypAndroid.mk. This means that all # variables in .mk-files clobber one another, and furthermore that any # variables set potentially clash with other Android build system variables. # Try to avoid setting global variables where possible. import gyp import gyp.common import gyp.generator.make as make # Reuse global functions from make backend. import os import re import subprocess generator_default_variables = { "OS": "android", "EXECUTABLE_PREFIX": "", "EXECUTABLE_SUFFIX": "", "STATIC_LIB_PREFIX": "lib", "SHARED_LIB_PREFIX": "lib", "STATIC_LIB_SUFFIX": ".a", "SHARED_LIB_SUFFIX": ".so", "INTERMEDIATE_DIR": "$(gyp_intermediate_dir)", "SHARED_INTERMEDIATE_DIR": "$(gyp_shared_intermediate_dir)", "PRODUCT_DIR": "$(gyp_shared_intermediate_dir)", "SHARED_LIB_DIR": "$(builddir)/lib.$(TOOLSET)", "LIB_DIR": "$(obj).$(TOOLSET)", "RULE_INPUT_ROOT": "%(INPUT_ROOT)s", # This gets expanded by Python. "RULE_INPUT_DIRNAME": "%(INPUT_DIRNAME)s", # This gets expanded by Python. "RULE_INPUT_PATH": "$(RULE_SOURCES)", "RULE_INPUT_EXT": "$(suffix $<)", "RULE_INPUT_NAME": "$(notdir $<)", "CONFIGURATION_NAME": "$(GYP_CONFIGURATION)", } # Make supports multiple toolsets generator_supports_multiple_toolsets = True # Generator-specific gyp specs. generator_additional_non_configuration_keys = [ # Boolean to declare that this target does not want its name mangled. "android_unmangled_name", # Map of android build system variables to set. "aosp_build_settings", ] generator_additional_path_sections = [] generator_extra_sources_for_rules = [] ALL_MODULES_FOOTER = """\ # "gyp_all_modules" is a concatenation of the "gyp_all_modules" targets from # all the included sub-makefiles. This is just here to clarify. gyp_all_modules: """ header = """\ # This file is generated by gyp; do not edit. """ # Map gyp target types to Android module classes. MODULE_CLASSES = { "static_library": "STATIC_LIBRARIES", "shared_library": "SHARED_LIBRARIES", "executable": "EXECUTABLES", } def IsCPPExtension(ext): return make.COMPILABLE_EXTENSIONS.get(ext) == "cxx" def Sourceify(path): """Convert a path to its source directory form. The Android backend does not support options.generator_output, so this function is a noop.""" return path # Map from qualified target to path to output. # For Android, the target of these maps is a tuple ('static', 'modulename'), # ('dynamic', 'modulename'), or ('path', 'some/path') instead of a string, # since we link by module. target_outputs = {} # Map from qualified target to any linkable output. A subset # of target_outputs. E.g. when mybinary depends on liba, we want to # include liba in the linker line; when otherbinary depends on # mybinary, we just want to build mybinary first. target_link_deps = {} class AndroidMkWriter: """AndroidMkWriter packages up the writing of one target-specific Android.mk. Its only real entry point is Write(), and is mostly used for namespacing. """ def __init__(self, android_top_dir): self.android_top_dir = android_top_dir def Write( self, qualified_target, relative_target, base_path, output_filename, spec, configs, part_of_all, write_alias_target, sdk_version, ): """The main entry point: writes a .mk file for a single target. Arguments: qualified_target: target we're generating relative_target: qualified target name relative to the root base_path: path relative to source root we're building in, used to resolve target-relative paths output_filename: output .mk file name to write spec, configs: gyp info part_of_all: flag indicating this target is part of 'all' write_alias_target: flag indicating whether to create short aliases for this target sdk_version: what to emit for LOCAL_SDK_VERSION in output """ gyp.common.EnsureDirExists(output_filename) self.fp = open(output_filename, "w") self.fp.write(header) self.qualified_target = qualified_target self.relative_target = relative_target self.path = base_path self.target = spec["target_name"] self.type = spec["type"] self.toolset = spec["toolset"] deps, link_deps = self.ComputeDeps(spec) # Some of the generation below can add extra output, sources, or # link dependencies. All of the out params of the functions that # follow use names like extra_foo. extra_outputs = [] extra_sources = [] self.android_class = MODULE_CLASSES.get(self.type, "GYP") self.android_module = self.ComputeAndroidModule(spec) (self.android_stem, self.android_suffix) = self.ComputeOutputParts(spec) self.output = self.output_binary = self.ComputeOutput(spec) # Standard header. self.WriteLn("include $(CLEAR_VARS)\n") # Module class and name. self.WriteLn("LOCAL_MODULE_CLASS := " + self.android_class) self.WriteLn("LOCAL_MODULE := " + self.android_module) # Only emit LOCAL_MODULE_STEM if it's different to LOCAL_MODULE. # The library module classes fail if the stem is set. ComputeOutputParts # makes sure that stem == modulename in these cases. if self.android_stem != self.android_module: self.WriteLn("LOCAL_MODULE_STEM := " + self.android_stem) self.WriteLn("LOCAL_MODULE_SUFFIX := " + self.android_suffix) if self.toolset == "host": self.WriteLn("LOCAL_IS_HOST_MODULE := true") self.WriteLn("LOCAL_MULTILIB := $(GYP_HOST_MULTILIB)") elif sdk_version > 0: self.WriteLn( "LOCAL_MODULE_TARGET_ARCH := " "$(TARGET_$(GYP_VAR_PREFIX)ARCH)" ) self.WriteLn("LOCAL_SDK_VERSION := %s" % sdk_version) # Grab output directories; needed for Actions and Rules. if self.toolset == "host": self.WriteLn( "gyp_intermediate_dir := " "$(call local-intermediates-dir,,$(GYP_HOST_VAR_PREFIX))" ) else: self.WriteLn( "gyp_intermediate_dir := " "$(call local-intermediates-dir,,$(GYP_VAR_PREFIX))" ) self.WriteLn( "gyp_shared_intermediate_dir := " "$(call intermediates-dir-for,GYP,shared,,,$(GYP_VAR_PREFIX))" ) self.WriteLn() # List files this target depends on so that actions/rules/copies/sources # can depend on the list. # TODO: doesn't pull in things through transitive link deps; needed? target_dependencies = [x[1] for x in deps if x[0] == "path"] self.WriteLn("# Make sure our deps are built first.") self.WriteList( target_dependencies, "GYP_TARGET_DEPENDENCIES", local_pathify=True ) # Actions must come first, since they can generate more OBJs for use below. if "actions" in spec: self.WriteActions(spec["actions"], extra_sources, extra_outputs) # Rules must be early like actions. if "rules" in spec: self.WriteRules(spec["rules"], extra_sources, extra_outputs) if "copies" in spec: self.WriteCopies(spec["copies"], extra_outputs) # GYP generated outputs. self.WriteList(extra_outputs, "GYP_GENERATED_OUTPUTS", local_pathify=True) # Set LOCAL_ADDITIONAL_DEPENDENCIES so that Android's build rules depend # on both our dependency targets and our generated files. self.WriteLn("# Make sure our deps and generated files are built first.") self.WriteLn( "LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) " "$(GYP_GENERATED_OUTPUTS)" ) self.WriteLn() # Sources. if spec.get("sources", []) or extra_sources: self.WriteSources(spec, configs, extra_sources) self.WriteTarget( spec, configs, deps, link_deps, part_of_all, write_alias_target ) # Update global list of target outputs, used in dependency tracking. target_outputs[qualified_target] = ("path", self.output_binary) # Update global list of link dependencies. if self.type == "static_library": target_link_deps[qualified_target] = ("static", self.android_module) elif self.type == "shared_library": target_link_deps[qualified_target] = ("shared", self.android_module) self.fp.close() return self.android_module def WriteActions(self, actions, extra_sources, extra_outputs): """Write Makefile code for any 'actions' from the gyp input. extra_sources: a list that will be filled in with newly generated source files, if any extra_outputs: a list that will be filled in with any outputs of these actions (used to make other pieces dependent on these actions) """ for action in actions: name = make.StringToMakefileVariable( "{}_{}".format(self.relative_target, action["action_name"]) ) self.WriteLn('### Rules for action "%s":' % action["action_name"]) inputs = action["inputs"] outputs = action["outputs"] # Build up a list of outputs. # Collect the output dirs we'll need. dirs = set() for out in outputs: if not out.startswith("$"): print( 'WARNING: Action for target "%s" writes output to local path ' '"%s".' % (self.target, out) ) dir = os.path.split(out)[0] if dir: dirs.add(dir) if int(action.get("process_outputs_as_sources", False)): extra_sources += outputs # Prepare the actual command. command = gyp.common.EncodePOSIXShellList(action["action"]) if "message" in action: quiet_cmd = "Gyp action: %s ($@)" % action["message"] else: quiet_cmd = "Gyp action: %s ($@)" % name if len(dirs) > 0: command = "mkdir -p %s" % " ".join(dirs) + "; " + command cd_action = "cd $(gyp_local_path)/%s; " % self.path command = cd_action + command # The makefile rules are all relative to the top dir, but the gyp actions # are defined relative to their containing dir. This replaces the gyp_* # variables for the action rule with an absolute version so that the # output goes in the right place. # Only write the gyp_* rules for the "primary" output (:1); # it's superfluous for the "extra outputs", and this avoids accidentally # writing duplicate dummy rules for those outputs. main_output = make.QuoteSpaces(self.LocalPathify(outputs[0])) self.WriteLn("%s: gyp_local_path := $(LOCAL_PATH)" % main_output) self.WriteLn("%s: gyp_var_prefix := $(GYP_VAR_PREFIX)" % main_output) self.WriteLn( "%s: gyp_intermediate_dir := " "$(abspath $(gyp_intermediate_dir))" % main_output ) self.WriteLn( "%s: gyp_shared_intermediate_dir := " "$(abspath $(gyp_shared_intermediate_dir))" % main_output ) # Android's envsetup.sh adds a number of directories to the path including # the built host binary directory. This causes actions/rules invoked by # gyp to sometimes use these instead of system versions, e.g. bison. # The built host binaries may not be suitable, and can cause errors. # So, we remove them from the PATH using the ANDROID_BUILD_PATHS variable # set by envsetup. self.WriteLn( "%s: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))" % main_output ) # Don't allow spaces in input/output filenames, but make an exception for # filenames which start with '$(' since it's okay for there to be spaces # inside of make function/macro invocations. for input in inputs: if not input.startswith("$(") and " " in input: raise gyp.common.GypError( 'Action input filename "%s" in target %s contains a space' % (input, self.target) ) for output in outputs: if not output.startswith("$(") and " " in output: raise gyp.common.GypError( 'Action output filename "%s" in target %s contains a space' % (output, self.target) ) self.WriteLn( "%s: %s $(GYP_TARGET_DEPENDENCIES)" % (main_output, " ".join(map(self.LocalPathify, inputs))) ) self.WriteLn('\t@echo "%s"' % quiet_cmd) self.WriteLn("\t$(hide)%s\n" % command) for output in outputs[1:]: # Make each output depend on the main output, with an empty command # to force make to notice that the mtime has changed. self.WriteLn(f"{self.LocalPathify(output)}: {main_output} ;") extra_outputs += outputs self.WriteLn() self.WriteLn() def WriteRules(self, rules, extra_sources, extra_outputs): """Write Makefile code for any 'rules' from the gyp input. extra_sources: a list that will be filled in with newly generated source files, if any extra_outputs: a list that will be filled in with any outputs of these rules (used to make other pieces dependent on these rules) """ if len(rules) == 0: return for rule in rules: if len(rule.get("rule_sources", [])) == 0: continue name = make.StringToMakefileVariable( "{}_{}".format(self.relative_target, rule["rule_name"]) ) self.WriteLn('\n### Generated for rule "%s":' % name) self.WriteLn('# "%s":' % rule) inputs = rule.get("inputs") for rule_source in rule.get("rule_sources", []): (rule_source_dirname, rule_source_basename) = os.path.split(rule_source) (rule_source_root, rule_source_ext) = os.path.splitext( rule_source_basename ) outputs = [ self.ExpandInputRoot(out, rule_source_root, rule_source_dirname) for out in rule["outputs"] ] dirs = set() for out in outputs: if not out.startswith("$"): print( "WARNING: Rule for target %s writes output to local path %s" % (self.target, out) ) dir = os.path.dirname(out) if dir: dirs.add(dir) extra_outputs += outputs if int(rule.get("process_outputs_as_sources", False)): extra_sources.extend(outputs) components = [] for component in rule["action"]: component = self.ExpandInputRoot( component, rule_source_root, rule_source_dirname ) if "$(RULE_SOURCES)" in component: component = component.replace("$(RULE_SOURCES)", rule_source) components.append(component) command = gyp.common.EncodePOSIXShellList(components) cd_action = "cd $(gyp_local_path)/%s; " % self.path command = cd_action + command if dirs: command = "mkdir -p %s" % " ".join(dirs) + "; " + command # We set up a rule to build the first output, and then set up # a rule for each additional output to depend on the first. outputs = map(self.LocalPathify, outputs) main_output = outputs[0] self.WriteLn("%s: gyp_local_path := $(LOCAL_PATH)" % main_output) self.WriteLn("%s: gyp_var_prefix := $(GYP_VAR_PREFIX)" % main_output) self.WriteLn( "%s: gyp_intermediate_dir := " "$(abspath $(gyp_intermediate_dir))" % main_output ) self.WriteLn( "%s: gyp_shared_intermediate_dir := " "$(abspath $(gyp_shared_intermediate_dir))" % main_output ) # See explanation in WriteActions. self.WriteLn( "%s: export PATH := " "$(subst $(ANDROID_BUILD_PATHS),,$(PATH))" % main_output ) main_output_deps = self.LocalPathify(rule_source) if inputs: main_output_deps += " " main_output_deps += " ".join([self.LocalPathify(f) for f in inputs]) self.WriteLn( "%s: %s $(GYP_TARGET_DEPENDENCIES)" % (main_output, main_output_deps) ) self.WriteLn("\t%s\n" % command) for output in outputs[1:]: # Make each output depend on the main output, with an empty command # to force make to notice that the mtime has changed. self.WriteLn(f"{output}: {main_output} ;") self.WriteLn() self.WriteLn() def WriteCopies(self, copies, extra_outputs): """Write Makefile code for any 'copies' from the gyp input. extra_outputs: a list that will be filled in with any outputs of this action (used to make other pieces dependent on this action) """ self.WriteLn("### Generated for copy rule.") variable = make.StringToMakefileVariable(self.relative_target + "_copies") outputs = [] for copy in copies: for path in copy["files"]: # The Android build system does not allow generation of files into the # source tree. The destination should start with a variable, which will # typically be $(gyp_intermediate_dir) or # $(gyp_shared_intermediate_dir). Note that we can't use an assertion # because some of the gyp tests depend on this. if not copy["destination"].startswith("$"): print( "WARNING: Copy rule for target %s writes output to " "local path %s" % (self.target, copy["destination"]) ) # LocalPathify() calls normpath, stripping trailing slashes. path = Sourceify(self.LocalPathify(path)) filename = os.path.split(path)[1] output = Sourceify( self.LocalPathify(os.path.join(copy["destination"], filename)) ) self.WriteLn(f"{output}: {path} $(GYP_TARGET_DEPENDENCIES) | $(ACP)") self.WriteLn("\t@echo Copying: $@") self.WriteLn("\t$(hide) mkdir -p $(dir $@)") self.WriteLn("\t$(hide) $(ACP) -rpf $< $@") self.WriteLn() outputs.append(output) self.WriteLn( "{} = {}".format(variable, " ".join(map(make.QuoteSpaces, outputs))) ) extra_outputs.append("$(%s)" % variable) self.WriteLn() def WriteSourceFlags(self, spec, configs): """Write out the flags and include paths used to compile source files for the current target. Args: spec, configs: input from gyp. """ for configname, config in sorted(configs.items()): extracted_includes = [] self.WriteLn("\n# Flags passed to both C and C++ files.") cflags, includes_from_cflags = self.ExtractIncludesFromCFlags( config.get("cflags", []) + config.get("cflags_c", []) ) extracted_includes.extend(includes_from_cflags) self.WriteList(cflags, "MY_CFLAGS_%s" % configname) self.WriteList( config.get("defines"), "MY_DEFS_%s" % configname, prefix="-D", quoter=make.EscapeCppDefine, ) self.WriteLn("\n# Include paths placed before CFLAGS/CPPFLAGS") includes = list(config.get("include_dirs", [])) includes.extend(extracted_includes) includes = map(Sourceify, map(self.LocalPathify, includes)) includes = self.NormalizeIncludePaths(includes) self.WriteList(includes, "LOCAL_C_INCLUDES_%s" % configname) self.WriteLn("\n# Flags passed to only C++ (and not C) files.") self.WriteList(config.get("cflags_cc"), "LOCAL_CPPFLAGS_%s" % configname) self.WriteLn( "\nLOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) " "$(MY_DEFS_$(GYP_CONFIGURATION))" ) # Undefine ANDROID for host modules # TODO: the source code should not use macro ANDROID to tell if it's host # or target module. if self.toolset == "host": self.WriteLn("# Undefine ANDROID for host modules") self.WriteLn("LOCAL_CFLAGS += -UANDROID") self.WriteLn( "LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) " "$(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))" ) self.WriteLn("LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))") # Android uses separate flags for assembly file invocations, but gyp expects # the same CFLAGS to be applied: self.WriteLn("LOCAL_ASFLAGS := $(LOCAL_CFLAGS)") def WriteSources(self, spec, configs, extra_sources): """Write Makefile code for any 'sources' from the gyp input. These are source files necessary to build the current target. We need to handle shared_intermediate directory source files as a special case by copying them to the intermediate directory and treating them as a generated sources. Otherwise the Android build rules won't pick them up. Args: spec, configs: input from gyp. extra_sources: Sources generated from Actions or Rules. """ sources = filter(make.Compilable, spec.get("sources", [])) generated_not_sources = [x for x in extra_sources if not make.Compilable(x)] extra_sources = filter(make.Compilable, extra_sources) # Determine and output the C++ extension used by these sources. # We simply find the first C++ file and use that extension. all_sources = sources + extra_sources local_cpp_extension = ".cpp" for source in all_sources: (root, ext) = os.path.splitext(source) if IsCPPExtension(ext): local_cpp_extension = ext break if local_cpp_extension != ".cpp": self.WriteLn("LOCAL_CPP_EXTENSION := %s" % local_cpp_extension) # We need to move any non-generated sources that are coming from the # shared intermediate directory out of LOCAL_SRC_FILES and put them # into LOCAL_GENERATED_SOURCES. We also need to move over any C++ files # that don't match our local_cpp_extension, since Android will only # generate Makefile rules for a single LOCAL_CPP_EXTENSION. local_files = [] for source in sources: (root, ext) = os.path.splitext(source) if "$(gyp_shared_intermediate_dir)" in source: extra_sources.append(source) elif "$(gyp_intermediate_dir)" in source: extra_sources.append(source) elif IsCPPExtension(ext) and ext != local_cpp_extension: extra_sources.append(source) else: local_files.append(os.path.normpath(os.path.join(self.path, source))) # For any generated source, if it is coming from the shared intermediate # directory then we add a Make rule to copy them to the local intermediate # directory first. This is because the Android LOCAL_GENERATED_SOURCES # must be in the local module intermediate directory for the compile rules # to work properly. If the file has the wrong C++ extension, then we add # a rule to copy that to intermediates and use the new version. final_generated_sources = [] # If a source file gets copied, we still need to add the original source # directory as header search path, for GCC searches headers in the # directory that contains the source file by default. origin_src_dirs = [] for source in extra_sources: local_file = source if "$(gyp_intermediate_dir)/" not in local_file: basename = os.path.basename(local_file) local_file = "$(gyp_intermediate_dir)/" + basename (root, ext) = os.path.splitext(local_file) if IsCPPExtension(ext) and ext != local_cpp_extension: local_file = root + local_cpp_extension if local_file != source: self.WriteLn(f"{local_file}: {self.LocalPathify(source)}") self.WriteLn("\tmkdir -p $(@D); cp $< $@") origin_src_dirs.append(os.path.dirname(source)) final_generated_sources.append(local_file) # We add back in all of the non-compilable stuff to make sure that the # make rules have dependencies on them. final_generated_sources.extend(generated_not_sources) self.WriteList(final_generated_sources, "LOCAL_GENERATED_SOURCES") origin_src_dirs = gyp.common.uniquer(origin_src_dirs) origin_src_dirs = map(Sourceify, map(self.LocalPathify, origin_src_dirs)) self.WriteList(origin_src_dirs, "GYP_COPIED_SOURCE_ORIGIN_DIRS") self.WriteList(local_files, "LOCAL_SRC_FILES") # Write out the flags used to compile the source; this must be done last # so that GYP_COPIED_SOURCE_ORIGIN_DIRS can be used as an include path. self.WriteSourceFlags(spec, configs) def ComputeAndroidModule(self, spec): """Return the Android module name used for a gyp spec. We use the complete qualified target name to avoid collisions between duplicate targets in different directories. We also add a suffix to distinguish gyp-generated module names. """ if int(spec.get("android_unmangled_name", 0)): assert self.type != "shared_library" or self.target.startswith("lib") return self.target if self.type == "shared_library": # For reasons of convention, the Android build system requires that all # shared library modules are named 'libfoo' when generating -l flags. prefix = "lib_" else: prefix = "" if spec["toolset"] == "host": suffix = "_$(TARGET_$(GYP_VAR_PREFIX)ARCH)_host_gyp" else: suffix = "_gyp" if self.path: middle = make.StringToMakefileVariable(f"{self.path}_{self.target}") else: middle = make.StringToMakefileVariable(self.target) return "".join([prefix, middle, suffix]) def ComputeOutputParts(self, spec): """Return the 'output basename' of a gyp spec, split into filename + ext. Android libraries must be named the same thing as their module name, otherwise the linker can't find them, so product_name and so on must be ignored if we are building a library, and the "lib" prepending is not done for Android. """ assert self.type != "loadable_module" # TODO: not supported? target = spec["target_name"] target_prefix = "" target_ext = "" if self.type == "static_library": target = self.ComputeAndroidModule(spec) target_ext = ".a" elif self.type == "shared_library": target = self.ComputeAndroidModule(spec) target_ext = ".so" elif self.type == "none": target_ext = ".stamp" elif self.type != "executable": print( "ERROR: What output file should be generated?", "type", self.type, "target", target, ) if self.type not in {"static_library", "shared_library"}: target_prefix = spec.get("product_prefix", target_prefix) target = spec.get("product_name", target) product_ext = spec.get("product_extension") if product_ext: target_ext = "." + product_ext target_stem = target_prefix + target return (target_stem, target_ext) def ComputeOutputBasename(self, spec): """Return the 'output basename' of a gyp spec. E.g., the loadable module 'foobar' in directory 'baz' will produce 'libfoobar.so' """ return "".join(self.ComputeOutputParts(spec)) def ComputeOutput(self, spec): """Return the 'output' (full output path) of a gyp spec. E.g., the loadable module 'foobar' in directory 'baz' will produce '$(obj)/baz/libfoobar.so' """ if self.type == "executable": # We install host executables into shared_intermediate_dir so they can be # run by gyp rules that refer to PRODUCT_DIR. path = "$(gyp_shared_intermediate_dir)" elif self.type == "shared_library": if self.toolset == "host": path = "$($(GYP_HOST_VAR_PREFIX)HOST_OUT_INTERMEDIATE_LIBRARIES)" else: path = "$($(GYP_VAR_PREFIX)TARGET_OUT_INTERMEDIATE_LIBRARIES)" else: # Other targets just get built into their intermediate dir. if self.toolset == "host": path = ( "$(call intermediates-dir-for,%s,%s,true,," "$(GYP_HOST_VAR_PREFIX))" % (self.android_class, self.android_module) ) else: path = ( "$(call intermediates-dir-for," f"{self.android_class},{self.android_module},,,$(GYP_VAR_PREFIX))" ) assert spec.get("product_dir") is None # TODO: not supported? return os.path.join(path, self.ComputeOutputBasename(spec)) def NormalizeIncludePaths(self, include_paths): """Normalize include_paths. Convert absolute paths to relative to the Android top directory. Args: include_paths: A list of unprocessed include paths. Returns: A list of normalized include paths. """ normalized = [] for path in include_paths: if path[0] == "/": path = gyp.common.RelativePath(path, self.android_top_dir) normalized.append(path) return normalized def ExtractIncludesFromCFlags(self, cflags): """Extract includes "-I..." out from cflags Args: cflags: A list of compiler flags, which may be mixed with "-I.." Returns: A tuple of lists: (clean_clfags, include_paths). "-I.." is trimmed. """ clean_cflags = [] include_paths = [] for flag in cflags: if flag.startswith("-I"): include_paths.append(flag[2:]) else: clean_cflags.append(flag) return (clean_cflags, include_paths) def FilterLibraries(self, libraries): """Filter the 'libraries' key to separate things that shouldn't be ldflags. Library entries that look like filenames should be converted to android module names instead of being passed to the linker as flags. Args: libraries: the value of spec.get('libraries') Returns: A tuple (static_lib_modules, dynamic_lib_modules, ldflags) """ static_lib_modules = [] dynamic_lib_modules = [] ldflags = [] for libs in libraries: # Libs can have multiple words. for lib in libs.split(): # Filter the system libraries, which are added by default by the Android # build system. if ( lib == "-lc" or lib == "-lstdc++" or lib == "-lm" or lib.endswith("libgcc.a") ): continue match = re.search(r"([^/]+)\.a$", lib) if match: static_lib_modules.append(match.group(1)) continue match = re.search(r"([^/]+)\.so$", lib) if match: dynamic_lib_modules.append(match.group(1)) continue if lib.startswith("-l"): ldflags.append(lib) return (static_lib_modules, dynamic_lib_modules, ldflags) def ComputeDeps(self, spec): """Compute the dependencies of a gyp spec. Returns a tuple (deps, link_deps), where each is a list of filenames that will need to be put in front of make for either building (deps) or linking (link_deps). """ deps = [] link_deps = [] if "dependencies" in spec: deps.extend( [ target_outputs[dep] for dep in spec["dependencies"] if target_outputs[dep] ] ) for dep in spec["dependencies"]: if dep in target_link_deps: link_deps.append(target_link_deps[dep]) deps.extend(link_deps) return (gyp.common.uniquer(deps), gyp.common.uniquer(link_deps)) def WriteTargetFlags(self, spec, configs, link_deps): """Write Makefile code to specify the link flags and library dependencies. spec, configs: input from gyp. link_deps: link dependency list; see ComputeDeps() """ # Libraries (i.e. -lfoo) # These must be included even for static libraries as some of them provide # implicit include paths through the build system. libraries = gyp.common.uniquer(spec.get("libraries", [])) static_libs, dynamic_libs, ldflags_libs = self.FilterLibraries(libraries) if self.type != "static_library": for configname, config in sorted(configs.items()): ldflags = list(config.get("ldflags", [])) self.WriteLn("") self.WriteList(ldflags, "LOCAL_LDFLAGS_%s" % configname) self.WriteList(ldflags_libs, "LOCAL_GYP_LIBS") self.WriteLn( "LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION)) " "$(LOCAL_GYP_LIBS)" ) # Link dependencies (i.e. other gyp targets this target depends on) # These need not be included for static libraries as within the gyp build # we do not use the implicit include path mechanism. if self.type != "static_library": static_link_deps = [x[1] for x in link_deps if x[0] == "static"] shared_link_deps = [x[1] for x in link_deps if x[0] == "shared"] else: static_link_deps = [] shared_link_deps = [] # Only write the lists if they are non-empty. if static_libs or static_link_deps: self.WriteLn("") self.WriteList(static_libs + static_link_deps, "LOCAL_STATIC_LIBRARIES") self.WriteLn("# Enable grouping to fix circular references") self.WriteLn("LOCAL_GROUP_STATIC_LIBRARIES := true") if dynamic_libs or shared_link_deps: self.WriteLn("") self.WriteList(dynamic_libs + shared_link_deps, "LOCAL_SHARED_LIBRARIES") def WriteTarget( self, spec, configs, deps, link_deps, part_of_all, write_alias_target ): """Write Makefile code to produce the final target of the gyp spec. spec, configs: input from gyp. deps, link_deps: dependency lists; see ComputeDeps() part_of_all: flag indicating this target is part of 'all' write_alias_target: flag indicating whether to create short aliases for this target """ self.WriteLn("### Rules for final target.") if self.type != "none": self.WriteTargetFlags(spec, configs, link_deps) settings = spec.get("aosp_build_settings", {}) if settings: self.WriteLn("### Set directly by aosp_build_settings.") for k, v in settings.items(): if isinstance(v, list): self.WriteList(v, k) else: self.WriteLn(f"{k} := {make.QuoteIfNecessary(v)}") self.WriteLn("") # Add to the set of targets which represent the gyp 'all' target. We use the # name 'gyp_all_modules' as the Android build system doesn't allow the use # of the Make target 'all' and because 'all_modules' is the equivalent of # the Make target 'all' on Android. if part_of_all and write_alias_target: self.WriteLn('# Add target alias to "gyp_all_modules" target.') self.WriteLn(".PHONY: gyp_all_modules") self.WriteLn("gyp_all_modules: %s" % self.android_module) self.WriteLn("") # Add an alias from the gyp target name to the Android module name. This # simplifies manual builds of the target, and is required by the test # framework. if self.target != self.android_module and write_alias_target: self.WriteLn("# Alias gyp target name.") self.WriteLn(".PHONY: %s" % self.target) self.WriteLn(f"{self.target}: {self.android_module}") self.WriteLn("") # Add the command to trigger build of the target type depending # on the toolset. Ex: BUILD_STATIC_LIBRARY vs. BUILD_HOST_STATIC_LIBRARY # NOTE: This has to come last! modifier = "" if self.toolset == "host": modifier = "HOST_" if self.type == "static_library": self.WriteLn("include $(BUILD_%sSTATIC_LIBRARY)" % modifier) elif self.type == "shared_library": self.WriteLn("LOCAL_PRELINK_MODULE := false") self.WriteLn("include $(BUILD_%sSHARED_LIBRARY)" % modifier) elif self.type == "executable": self.WriteLn("LOCAL_CXX_STL := libc++_static") # Executables are for build and test purposes only, so they're installed # to a directory that doesn't get included in the system image. self.WriteLn("LOCAL_MODULE_PATH := $(gyp_shared_intermediate_dir)") self.WriteLn("include $(BUILD_%sEXECUTABLE)" % modifier) else: self.WriteLn("LOCAL_MODULE_PATH := $(PRODUCT_OUT)/gyp_stamp") self.WriteLn("LOCAL_UNINSTALLABLE_MODULE := true") if self.toolset == "target": self.WriteLn("LOCAL_2ND_ARCH_VAR_PREFIX := $(GYP_VAR_PREFIX)") else: self.WriteLn("LOCAL_2ND_ARCH_VAR_PREFIX := $(GYP_HOST_VAR_PREFIX)") self.WriteLn() self.WriteLn("include $(BUILD_SYSTEM)/base_rules.mk") self.WriteLn() self.WriteLn("$(LOCAL_BUILT_MODULE): $(LOCAL_ADDITIONAL_DEPENDENCIES)") self.WriteLn('\t$(hide) echo "Gyp timestamp: $@"') self.WriteLn("\t$(hide) mkdir -p $(dir $@)") self.WriteLn("\t$(hide) touch $@") self.WriteLn() self.WriteLn("LOCAL_2ND_ARCH_VAR_PREFIX :=") def WriteList( self, value_list, variable=None, prefix="", quoter=make.QuoteIfNecessary, local_pathify=False, ): """Write a variable definition that is a list of values. E.g. WriteList(['a','b'], 'foo', prefix='blah') writes out foo = blaha blahb but in a pretty-printed style. """ values = "" if value_list: value_list = [quoter(prefix + value) for value in value_list] if local_pathify: value_list = [self.LocalPathify(value) for value in value_list] values = " \\\n\t" + " \\\n\t".join(value_list) self.fp.write(f"{variable} :={values}\n\n") def WriteLn(self, text=""): self.fp.write(text + "\n") def LocalPathify(self, path): """Convert a subdirectory-relative path into a normalized path which starts with the make variable $(LOCAL_PATH) (i.e. the top of the project tree). Absolute paths, or paths that contain variables, are just normalized.""" if "$(" in path or os.path.isabs(path): # path is not a file in the project tree in this case, but calling # normpath is still important for trimming trailing slashes. return os.path.normpath(path) local_path = os.path.join("$(LOCAL_PATH)", self.path, path) local_path = os.path.normpath(local_path) # Check that normalizing the path didn't ../ itself out of $(LOCAL_PATH) # - i.e. that the resulting path is still inside the project tree. The # path may legitimately have ended up containing just $(LOCAL_PATH), though, # so we don't look for a slash. assert local_path.startswith( "$(LOCAL_PATH)" ), f"Path {path} attempts to escape from gyp path {self.path} !)" return local_path def ExpandInputRoot(self, template, expansion, dirname): if "%(INPUT_ROOT)s" not in template and "%(INPUT_DIRNAME)s" not in template: return template path = template % { "INPUT_ROOT": expansion, "INPUT_DIRNAME": dirname, } return os.path.normpath(path) def PerformBuild(data, configurations, params): # The android backend only supports the default configuration. options = params["options"] makefile = os.path.abspath(os.path.join(options.toplevel_dir, "GypAndroid.mk")) env = dict(os.environ) env["ONE_SHOT_MAKEFILE"] = makefile arguments = ["make", "-C", os.environ["ANDROID_BUILD_TOP"], "gyp_all_modules"] print("Building: %s" % arguments) subprocess.check_call(arguments, env=env) def GenerateOutput(target_list, target_dicts, data, params): options = params["options"] generator_flags = params.get("generator_flags", {}) limit_to_target_all = generator_flags.get("limit_to_target_all", False) write_alias_targets = generator_flags.get("write_alias_targets", True) sdk_version = generator_flags.get("aosp_sdk_version", 0) android_top_dir = os.environ.get("ANDROID_BUILD_TOP") assert android_top_dir, "$ANDROID_BUILD_TOP not set; you need to run lunch." def CalculateMakefilePath(build_file, base_name): """Determine where to write a Makefile for a given gyp file.""" # Paths in gyp files are relative to the .gyp file, but we want # paths relative to the source root for the master makefile. Grab # the path of the .gyp file as the base to relativize against. # E.g. "foo/bar" when we're constructing targets for "foo/bar/baz.gyp". base_path = gyp.common.RelativePath(os.path.dirname(build_file), options.depth) # We write the file in the base_path directory. output_file = os.path.join(options.depth, base_path, base_name) assert ( not options.generator_output ), "The Android backend does not support options.generator_output." base_path = gyp.common.RelativePath( os.path.dirname(build_file), options.toplevel_dir ) return base_path, output_file # TODO: search for the first non-'Default' target. This can go # away when we add verification that all targets have the # necessary configurations. default_configuration = None for target in target_list: spec = target_dicts[target] if spec["default_configuration"] != "Default": default_configuration = spec["default_configuration"] break if not default_configuration: default_configuration = "Default" makefile_name = "GypAndroid" + options.suffix + ".mk" makefile_path = os.path.join(options.toplevel_dir, makefile_name) assert ( not options.generator_output ), "The Android backend does not support options.generator_output." gyp.common.EnsureDirExists(makefile_path) root_makefile = open(makefile_path, "w") root_makefile.write(header) # We set LOCAL_PATH just once, here, to the top of the project tree. This # allows all the other paths we use to be relative to the Android.mk file, # as the Android build system expects. root_makefile.write("\nLOCAL_PATH := $(call my-dir)\n") # Find the list of targets that derive from the gyp file(s) being built. needed_targets = set() for build_file in params["build_files"]: for target in gyp.common.AllTargets(target_list, target_dicts, build_file): needed_targets.add(target) build_files = set() include_list = set() android_modules = {} for qualified_target in target_list: build_file, target, toolset = gyp.common.ParseQualifiedTarget(qualified_target) relative_build_file = gyp.common.RelativePath(build_file, options.toplevel_dir) build_files.add(relative_build_file) included_files = data[build_file]["included_files"] for included_file in included_files: # The included_files entries are relative to the dir of the build file # that included them, so we have to undo that and then make them relative # to the root dir. relative_include_file = gyp.common.RelativePath( gyp.common.UnrelativePath(included_file, build_file), options.toplevel_dir, ) abs_include_file = os.path.abspath(relative_include_file) # If the include file is from the ~/.gyp dir, we should use absolute path # so that relocating the src dir doesn't break the path. if params["home_dot_gyp"] and abs_include_file.startswith( params["home_dot_gyp"] ): build_files.add(abs_include_file) else: build_files.add(relative_include_file) base_path, output_file = CalculateMakefilePath( build_file, target + "." + toolset + options.suffix + ".mk" ) spec = target_dicts[qualified_target] configs = spec["configurations"] part_of_all = qualified_target in needed_targets if limit_to_target_all and not part_of_all: continue relative_target = gyp.common.QualifiedTarget( relative_build_file, target, toolset ) writer = AndroidMkWriter(android_top_dir) android_module = writer.Write( qualified_target, relative_target, base_path, output_file, spec, configs, part_of_all=part_of_all, write_alias_target=write_alias_targets, sdk_version=sdk_version, ) if android_module in android_modules: print( "ERROR: Android module names must be unique. The following " "targets both generate Android module name %s.\n %s\n %s" % (android_module, android_modules[android_module], qualified_target) ) return android_modules[android_module] = qualified_target # Our root_makefile lives at the source root. Compute the relative path # from there to the output_file for including. mkfile_rel_path = gyp.common.RelativePath( output_file, os.path.dirname(makefile_path) ) include_list.add(mkfile_rel_path) root_makefile.write("GYP_CONFIGURATION ?= %s\n" % default_configuration) root_makefile.write("GYP_VAR_PREFIX ?=\n") root_makefile.write("GYP_HOST_VAR_PREFIX ?=\n") root_makefile.write("GYP_HOST_MULTILIB ?= first\n") # Write out the sorted list of includes. root_makefile.write("\n") for include_file in sorted(include_list): root_makefile.write("include $(LOCAL_PATH)/" + include_file + "\n") root_makefile.write("\n") if write_alias_targets: root_makefile.write(ALL_MODULES_FOOTER) root_makefile.close() PK ~\v&2''"node-gyp/gyp/pylib/gyp/MSVSUtil.pynu[# Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Utility functions shared amongst the Windows generators.""" import copy import os # A dictionary mapping supported target types to extensions. TARGET_TYPE_EXT = { "executable": "exe", "loadable_module": "dll", "shared_library": "dll", "static_library": "lib", "windows_driver": "sys", } def _GetLargePdbShimCcPath(): """Returns the path of the large_pdb_shim.cc file.""" this_dir = os.path.abspath(os.path.dirname(__file__)) src_dir = os.path.abspath(os.path.join(this_dir, "..", "..")) win_data_dir = os.path.join(src_dir, "data", "win") large_pdb_shim_cc = os.path.join(win_data_dir, "large-pdb-shim.cc") return large_pdb_shim_cc def _DeepCopySomeKeys(in_dict, keys): """Performs a partial deep-copy on |in_dict|, only copying the keys in |keys|. Arguments: in_dict: The dictionary to copy. keys: The keys to be copied. If a key is in this list and doesn't exist in |in_dict| this is not an error. Returns: The partially deep-copied dictionary. """ d = {} for key in keys: if key not in in_dict: continue d[key] = copy.deepcopy(in_dict[key]) return d def _SuffixName(name, suffix): """Add a suffix to the end of a target. Arguments: name: name of the target (foo#target) suffix: the suffix to be added Returns: Target name with suffix added (foo_suffix#target) """ parts = name.rsplit("#", 1) parts[0] = f"{parts[0]}_{suffix}" return "#".join(parts) def _ShardName(name, number): """Add a shard number to the end of a target. Arguments: name: name of the target (foo#target) number: shard number Returns: Target name with shard added (foo_1#target) """ return _SuffixName(name, str(number)) def ShardTargets(target_list, target_dicts): """Shard some targets apart to work around the linkers limits. Arguments: target_list: List of target pairs: 'base/base.gyp:base'. target_dicts: Dict of target properties keyed on target pair. Returns: Tuple of the new sharded versions of the inputs. """ # Gather the targets to shard, and how many pieces. targets_to_shard = {} for t in target_dicts: shards = int(target_dicts[t].get("msvs_shard", 0)) if shards: targets_to_shard[t] = shards # Shard target_list. new_target_list = [] for t in target_list: if t in targets_to_shard: for i in range(targets_to_shard[t]): new_target_list.append(_ShardName(t, i)) else: new_target_list.append(t) # Shard target_dict. new_target_dicts = {} for t in target_dicts: if t in targets_to_shard: for i in range(targets_to_shard[t]): name = _ShardName(t, i) new_target_dicts[name] = copy.copy(target_dicts[t]) new_target_dicts[name]["target_name"] = _ShardName( new_target_dicts[name]["target_name"], i ) sources = new_target_dicts[name].get("sources", []) new_sources = [] for pos in range(i, len(sources), targets_to_shard[t]): new_sources.append(sources[pos]) new_target_dicts[name]["sources"] = new_sources else: new_target_dicts[t] = target_dicts[t] # Shard dependencies. for t in sorted(new_target_dicts): for deptype in ("dependencies", "dependencies_original"): dependencies = copy.copy(new_target_dicts[t].get(deptype, [])) new_dependencies = [] for d in dependencies: if d in targets_to_shard: for i in range(targets_to_shard[d]): new_dependencies.append(_ShardName(d, i)) else: new_dependencies.append(d) new_target_dicts[t][deptype] = new_dependencies return (new_target_list, new_target_dicts) def _GetPdbPath(target_dict, config_name, vars): """Returns the path to the PDB file that will be generated by a given configuration. The lookup proceeds as follows: - Look for an explicit path in the VCLinkerTool configuration block. - Look for an 'msvs_large_pdb_path' variable. - Use '<(PRODUCT_DIR)/<(product_name).(exe|dll).pdb' if 'product_name' is specified. - Use '<(PRODUCT_DIR)/<(target_name).(exe|dll).pdb'. Arguments: target_dict: The target dictionary to be searched. config_name: The name of the configuration of interest. vars: A dictionary of common GYP variables with generator-specific values. Returns: The path of the corresponding PDB file. """ config = target_dict["configurations"][config_name] msvs = config.setdefault("msvs_settings", {}) linker = msvs.get("VCLinkerTool", {}) pdb_path = linker.get("ProgramDatabaseFile") if pdb_path: return pdb_path variables = target_dict.get("variables", {}) pdb_path = variables.get("msvs_large_pdb_path", None) if pdb_path: return pdb_path pdb_base = target_dict.get("product_name", target_dict["target_name"]) pdb_base = "{}.{}.pdb".format(pdb_base, TARGET_TYPE_EXT[target_dict["type"]]) pdb_path = vars["PRODUCT_DIR"] + "/" + pdb_base return pdb_path def InsertLargePdbShims(target_list, target_dicts, vars): """Insert a shim target that forces the linker to use 4KB pagesize PDBs. This is a workaround for targets with PDBs greater than 1GB in size, the limit for the 1KB pagesize PDBs created by the linker by default. Arguments: target_list: List of target pairs: 'base/base.gyp:base'. target_dicts: Dict of target properties keyed on target pair. vars: A dictionary of common GYP variables with generator-specific values. Returns: Tuple of the shimmed version of the inputs. """ # Determine which targets need shimming. targets_to_shim = [] for t in target_dicts: target_dict = target_dicts[t] # We only want to shim targets that have msvs_large_pdb enabled. if not int(target_dict.get("msvs_large_pdb", 0)): continue # This is intended for executable, shared_library and loadable_module # targets where every configuration is set up to produce a PDB output. # If any of these conditions is not true then the shim logic will fail # below. targets_to_shim.append(t) large_pdb_shim_cc = _GetLargePdbShimCcPath() for t in targets_to_shim: target_dict = target_dicts[t] target_name = target_dict.get("target_name") base_dict = _DeepCopySomeKeys( target_dict, ["configurations", "default_configuration", "toolset"] ) # This is the dict for copying the source file (part of the GYP tree) # to the intermediate directory of the project. This is necessary because # we can't always build a relative path to the shim source file (on Windows # GYP and the project may be on different drives), and Ninja hates absolute # paths (it ends up generating the .obj and .obj.d alongside the source # file, polluting GYPs tree). copy_suffix = "large_pdb_copy" copy_target_name = target_name + "_" + copy_suffix full_copy_target_name = _SuffixName(t, copy_suffix) shim_cc_basename = os.path.basename(large_pdb_shim_cc) shim_cc_dir = vars["SHARED_INTERMEDIATE_DIR"] + "/" + copy_target_name shim_cc_path = shim_cc_dir + "/" + shim_cc_basename copy_dict = copy.deepcopy(base_dict) copy_dict["target_name"] = copy_target_name copy_dict["type"] = "none" copy_dict["sources"] = [large_pdb_shim_cc] copy_dict["copies"] = [ {"destination": shim_cc_dir, "files": [large_pdb_shim_cc]} ] # This is the dict for the PDB generating shim target. It depends on the # copy target. shim_suffix = "large_pdb_shim" shim_target_name = target_name + "_" + shim_suffix full_shim_target_name = _SuffixName(t, shim_suffix) shim_dict = copy.deepcopy(base_dict) shim_dict["target_name"] = shim_target_name shim_dict["type"] = "static_library" shim_dict["sources"] = [shim_cc_path] shim_dict["dependencies"] = [full_copy_target_name] # Set up the shim to output its PDB to the same location as the final linker # target. for config_name, config in shim_dict.get("configurations").items(): pdb_path = _GetPdbPath(target_dict, config_name, vars) # A few keys that we don't want to propagate. for key in ["msvs_precompiled_header", "msvs_precompiled_source", "test"]: config.pop(key, None) msvs = config.setdefault("msvs_settings", {}) # Update the compiler directives in the shim target. compiler = msvs.setdefault("VCCLCompilerTool", {}) compiler["DebugInformationFormat"] = "3" compiler["ProgramDataBaseFileName"] = pdb_path # Set the explicit PDB path in the appropriate configuration of the # original target. config = target_dict["configurations"][config_name] msvs = config.setdefault("msvs_settings", {}) linker = msvs.setdefault("VCLinkerTool", {}) linker["GenerateDebugInformation"] = "true" linker["ProgramDatabaseFile"] = pdb_path # Add the new targets. They must go to the beginning of the list so that # the dependency generation works as expected in ninja. target_list.insert(0, full_copy_target_name) target_list.insert(0, full_shim_target_name) target_dicts[full_copy_target_name] = copy_dict target_dicts[full_shim_target_name] = shim_dict # Update the original target to depend on the shim target. target_dict.setdefault("dependencies", []).append(full_shim_target_name) return (target_list, target_dicts) PK ~\&&node-gyp/gyp/pylib/gyp/MSVSUserFile.pynu[# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Visual Studio user preferences file writer.""" import os import re import socket # for gethostname import gyp.easy_xml as easy_xml # ------------------------------------------------------------------------------ def _FindCommandInPath(command): """If there are no slashes in the command given, this function searches the PATH env to find the given command, and converts it to an absolute path. We have to do this because MSVS is looking for an actual file to launch a debugger on, not just a command line. Note that this happens at GYP time, so anything needing to be built needs to have a full path.""" if "/" in command or "\\" in command: # If the command already has path elements (either relative or # absolute), then assume it is constructed properly. return command else: # Search through the path list and find an existing file that # we can access. paths = os.environ.get("PATH", "").split(os.pathsep) for path in paths: item = os.path.join(path, command) if os.path.isfile(item) and os.access(item, os.X_OK): return item return command def _QuoteWin32CommandLineArgs(args): new_args = [] for arg in args: # Replace all double-quotes with double-double-quotes to escape # them for cmd shell, and then quote the whole thing if there # are any. if arg.find('"') != -1: arg = '""'.join(arg.split('"')) arg = '"%s"' % arg # Otherwise, if there are any spaces, quote the whole arg. elif re.search(r"[ \t\n]", arg): arg = '"%s"' % arg new_args.append(arg) return new_args class Writer: """Visual Studio XML user user file writer.""" def __init__(self, user_file_path, version, name): """Initializes the user file. Args: user_file_path: Path to the user file. version: Version info. name: Name of the user file. """ self.user_file_path = user_file_path self.version = version self.name = name self.configurations = {} def AddConfig(self, name): """Adds a configuration to the project. Args: name: Configuration name. """ self.configurations[name] = ["Configuration", {"Name": name}] def AddDebugSettings( self, config_name, command, environment={}, working_directory="" ): """Adds a DebugSettings node to the user file for a particular config. Args: command: command line to run. First element in the list is the executable. All elements of the command will be quoted if necessary. working_directory: other files which may trigger the rule. (optional) """ command = _QuoteWin32CommandLineArgs(command) abs_command = _FindCommandInPath(command[0]) if environment and isinstance(environment, dict): env_list = [f'{key}="{val}"' for (key, val) in environment.items()] environment = " ".join(env_list) else: environment = "" n_cmd = [ "DebugSettings", { "Command": abs_command, "WorkingDirectory": working_directory, "CommandArguments": " ".join(command[1:]), "RemoteMachine": socket.gethostname(), "Environment": environment, "EnvironmentMerge": "true", # Currently these are all "dummy" values that we're just setting # in the default manner that MSVS does it. We could use some of # these to add additional capabilities, I suppose, but they might # not have parity with other platforms then. "Attach": "false", "DebuggerType": "3", # 'auto' debugger "Remote": "1", "RemoteCommand": "", "HttpUrl": "", "PDBPath": "", "SQLDebugging": "", "DebuggerFlavor": "0", "MPIRunCommand": "", "MPIRunArguments": "", "MPIRunWorkingDirectory": "", "ApplicationCommand": "", "ApplicationArguments": "", "ShimCommand": "", "MPIAcceptMode": "", "MPIAcceptFilter": "", }, ] # Find the config, and add it if it doesn't exist. if config_name not in self.configurations: self.AddConfig(config_name) # Add the DebugSettings onto the appropriate config. self.configurations[config_name].append(n_cmd) def WriteIfChanged(self): """Writes the user file.""" configs = ["Configurations"] for config, spec in sorted(self.configurations.items()): configs.append(spec) content = [ "VisualStudioUserFile", {"Version": self.version.ProjectVersion(), "Name": self.name}, configs, ] easy_xml.WriteXmlIfChanged( content, self.user_file_path, encoding="Windows-1252" ) PK ~\uSE &node-gyp/gyp/pylib/gyp/MSVSSettings.pynu[# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. r"""Code to validate and convert settings of the Microsoft build tools. This file contains code to validate and convert settings of the Microsoft build tools. The function ConvertToMSBuildSettings(), ValidateMSVSSettings(), and ValidateMSBuildSettings() are the entry points. This file was created by comparing the projects created by Visual Studio 2008 and Visual Studio 2010 for all available settings through the user interface. The MSBuild schemas were also considered. They are typically found in the MSBuild install directory, e.g. c:\Program Files (x86)\MSBuild """ import re import sys # Dictionaries of settings validators. The key is the tool name, the value is # a dictionary mapping setting names to validation functions. _msvs_validators = {} _msbuild_validators = {} # A dictionary of settings converters. The key is the tool name, the value is # a dictionary mapping setting names to conversion functions. _msvs_to_msbuild_converters = {} # Tool name mapping from MSVS to MSBuild. _msbuild_name_of_tool = {} class _Tool: """Represents a tool used by MSVS or MSBuild. Attributes: msvs_name: The name of the tool in MSVS. msbuild_name: The name of the tool in MSBuild. """ def __init__(self, msvs_name, msbuild_name): self.msvs_name = msvs_name self.msbuild_name = msbuild_name def _AddTool(tool): """Adds a tool to the four dictionaries used to process settings. This only defines the tool. Each setting also needs to be added. Args: tool: The _Tool object to be added. """ _msvs_validators[tool.msvs_name] = {} _msbuild_validators[tool.msbuild_name] = {} _msvs_to_msbuild_converters[tool.msvs_name] = {} _msbuild_name_of_tool[tool.msvs_name] = tool.msbuild_name def _GetMSBuildToolSettings(msbuild_settings, tool): """Returns an MSBuild tool dictionary. Creates it if needed.""" return msbuild_settings.setdefault(tool.msbuild_name, {}) class _Type: """Type of settings (Base class).""" def ValidateMSVS(self, value): """Verifies that the value is legal for MSVS. Args: value: the value to check for this type. Raises: ValueError if value is not valid for MSVS. """ def ValidateMSBuild(self, value): """Verifies that the value is legal for MSBuild. Args: value: the value to check for this type. Raises: ValueError if value is not valid for MSBuild. """ def ConvertToMSBuild(self, value): """Returns the MSBuild equivalent of the MSVS value given. Args: value: the MSVS value to convert. Returns: the MSBuild equivalent. Raises: ValueError if value is not valid. """ return value class _String(_Type): """A setting that's just a string.""" def ValidateMSVS(self, value): if not isinstance(value, str): raise ValueError("expected string; got %r" % value) def ValidateMSBuild(self, value): if not isinstance(value, str): raise ValueError("expected string; got %r" % value) def ConvertToMSBuild(self, value): # Convert the macros return ConvertVCMacrosToMSBuild(value) class _StringList(_Type): """A settings that's a list of strings.""" def ValidateMSVS(self, value): if not isinstance(value, (list, str)): raise ValueError("expected string list; got %r" % value) def ValidateMSBuild(self, value): if not isinstance(value, (list, str)): raise ValueError("expected string list; got %r" % value) def ConvertToMSBuild(self, value): # Convert the macros if isinstance(value, list): return [ConvertVCMacrosToMSBuild(i) for i in value] else: return ConvertVCMacrosToMSBuild(value) class _Boolean(_Type): """Boolean settings, can have the values 'false' or 'true'.""" def _Validate(self, value): if value not in {"true", "false"}: raise ValueError("expected bool; got %r" % value) def ValidateMSVS(self, value): self._Validate(value) def ValidateMSBuild(self, value): self._Validate(value) def ConvertToMSBuild(self, value): self._Validate(value) return value class _Integer(_Type): """Integer settings.""" def __init__(self, msbuild_base=10): _Type.__init__(self) self._msbuild_base = msbuild_base def ValidateMSVS(self, value): # Try to convert, this will raise ValueError if invalid. self.ConvertToMSBuild(value) def ValidateMSBuild(self, value): # Try to convert, this will raise ValueError if invalid. int(value, self._msbuild_base) def ConvertToMSBuild(self, value): msbuild_format = (self._msbuild_base == 10) and "%d" or "0x%04x" return msbuild_format % int(value) class _Enumeration(_Type): """Type of settings that is an enumeration. In MSVS, the values are indexes like '0', '1', and '2'. MSBuild uses text labels that are more representative, like 'Win32'. Constructor args: label_list: an array of MSBuild labels that correspond to the MSVS index. In the rare cases where MSVS has skipped an index value, None is used in the array to indicate the unused spot. new: an array of labels that are new to MSBuild. """ def __init__(self, label_list, new=None): _Type.__init__(self) self._label_list = label_list self._msbuild_values = {value for value in label_list if value is not None} if new is not None: self._msbuild_values.update(new) def ValidateMSVS(self, value): # Try to convert. It will raise an exception if not valid. self.ConvertToMSBuild(value) def ValidateMSBuild(self, value): if value not in self._msbuild_values: raise ValueError("unrecognized enumerated value %s" % value) def ConvertToMSBuild(self, value): index = int(value) if index < 0 or index >= len(self._label_list): raise ValueError( "index value (%d) not in expected range [0, %d)" % (index, len(self._label_list)) ) label = self._label_list[index] if label is None: raise ValueError("converted value for %s not specified." % value) return label # Instantiate the various generic types. _boolean = _Boolean() _integer = _Integer() # For now, we don't do any special validation on these types: _string = _String() _file_name = _String() _folder_name = _String() _file_list = _StringList() _folder_list = _StringList() _string_list = _StringList() # Some boolean settings went from numerical values to boolean. The # mapping is 0: default, 1: false, 2: true. _newly_boolean = _Enumeration(["", "false", "true"]) def _Same(tool, name, setting_type): """Defines a setting that has the same name in MSVS and MSBuild. Args: tool: a dictionary that gives the names of the tool for MSVS and MSBuild. name: the name of the setting. setting_type: the type of this setting. """ _Renamed(tool, name, name, setting_type) def _Renamed(tool, msvs_name, msbuild_name, setting_type): """Defines a setting for which the name has changed. Args: tool: a dictionary that gives the names of the tool for MSVS and MSBuild. msvs_name: the name of the MSVS setting. msbuild_name: the name of the MSBuild setting. setting_type: the type of this setting. """ def _Translate(value, msbuild_settings): msbuild_tool_settings = _GetMSBuildToolSettings(msbuild_settings, tool) msbuild_tool_settings[msbuild_name] = setting_type.ConvertToMSBuild(value) _msvs_validators[tool.msvs_name][msvs_name] = setting_type.ValidateMSVS _msbuild_validators[tool.msbuild_name][msbuild_name] = setting_type.ValidateMSBuild _msvs_to_msbuild_converters[tool.msvs_name][msvs_name] = _Translate def _Moved(tool, settings_name, msbuild_tool_name, setting_type): _MovedAndRenamed( tool, settings_name, msbuild_tool_name, settings_name, setting_type ) def _MovedAndRenamed( tool, msvs_settings_name, msbuild_tool_name, msbuild_settings_name, setting_type ): """Defines a setting that may have moved to a new section. Args: tool: a dictionary that gives the names of the tool for MSVS and MSBuild. msvs_settings_name: the MSVS name of the setting. msbuild_tool_name: the name of the MSBuild tool to place the setting under. msbuild_settings_name: the MSBuild name of the setting. setting_type: the type of this setting. """ def _Translate(value, msbuild_settings): tool_settings = msbuild_settings.setdefault(msbuild_tool_name, {}) tool_settings[msbuild_settings_name] = setting_type.ConvertToMSBuild(value) _msvs_validators[tool.msvs_name][msvs_settings_name] = setting_type.ValidateMSVS validator = setting_type.ValidateMSBuild _msbuild_validators[msbuild_tool_name][msbuild_settings_name] = validator _msvs_to_msbuild_converters[tool.msvs_name][msvs_settings_name] = _Translate def _MSVSOnly(tool, name, setting_type): """Defines a setting that is only found in MSVS. Args: tool: a dictionary that gives the names of the tool for MSVS and MSBuild. name: the name of the setting. setting_type: the type of this setting. """ def _Translate(unused_value, unused_msbuild_settings): # Since this is for MSVS only settings, no translation will happen. pass _msvs_validators[tool.msvs_name][name] = setting_type.ValidateMSVS _msvs_to_msbuild_converters[tool.msvs_name][name] = _Translate def _MSBuildOnly(tool, name, setting_type): """Defines a setting that is only found in MSBuild. Args: tool: a dictionary that gives the names of the tool for MSVS and MSBuild. name: the name of the setting. setting_type: the type of this setting. """ def _Translate(value, msbuild_settings): # Let msbuild-only properties get translated as-is from msvs_settings. tool_settings = msbuild_settings.setdefault(tool.msbuild_name, {}) tool_settings[name] = value _msbuild_validators[tool.msbuild_name][name] = setting_type.ValidateMSBuild _msvs_to_msbuild_converters[tool.msvs_name][name] = _Translate def _ConvertedToAdditionalOption(tool, msvs_name, flag): """Defines a setting that's handled via a command line option in MSBuild. Args: tool: a dictionary that gives the names of the tool for MSVS and MSBuild. msvs_name: the name of the MSVS setting that if 'true' becomes a flag flag: the flag to insert at the end of the AdditionalOptions """ def _Translate(value, msbuild_settings): if value == "true": tool_settings = _GetMSBuildToolSettings(msbuild_settings, tool) if "AdditionalOptions" in tool_settings: new_flags = "{} {}".format(tool_settings["AdditionalOptions"], flag) else: new_flags = flag tool_settings["AdditionalOptions"] = new_flags _msvs_validators[tool.msvs_name][msvs_name] = _boolean.ValidateMSVS _msvs_to_msbuild_converters[tool.msvs_name][msvs_name] = _Translate def _CustomGeneratePreprocessedFile(tool, msvs_name): def _Translate(value, msbuild_settings): tool_settings = _GetMSBuildToolSettings(msbuild_settings, tool) if value == "0": tool_settings["PreprocessToFile"] = "false" tool_settings["PreprocessSuppressLineNumbers"] = "false" elif value == "1": # /P tool_settings["PreprocessToFile"] = "true" tool_settings["PreprocessSuppressLineNumbers"] = "false" elif value == "2": # /EP /P tool_settings["PreprocessToFile"] = "true" tool_settings["PreprocessSuppressLineNumbers"] = "true" else: raise ValueError("value must be one of [0, 1, 2]; got %s" % value) # Create a bogus validator that looks for '0', '1', or '2' msvs_validator = _Enumeration(["a", "b", "c"]).ValidateMSVS _msvs_validators[tool.msvs_name][msvs_name] = msvs_validator msbuild_validator = _boolean.ValidateMSBuild msbuild_tool_validators = _msbuild_validators[tool.msbuild_name] msbuild_tool_validators["PreprocessToFile"] = msbuild_validator msbuild_tool_validators["PreprocessSuppressLineNumbers"] = msbuild_validator _msvs_to_msbuild_converters[tool.msvs_name][msvs_name] = _Translate fix_vc_macro_slashes_regex_list = ("IntDir", "OutDir") fix_vc_macro_slashes_regex = re.compile( r"(\$\((?:%s)\))(?:[\\/]+)" % "|".join(fix_vc_macro_slashes_regex_list) ) # Regular expression to detect keys that were generated by exclusion lists _EXCLUDED_SUFFIX_RE = re.compile("^(.*)_excluded$") def _ValidateExclusionSetting(setting, settings, error_msg, stderr=sys.stderr): """Verify that 'setting' is valid if it is generated from an exclusion list. If the setting appears to be generated from an exclusion list, the root name is checked. Args: setting: A string that is the setting name to validate settings: A dictionary where the keys are valid settings error_msg: The message to emit in the event of error stderr: The stream receiving the error messages. """ # This may be unrecognized because it's an exclusion list. If the # setting name has the _excluded suffix, then check the root name. unrecognized = True m = re.match(_EXCLUDED_SUFFIX_RE, setting) if m: root_setting = m.group(1) unrecognized = root_setting not in settings if unrecognized: # We don't know this setting. Give a warning. print(error_msg, file=stderr) def FixVCMacroSlashes(s): """Replace macros which have excessive following slashes. These macros are known to have a built-in trailing slash. Furthermore, many scripts hiccup on processing paths with extra slashes in the middle. This list is probably not exhaustive. Add as needed. """ if "$" in s: s = fix_vc_macro_slashes_regex.sub(r"\1", s) return s def ConvertVCMacrosToMSBuild(s): """Convert the MSVS macros found in the string to the MSBuild equivalent. This list is probably not exhaustive. Add as needed. """ if "$" in s: replace_map = { "$(ConfigurationName)": "$(Configuration)", "$(InputDir)": "%(RelativeDir)", "$(InputExt)": "%(Extension)", "$(InputFileName)": "%(Filename)%(Extension)", "$(InputName)": "%(Filename)", "$(InputPath)": "%(Identity)", "$(ParentName)": "$(ProjectFileName)", "$(PlatformName)": "$(Platform)", "$(SafeInputName)": "%(Filename)", } for old, new in replace_map.items(): s = s.replace(old, new) s = FixVCMacroSlashes(s) return s def ConvertToMSBuildSettings(msvs_settings, stderr=sys.stderr): """Converts MSVS settings (VS2008 and earlier) to MSBuild settings (VS2010+). Args: msvs_settings: A dictionary. The key is the tool name. The values are themselves dictionaries of settings and their values. stderr: The stream receiving the error messages. Returns: A dictionary of MSBuild settings. The key is either the MSBuild tool name or the empty string (for the global settings). The values are themselves dictionaries of settings and their values. """ msbuild_settings = {} for msvs_tool_name, msvs_tool_settings in msvs_settings.items(): if msvs_tool_name in _msvs_to_msbuild_converters: msvs_tool = _msvs_to_msbuild_converters[msvs_tool_name] for msvs_setting, msvs_value in msvs_tool_settings.items(): if msvs_setting in msvs_tool: # Invoke the translation function. try: msvs_tool[msvs_setting](msvs_value, msbuild_settings) except ValueError as e: print( "Warning: while converting %s/%s to MSBuild, " "%s" % (msvs_tool_name, msvs_setting, e), file=stderr, ) else: _ValidateExclusionSetting( msvs_setting, msvs_tool, ( "Warning: unrecognized setting %s/%s " "while converting to MSBuild." % (msvs_tool_name, msvs_setting) ), stderr, ) else: print( "Warning: unrecognized tool %s while converting to " "MSBuild." % msvs_tool_name, file=stderr, ) return msbuild_settings def ValidateMSVSSettings(settings, stderr=sys.stderr): """Validates that the names of the settings are valid for MSVS. Args: settings: A dictionary. The key is the tool name. The values are themselves dictionaries of settings and their values. stderr: The stream receiving the error messages. """ _ValidateSettings(_msvs_validators, settings, stderr) def ValidateMSBuildSettings(settings, stderr=sys.stderr): """Validates that the names of the settings are valid for MSBuild. Args: settings: A dictionary. The key is the tool name. The values are themselves dictionaries of settings and their values. stderr: The stream receiving the error messages. """ _ValidateSettings(_msbuild_validators, settings, stderr) def _ValidateSettings(validators, settings, stderr): """Validates that the settings are valid for MSBuild or MSVS. We currently only validate the names of the settings, not their values. Args: validators: A dictionary of tools and their validators. settings: A dictionary. The key is the tool name. The values are themselves dictionaries of settings and their values. stderr: The stream receiving the error messages. """ for tool_name in settings: if tool_name in validators: tool_validators = validators[tool_name] for setting, value in settings[tool_name].items(): if setting in tool_validators: try: tool_validators[setting](value) except ValueError as e: print( f"Warning: for {tool_name}/{setting}, {e}", file=stderr, ) else: _ValidateExclusionSetting( setting, tool_validators, (f"Warning: unrecognized setting {tool_name}/{setting}"), stderr, ) else: print("Warning: unrecognized tool %s" % (tool_name), file=stderr) # MSVS and MBuild names of the tools. _compile = _Tool("VCCLCompilerTool", "ClCompile") _link = _Tool("VCLinkerTool", "Link") _midl = _Tool("VCMIDLTool", "Midl") _rc = _Tool("VCResourceCompilerTool", "ResourceCompile") _lib = _Tool("VCLibrarianTool", "Lib") _manifest = _Tool("VCManifestTool", "Manifest") _masm = _Tool("MASM", "MASM") _armasm = _Tool("ARMASM", "ARMASM") _AddTool(_compile) _AddTool(_link) _AddTool(_midl) _AddTool(_rc) _AddTool(_lib) _AddTool(_manifest) _AddTool(_masm) _AddTool(_armasm) # Add sections only found in the MSBuild settings. _msbuild_validators[""] = {} _msbuild_validators["ProjectReference"] = {} _msbuild_validators["ManifestResourceCompile"] = {} # Descriptions of the compiler options, i.e. VCCLCompilerTool in MSVS and # ClCompile in MSBuild. # See "c:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\1033\cl.xml" for # the schema of the MSBuild ClCompile settings. # Options that have the same name in MSVS and MSBuild _Same(_compile, "AdditionalIncludeDirectories", _folder_list) # /I _Same(_compile, "AdditionalOptions", _string_list) _Same(_compile, "AdditionalUsingDirectories", _folder_list) # /AI _Same(_compile, "AssemblerListingLocation", _file_name) # /Fa _Same(_compile, "BrowseInformationFile", _file_name) _Same(_compile, "BufferSecurityCheck", _boolean) # /GS _Same(_compile, "DisableLanguageExtensions", _boolean) # /Za _Same(_compile, "DisableSpecificWarnings", _string_list) # /wd _Same(_compile, "EnableFiberSafeOptimizations", _boolean) # /GT _Same(_compile, "EnablePREfast", _boolean) # /analyze Visible='false' _Same(_compile, "ExpandAttributedSource", _boolean) # /Fx _Same(_compile, "FloatingPointExceptions", _boolean) # /fp:except _Same(_compile, "ForceConformanceInForLoopScope", _boolean) # /Zc:forScope _Same(_compile, "ForcedIncludeFiles", _file_list) # /FI _Same(_compile, "ForcedUsingFiles", _file_list) # /FU _Same(_compile, "GenerateXMLDocumentationFiles", _boolean) # /doc _Same(_compile, "IgnoreStandardIncludePath", _boolean) # /X _Same(_compile, "MinimalRebuild", _boolean) # /Gm _Same(_compile, "OmitDefaultLibName", _boolean) # /Zl _Same(_compile, "OmitFramePointers", _boolean) # /Oy _Same(_compile, "PreprocessorDefinitions", _string_list) # /D _Same(_compile, "ProgramDataBaseFileName", _file_name) # /Fd _Same(_compile, "RuntimeTypeInfo", _boolean) # /GR _Same(_compile, "ShowIncludes", _boolean) # /showIncludes _Same(_compile, "SmallerTypeCheck", _boolean) # /RTCc _Same(_compile, "StringPooling", _boolean) # /GF _Same(_compile, "SuppressStartupBanner", _boolean) # /nologo _Same(_compile, "TreatWChar_tAsBuiltInType", _boolean) # /Zc:wchar_t _Same(_compile, "UndefineAllPreprocessorDefinitions", _boolean) # /u _Same(_compile, "UndefinePreprocessorDefinitions", _string_list) # /U _Same(_compile, "UseFullPaths", _boolean) # /FC _Same(_compile, "WholeProgramOptimization", _boolean) # /GL _Same(_compile, "XMLDocumentationFileName", _file_name) _Same(_compile, "CompileAsWinRT", _boolean) # /ZW _Same( _compile, "AssemblerOutput", _Enumeration( [ "NoListing", "AssemblyCode", # /FA "All", # /FAcs "AssemblyAndMachineCode", # /FAc "AssemblyAndSourceCode", ] ), ) # /FAs _Same( _compile, "BasicRuntimeChecks", _Enumeration( [ "Default", "StackFrameRuntimeCheck", # /RTCs "UninitializedLocalUsageCheck", # /RTCu "EnableFastChecks", ] ), ) # /RTC1 _Same( _compile, "BrowseInformation", _Enumeration(["false", "true", "true"]) # /FR ) # /Fr _Same( _compile, "CallingConvention", _Enumeration(["Cdecl", "FastCall", "StdCall", "VectorCall"]), # /Gd # /Gr # /Gz ) # /Gv _Same( _compile, "CompileAs", _Enumeration(["Default", "CompileAsC", "CompileAsCpp"]), # /TC ) # /TP _Same( _compile, "DebugInformationFormat", _Enumeration( [ "", # Disabled "OldStyle", # /Z7 None, "ProgramDatabase", # /Zi "EditAndContinue", ] ), ) # /ZI _Same( _compile, "EnableEnhancedInstructionSet", _Enumeration( [ "NotSet", "StreamingSIMDExtensions", # /arch:SSE "StreamingSIMDExtensions2", # /arch:SSE2 "AdvancedVectorExtensions", # /arch:AVX (vs2012+) "NoExtensions", # /arch:IA32 (vs2012+) # This one only exists in the new msbuild format. "AdvancedVectorExtensions2", # /arch:AVX2 (vs2013r2+) ] ), ) _Same( _compile, "ErrorReporting", _Enumeration( [ "None", # /errorReport:none "Prompt", # /errorReport:prompt "Queue", ], # /errorReport:queue new=["Send"], ), ) # /errorReport:send" _Same( _compile, "ExceptionHandling", _Enumeration(["false", "Sync", "Async"], new=["SyncCThrow"]), # /EHsc # /EHa ) # /EHs _Same( _compile, "FavorSizeOrSpeed", _Enumeration(["Neither", "Speed", "Size"]) # /Ot ) # /Os _Same( _compile, "FloatingPointModel", _Enumeration(["Precise", "Strict", "Fast"]), # /fp:precise # /fp:strict ) # /fp:fast _Same( _compile, "InlineFunctionExpansion", _Enumeration( ["Default", "OnlyExplicitInline", "AnySuitable"], # /Ob1 # /Ob2 new=["Disabled"], ), ) # /Ob0 _Same( _compile, "Optimization", _Enumeration(["Disabled", "MinSpace", "MaxSpeed", "Full"]), # /Od # /O1 # /O2 ) # /Ox _Same( _compile, "RuntimeLibrary", _Enumeration( [ "MultiThreaded", # /MT "MultiThreadedDebug", # /MTd "MultiThreadedDLL", # /MD "MultiThreadedDebugDLL", ] ), ) # /MDd _Same( _compile, "StructMemberAlignment", _Enumeration( [ "Default", "1Byte", # /Zp1 "2Bytes", # /Zp2 "4Bytes", # /Zp4 "8Bytes", # /Zp8 "16Bytes", ] ), ) # /Zp16 _Same( _compile, "WarningLevel", _Enumeration( [ "TurnOffAllWarnings", # /W0 "Level1", # /W1 "Level2", # /W2 "Level3", # /W3 "Level4", ], # /W4 new=["EnableAllWarnings"], ), ) # /Wall # Options found in MSVS that have been renamed in MSBuild. _Renamed( _compile, "EnableFunctionLevelLinking", "FunctionLevelLinking", _boolean ) # /Gy _Renamed(_compile, "EnableIntrinsicFunctions", "IntrinsicFunctions", _boolean) # /Oi _Renamed(_compile, "KeepComments", "PreprocessKeepComments", _boolean) # /C _Renamed(_compile, "ObjectFile", "ObjectFileName", _file_name) # /Fo _Renamed(_compile, "OpenMP", "OpenMPSupport", _boolean) # /openmp _Renamed( _compile, "PrecompiledHeaderThrough", "PrecompiledHeaderFile", _file_name ) # Used with /Yc and /Yu _Renamed( _compile, "PrecompiledHeaderFile", "PrecompiledHeaderOutputFile", _file_name ) # /Fp _Renamed( _compile, "UsePrecompiledHeader", "PrecompiledHeader", _Enumeration( ["NotUsing", "Create", "Use"] # VS recognized '' for this value too. # /Yc ), ) # /Yu _Renamed(_compile, "WarnAsError", "TreatWarningAsError", _boolean) # /WX _ConvertedToAdditionalOption(_compile, "DefaultCharIsUnsigned", "/J") # MSVS options not found in MSBuild. _MSVSOnly(_compile, "Detect64BitPortabilityProblems", _boolean) _MSVSOnly(_compile, "UseUnicodeResponseFiles", _boolean) # MSBuild options not found in MSVS. _MSBuildOnly(_compile, "BuildingInIDE", _boolean) _MSBuildOnly( _compile, "CompileAsManaged", _Enumeration([], new=["false", "true"]) ) # /clr _MSBuildOnly(_compile, "CreateHotpatchableImage", _boolean) # /hotpatch _MSBuildOnly(_compile, "MultiProcessorCompilation", _boolean) # /MP _MSBuildOnly(_compile, "PreprocessOutputPath", _string) # /Fi _MSBuildOnly(_compile, "ProcessorNumber", _integer) # the number of processors _MSBuildOnly(_compile, "TrackerLogDirectory", _folder_name) _MSBuildOnly(_compile, "TreatSpecificWarningsAsErrors", _string_list) # /we _MSBuildOnly(_compile, "UseUnicodeForAssemblerListing", _boolean) # /FAu # Defines a setting that needs very customized processing _CustomGeneratePreprocessedFile(_compile, "GeneratePreprocessedFile") # Directives for converting MSVS VCLinkerTool to MSBuild Link. # See "c:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\1033\link.xml" for # the schema of the MSBuild Link settings. # Options that have the same name in MSVS and MSBuild _Same(_link, "AdditionalDependencies", _file_list) _Same(_link, "AdditionalLibraryDirectories", _folder_list) # /LIBPATH # /MANIFESTDEPENDENCY: _Same(_link, "AdditionalManifestDependencies", _file_list) _Same(_link, "AdditionalOptions", _string_list) _Same(_link, "AddModuleNamesToAssembly", _file_list) # /ASSEMBLYMODULE _Same(_link, "AllowIsolation", _boolean) # /ALLOWISOLATION _Same(_link, "AssemblyLinkResource", _file_list) # /ASSEMBLYLINKRESOURCE _Same(_link, "BaseAddress", _string) # /BASE _Same(_link, "CLRUnmanagedCodeCheck", _boolean) # /CLRUNMANAGEDCODECHECK _Same(_link, "DelayLoadDLLs", _file_list) # /DELAYLOAD _Same(_link, "DelaySign", _boolean) # /DELAYSIGN _Same(_link, "EmbedManagedResourceFile", _file_list) # /ASSEMBLYRESOURCE _Same(_link, "EnableUAC", _boolean) # /MANIFESTUAC _Same(_link, "EntryPointSymbol", _string) # /ENTRY _Same(_link, "ForceSymbolReferences", _file_list) # /INCLUDE _Same(_link, "FunctionOrder", _file_name) # /ORDER _Same(_link, "GenerateDebugInformation", _boolean) # /DEBUG _Same(_link, "GenerateMapFile", _boolean) # /MAP _Same(_link, "HeapCommitSize", _string) _Same(_link, "HeapReserveSize", _string) # /HEAP _Same(_link, "IgnoreAllDefaultLibraries", _boolean) # /NODEFAULTLIB _Same(_link, "IgnoreEmbeddedIDL", _boolean) # /IGNOREIDL _Same(_link, "ImportLibrary", _file_name) # /IMPLIB _Same(_link, "KeyContainer", _file_name) # /KEYCONTAINER _Same(_link, "KeyFile", _file_name) # /KEYFILE _Same(_link, "ManifestFile", _file_name) # /ManifestFile _Same(_link, "MapExports", _boolean) # /MAPINFO:EXPORTS _Same(_link, "MapFileName", _file_name) _Same(_link, "MergedIDLBaseFileName", _file_name) # /IDLOUT _Same(_link, "MergeSections", _string) # /MERGE _Same(_link, "MidlCommandFile", _file_name) # /MIDL _Same(_link, "ModuleDefinitionFile", _file_name) # /DEF _Same(_link, "OutputFile", _file_name) # /OUT _Same(_link, "PerUserRedirection", _boolean) _Same(_link, "Profile", _boolean) # /PROFILE _Same(_link, "ProfileGuidedDatabase", _file_name) # /PGD _Same(_link, "ProgramDatabaseFile", _file_name) # /PDB _Same(_link, "RegisterOutput", _boolean) _Same(_link, "SetChecksum", _boolean) # /RELEASE _Same(_link, "StackCommitSize", _string) _Same(_link, "StackReserveSize", _string) # /STACK _Same(_link, "StripPrivateSymbols", _file_name) # /PDBSTRIPPED _Same(_link, "SupportUnloadOfDelayLoadedDLL", _boolean) # /DELAY:UNLOAD _Same(_link, "SuppressStartupBanner", _boolean) # /NOLOGO _Same(_link, "SwapRunFromCD", _boolean) # /SWAPRUN:CD _Same(_link, "TurnOffAssemblyGeneration", _boolean) # /NOASSEMBLY _Same(_link, "TypeLibraryFile", _file_name) # /TLBOUT _Same(_link, "TypeLibraryResourceID", _integer) # /TLBID _Same(_link, "UACUIAccess", _boolean) # /uiAccess='true' _Same(_link, "Version", _string) # /VERSION _Same(_link, "EnableCOMDATFolding", _newly_boolean) # /OPT:ICF _Same(_link, "FixedBaseAddress", _newly_boolean) # /FIXED _Same(_link, "LargeAddressAware", _newly_boolean) # /LARGEADDRESSAWARE _Same(_link, "OptimizeReferences", _newly_boolean) # /OPT:REF _Same(_link, "RandomizedBaseAddress", _newly_boolean) # /DYNAMICBASE _Same(_link, "TerminalServerAware", _newly_boolean) # /TSAWARE _subsystem_enumeration = _Enumeration( [ "NotSet", "Console", # /SUBSYSTEM:CONSOLE "Windows", # /SUBSYSTEM:WINDOWS "Native", # /SUBSYSTEM:NATIVE "EFI Application", # /SUBSYSTEM:EFI_APPLICATION "EFI Boot Service Driver", # /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER "EFI ROM", # /SUBSYSTEM:EFI_ROM "EFI Runtime", # /SUBSYSTEM:EFI_RUNTIME_DRIVER "WindowsCE", ], # /SUBSYSTEM:WINDOWSCE new=["POSIX"], ) # /SUBSYSTEM:POSIX _target_machine_enumeration = _Enumeration( [ "NotSet", "MachineX86", # /MACHINE:X86 None, "MachineARM", # /MACHINE:ARM "MachineEBC", # /MACHINE:EBC "MachineIA64", # /MACHINE:IA64 None, "MachineMIPS", # /MACHINE:MIPS "MachineMIPS16", # /MACHINE:MIPS16 "MachineMIPSFPU", # /MACHINE:MIPSFPU "MachineMIPSFPU16", # /MACHINE:MIPSFPU16 None, None, None, "MachineSH4", # /MACHINE:SH4 None, "MachineTHUMB", # /MACHINE:THUMB "MachineX64", ] ) # /MACHINE:X64 _Same( _link, "AssemblyDebug", _Enumeration(["", "true", "false"]) # /ASSEMBLYDEBUG ) # /ASSEMBLYDEBUG:DISABLE _Same( _link, "CLRImageType", _Enumeration( [ "Default", "ForceIJWImage", # /CLRIMAGETYPE:IJW "ForcePureILImage", # /Switch="CLRIMAGETYPE:PURE "ForceSafeILImage", ] ), ) # /Switch="CLRIMAGETYPE:SAFE _Same( _link, "CLRThreadAttribute", _Enumeration( [ "DefaultThreadingAttribute", # /CLRTHREADATTRIBUTE:NONE "MTAThreadingAttribute", # /CLRTHREADATTRIBUTE:MTA "STAThreadingAttribute", ] ), ) # /CLRTHREADATTRIBUTE:STA _Same( _link, "DataExecutionPrevention", _Enumeration(["", "false", "true"]), # /NXCOMPAT:NO ) # /NXCOMPAT _Same( _link, "Driver", _Enumeration(["NotSet", "Driver", "UpOnly", "WDM"]), # /Driver # /DRIVER:UPONLY ) # /DRIVER:WDM _Same( _link, "LinkTimeCodeGeneration", _Enumeration( [ "Default", "UseLinkTimeCodeGeneration", # /LTCG "PGInstrument", # /LTCG:PGInstrument "PGOptimization", # /LTCG:PGOptimize "PGUpdate", ] ), ) # /LTCG:PGUpdate _Same( _link, "ShowProgress", _Enumeration( ["NotSet", "LinkVerbose", "LinkVerboseLib"], # /VERBOSE # /VERBOSE:Lib new=[ "LinkVerboseICF", # /VERBOSE:ICF "LinkVerboseREF", # /VERBOSE:REF "LinkVerboseSAFESEH", # /VERBOSE:SAFESEH "LinkVerboseCLR", ], ), ) # /VERBOSE:CLR _Same(_link, "SubSystem", _subsystem_enumeration) _Same(_link, "TargetMachine", _target_machine_enumeration) _Same( _link, "UACExecutionLevel", _Enumeration( [ "AsInvoker", # /level='asInvoker' "HighestAvailable", # /level='highestAvailable' "RequireAdministrator", ] ), ) # /level='requireAdministrator' _Same(_link, "MinimumRequiredVersion", _string) _Same(_link, "TreatLinkerWarningAsErrors", _boolean) # /WX # Options found in MSVS that have been renamed in MSBuild. _Renamed( _link, "ErrorReporting", "LinkErrorReporting", _Enumeration( [ "NoErrorReport", # /ERRORREPORT:NONE "PromptImmediately", # /ERRORREPORT:PROMPT "QueueForNextLogin", ], # /ERRORREPORT:QUEUE new=["SendErrorReport"], ), ) # /ERRORREPORT:SEND _Renamed( _link, "IgnoreDefaultLibraryNames", "IgnoreSpecificDefaultLibraries", _file_list ) # /NODEFAULTLIB _Renamed(_link, "ResourceOnlyDLL", "NoEntryPoint", _boolean) # /NOENTRY _Renamed(_link, "SwapRunFromNet", "SwapRunFromNET", _boolean) # /SWAPRUN:NET _Moved(_link, "GenerateManifest", "", _boolean) _Moved(_link, "IgnoreImportLibrary", "", _boolean) _Moved(_link, "LinkIncremental", "", _newly_boolean) _Moved(_link, "LinkLibraryDependencies", "ProjectReference", _boolean) _Moved(_link, "UseLibraryDependencyInputs", "ProjectReference", _boolean) # MSVS options not found in MSBuild. _MSVSOnly(_link, "OptimizeForWindows98", _newly_boolean) _MSVSOnly(_link, "UseUnicodeResponseFiles", _boolean) # MSBuild options not found in MSVS. _MSBuildOnly(_link, "BuildingInIDE", _boolean) _MSBuildOnly(_link, "ImageHasSafeExceptionHandlers", _boolean) # /SAFESEH _MSBuildOnly(_link, "LinkDLL", _boolean) # /DLL Visible='false' _MSBuildOnly(_link, "LinkStatus", _boolean) # /LTCG:STATUS _MSBuildOnly(_link, "PreventDllBinding", _boolean) # /ALLOWBIND _MSBuildOnly(_link, "SupportNobindOfDelayLoadedDLL", _boolean) # /DELAY:NOBIND _MSBuildOnly(_link, "TrackerLogDirectory", _folder_name) _MSBuildOnly(_link, "MSDOSStubFileName", _file_name) # /STUB Visible='false' _MSBuildOnly(_link, "SectionAlignment", _integer) # /ALIGN _MSBuildOnly(_link, "SpecifySectionAttributes", _string) # /SECTION _MSBuildOnly( _link, "ForceFileOutput", _Enumeration( [], new=[ "Enabled", # /FORCE # /FORCE:MULTIPLE "MultiplyDefinedSymbolOnly", "UndefinedSymbolOnly", ], ), ) # /FORCE:UNRESOLVED _MSBuildOnly( _link, "CreateHotPatchableImage", _Enumeration( [], new=[ "Enabled", # /FUNCTIONPADMIN "X86Image", # /FUNCTIONPADMIN:5 "X64Image", # /FUNCTIONPADMIN:6 "ItaniumImage", ], ), ) # /FUNCTIONPADMIN:16 _MSBuildOnly( _link, "CLRSupportLastError", _Enumeration( [], new=[ "Enabled", # /CLRSupportLastError "Disabled", # /CLRSupportLastError:NO # /CLRSupportLastError:SYSTEMDLL "SystemDlls", ], ), ) # Directives for converting VCResourceCompilerTool to ResourceCompile. # See "c:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\1033\rc.xml" for # the schema of the MSBuild ResourceCompile settings. _Same(_rc, "AdditionalOptions", _string_list) _Same(_rc, "AdditionalIncludeDirectories", _folder_list) # /I _Same(_rc, "Culture", _Integer(msbuild_base=16)) _Same(_rc, "IgnoreStandardIncludePath", _boolean) # /X _Same(_rc, "PreprocessorDefinitions", _string_list) # /D _Same(_rc, "ResourceOutputFileName", _string) # /fo _Same(_rc, "ShowProgress", _boolean) # /v # There is no UI in VisualStudio 2008 to set the following properties. # However they are found in CL and other tools. Include them here for # completeness, as they are very likely to have the same usage pattern. _Same(_rc, "SuppressStartupBanner", _boolean) # /nologo _Same(_rc, "UndefinePreprocessorDefinitions", _string_list) # /u # MSBuild options not found in MSVS. _MSBuildOnly(_rc, "NullTerminateStrings", _boolean) # /n _MSBuildOnly(_rc, "TrackerLogDirectory", _folder_name) # Directives for converting VCMIDLTool to Midl. # See "c:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\1033\midl.xml" for # the schema of the MSBuild Midl settings. _Same(_midl, "AdditionalIncludeDirectories", _folder_list) # /I _Same(_midl, "AdditionalOptions", _string_list) _Same(_midl, "CPreprocessOptions", _string) # /cpp_opt _Same(_midl, "ErrorCheckAllocations", _boolean) # /error allocation _Same(_midl, "ErrorCheckBounds", _boolean) # /error bounds_check _Same(_midl, "ErrorCheckEnumRange", _boolean) # /error enum _Same(_midl, "ErrorCheckRefPointers", _boolean) # /error ref _Same(_midl, "ErrorCheckStubData", _boolean) # /error stub_data _Same(_midl, "GenerateStublessProxies", _boolean) # /Oicf _Same(_midl, "GenerateTypeLibrary", _boolean) _Same(_midl, "HeaderFileName", _file_name) # /h _Same(_midl, "IgnoreStandardIncludePath", _boolean) # /no_def_idir _Same(_midl, "InterfaceIdentifierFileName", _file_name) # /iid _Same(_midl, "MkTypLibCompatible", _boolean) # /mktyplib203 _Same(_midl, "OutputDirectory", _string) # /out _Same(_midl, "PreprocessorDefinitions", _string_list) # /D _Same(_midl, "ProxyFileName", _file_name) # /proxy _Same(_midl, "RedirectOutputAndErrors", _file_name) # /o _Same(_midl, "SuppressStartupBanner", _boolean) # /nologo _Same(_midl, "TypeLibraryName", _file_name) # /tlb _Same(_midl, "UndefinePreprocessorDefinitions", _string_list) # /U _Same(_midl, "WarnAsError", _boolean) # /WX _Same( _midl, "DefaultCharType", _Enumeration(["Unsigned", "Signed", "Ascii"]), # /char unsigned # /char signed ) # /char ascii7 _Same( _midl, "TargetEnvironment", _Enumeration( [ "NotSet", "Win32", # /env win32 "Itanium", # /env ia64 "X64", # /env x64 "ARM64", # /env arm64 ] ), ) _Same( _midl, "EnableErrorChecks", _Enumeration(["EnableCustom", "None", "All"]), # /error none ) # /error all _Same( _midl, "StructMemberAlignment", _Enumeration(["NotSet", "1", "2", "4", "8"]), # Zp1 # Zp2 # Zp4 ) # Zp8 _Same( _midl, "WarningLevel", _Enumeration(["0", "1", "2", "3", "4"]), # /W0 # /W1 # /W2 # /W3 ) # /W4 _Renamed(_midl, "DLLDataFileName", "DllDataFileName", _file_name) # /dlldata _Renamed(_midl, "ValidateParameters", "ValidateAllParameters", _boolean) # /robust # MSBuild options not found in MSVS. _MSBuildOnly(_midl, "ApplicationConfigurationMode", _boolean) # /app_config _MSBuildOnly(_midl, "ClientStubFile", _file_name) # /cstub _MSBuildOnly( _midl, "GenerateClientFiles", _Enumeration([], new=["Stub", "None"]) # /client stub ) # /client none _MSBuildOnly( _midl, "GenerateServerFiles", _Enumeration([], new=["Stub", "None"]) # /client stub ) # /client none _MSBuildOnly(_midl, "LocaleID", _integer) # /lcid DECIMAL _MSBuildOnly(_midl, "ServerStubFile", _file_name) # /sstub _MSBuildOnly(_midl, "SuppressCompilerWarnings", _boolean) # /no_warn _MSBuildOnly(_midl, "TrackerLogDirectory", _folder_name) _MSBuildOnly( _midl, "TypeLibFormat", _Enumeration([], new=["NewFormat", "OldFormat"]) # /newtlb ) # /oldtlb # Directives for converting VCLibrarianTool to Lib. # See "c:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\1033\lib.xml" for # the schema of the MSBuild Lib settings. _Same(_lib, "AdditionalDependencies", _file_list) _Same(_lib, "AdditionalLibraryDirectories", _folder_list) # /LIBPATH _Same(_lib, "AdditionalOptions", _string_list) _Same(_lib, "ExportNamedFunctions", _string_list) # /EXPORT _Same(_lib, "ForceSymbolReferences", _string) # /INCLUDE _Same(_lib, "IgnoreAllDefaultLibraries", _boolean) # /NODEFAULTLIB _Same(_lib, "IgnoreSpecificDefaultLibraries", _file_list) # /NODEFAULTLIB _Same(_lib, "ModuleDefinitionFile", _file_name) # /DEF _Same(_lib, "OutputFile", _file_name) # /OUT _Same(_lib, "SuppressStartupBanner", _boolean) # /NOLOGO _Same(_lib, "UseUnicodeResponseFiles", _boolean) _Same(_lib, "LinkTimeCodeGeneration", _boolean) # /LTCG _Same(_lib, "TargetMachine", _target_machine_enumeration) # TODO(jeanluc) _link defines the same value that gets moved to # ProjectReference. We may want to validate that they are consistent. _Moved(_lib, "LinkLibraryDependencies", "ProjectReference", _boolean) _MSBuildOnly(_lib, "DisplayLibrary", _string) # /LIST Visible='false' _MSBuildOnly( _lib, "ErrorReporting", _Enumeration( [], new=[ "PromptImmediately", # /ERRORREPORT:PROMPT "QueueForNextLogin", # /ERRORREPORT:QUEUE "SendErrorReport", # /ERRORREPORT:SEND "NoErrorReport", ], ), ) # /ERRORREPORT:NONE _MSBuildOnly(_lib, "MinimumRequiredVersion", _string) _MSBuildOnly(_lib, "Name", _file_name) # /NAME _MSBuildOnly(_lib, "RemoveObjects", _file_list) # /REMOVE _MSBuildOnly(_lib, "SubSystem", _subsystem_enumeration) _MSBuildOnly(_lib, "TrackerLogDirectory", _folder_name) _MSBuildOnly(_lib, "TreatLibWarningAsErrors", _boolean) # /WX _MSBuildOnly(_lib, "Verbose", _boolean) # Directives for converting VCManifestTool to Mt. # See "c:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\1033\mt.xml" for # the schema of the MSBuild Lib settings. # Options that have the same name in MSVS and MSBuild _Same(_manifest, "AdditionalManifestFiles", _file_list) # /manifest _Same(_manifest, "AdditionalOptions", _string_list) _Same(_manifest, "AssemblyIdentity", _string) # /identity: _Same(_manifest, "ComponentFileName", _file_name) # /dll _Same(_manifest, "GenerateCatalogFiles", _boolean) # /makecdfs _Same(_manifest, "InputResourceManifests", _string) # /inputresource _Same(_manifest, "OutputManifestFile", _file_name) # /out _Same(_manifest, "RegistrarScriptFile", _file_name) # /rgs _Same(_manifest, "ReplacementsFile", _file_name) # /replacements _Same(_manifest, "SuppressStartupBanner", _boolean) # /nologo _Same(_manifest, "TypeLibraryFile", _file_name) # /tlb: _Same(_manifest, "UpdateFileHashes", _boolean) # /hashupdate _Same(_manifest, "UpdateFileHashesSearchPath", _file_name) _Same(_manifest, "VerboseOutput", _boolean) # /verbose # Options that have moved location. _MovedAndRenamed( _manifest, "ManifestResourceFile", "ManifestResourceCompile", "ResourceOutputFileName", _file_name, ) _Moved(_manifest, "EmbedManifest", "", _boolean) # MSVS options not found in MSBuild. _MSVSOnly(_manifest, "DependencyInformationFile", _file_name) _MSVSOnly(_manifest, "UseFAT32Workaround", _boolean) _MSVSOnly(_manifest, "UseUnicodeResponseFiles", _boolean) # MSBuild options not found in MSVS. _MSBuildOnly(_manifest, "EnableDPIAwareness", _boolean) _MSBuildOnly(_manifest, "GenerateCategoryTags", _boolean) # /category _MSBuildOnly( _manifest, "ManifestFromManagedAssembly", _file_name ) # /managedassemblyname _MSBuildOnly(_manifest, "OutputResourceManifests", _string) # /outputresource _MSBuildOnly(_manifest, "SuppressDependencyElement", _boolean) # /nodependency _MSBuildOnly(_manifest, "TrackerLogDirectory", _folder_name) # Directives for MASM. # See "$(VCTargetsPath)\BuildCustomizations\masm.xml" for the schema of the # MSBuild MASM settings. # Options that have the same name in MSVS and MSBuild. _Same(_masm, "UseSafeExceptionHandlers", _boolean) # /safeseh PK ~\o#nn'node-gyp/gyp/pylib/gyp/easy_xml_test.pynu[#!/usr/bin/env python3 # Copyright (c) 2011 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Unit tests for the easy_xml.py file. """ import gyp.easy_xml as easy_xml import unittest from io import StringIO class TestSequenceFunctions(unittest.TestCase): def setUp(self): self.stderr = StringIO() def test_EasyXml_simple(self): self.assertEqual( easy_xml.XmlToString(["test"]), '', ) self.assertEqual( easy_xml.XmlToString(["test"], encoding="Windows-1252"), '', ) def test_EasyXml_simple_with_attributes(self): self.assertEqual( easy_xml.XmlToString(["test2", {"a": "value1", "b": "value2"}]), '', ) def test_EasyXml_escaping(self): original = "'\"\r&\nfoo" converted = "<test>'" & foo" converted_apos = converted.replace("'", "'") self.assertEqual( easy_xml.XmlToString(["test3", {"a": original}, original]), '%s' % (converted, converted_apos), ) def test_EasyXml_pretty(self): self.assertEqual( easy_xml.XmlToString( ["test3", ["GrandParent", ["Parent1", ["Child"]], ["Parent2"]]], pretty=True, ), '\n' "\n" " \n" " \n" " \n" " \n" " \n" " \n" "\n", ) def test_EasyXml_complex(self): # We want to create: target = ( '' "" '' "{D2250C20-3A94-4FB9-AF73-11BC5B73884B}" "Win32Proj" "automated_ui_tests" "" '' "' "Application" "Unicode" "SpectreLoadCF" "14.36.32532" "" "" ) xml = easy_xml.XmlToString( [ "Project", [ "PropertyGroup", {"Label": "Globals"}, ["ProjectGuid", "{D2250C20-3A94-4FB9-AF73-11BC5B73884B}"], ["Keyword", "Win32Proj"], ["RootNamespace", "automated_ui_tests"], ], ["Import", {"Project": "$(VCTargetsPath)\\Microsoft.Cpp.props"}], [ "PropertyGroup", { "Condition": "'$(Configuration)|$(Platform)'=='Debug|Win32'", "Label": "Configuration", }, ["ConfigurationType", "Application"], ["CharacterSet", "Unicode"], ["SpectreMitigation", "SpectreLoadCF"], ["VCToolsVersion", "14.36.32532"], ], ] ) self.assertEqual(xml, target) if __name__ == "__main__": unittest.main() PK ~\FT&node-gyp/gyp/pylib/gyp/ninja_syntax.pynu[# This file comes from # https://github.com/martine/ninja/blob/master/misc/ninja_syntax.py # Do not edit! Edit the upstream one instead. """Python module for generating .ninja files. Note that this is emphatically not a required piece of Ninja; it's just a helpful utility for build-file-generation systems that already use Python. """ import textwrap def escape_path(word): return word.replace("$ ", "$$ ").replace(" ", "$ ").replace(":", "$:") class Writer: def __init__(self, output, width=78): self.output = output self.width = width def newline(self): self.output.write("\n") def comment(self, text): for line in textwrap.wrap(text, self.width - 2): self.output.write("# " + line + "\n") def variable(self, key, value, indent=0): if value is None: return if isinstance(value, list): value = " ".join(filter(None, value)) # Filter out empty strings. self._line(f"{key} = {value}", indent) def pool(self, name, depth): self._line("pool %s" % name) self.variable("depth", depth, indent=1) def rule( self, name, command, description=None, depfile=None, generator=False, pool=None, restat=False, rspfile=None, rspfile_content=None, deps=None, ): self._line("rule %s" % name) self.variable("command", command, indent=1) if description: self.variable("description", description, indent=1) if depfile: self.variable("depfile", depfile, indent=1) if generator: self.variable("generator", "1", indent=1) if pool: self.variable("pool", pool, indent=1) if restat: self.variable("restat", "1", indent=1) if rspfile: self.variable("rspfile", rspfile, indent=1) if rspfile_content: self.variable("rspfile_content", rspfile_content, indent=1) if deps: self.variable("deps", deps, indent=1) def build( self, outputs, rule, inputs=None, implicit=None, order_only=None, variables=None ): outputs = self._as_list(outputs) all_inputs = self._as_list(inputs)[:] out_outputs = list(map(escape_path, outputs)) all_inputs = list(map(escape_path, all_inputs)) if implicit: implicit = map(escape_path, self._as_list(implicit)) all_inputs.append("|") all_inputs.extend(implicit) if order_only: order_only = map(escape_path, self._as_list(order_only)) all_inputs.append("||") all_inputs.extend(order_only) self._line( "build {}: {}".format(" ".join(out_outputs), " ".join([rule] + all_inputs)) ) if variables: if isinstance(variables, dict): iterator = iter(variables.items()) else: iterator = iter(variables) for key, val in iterator: self.variable(key, val, indent=1) return outputs def include(self, path): self._line("include %s" % path) def subninja(self, path): self._line("subninja %s" % path) def default(self, paths): self._line("default %s" % " ".join(self._as_list(paths))) def _count_dollars_before_index(self, s, i): """Returns the number of '$' characters right in front of s[i].""" dollar_count = 0 dollar_index = i - 1 while dollar_index > 0 and s[dollar_index] == "$": dollar_count += 1 dollar_index -= 1 return dollar_count def _line(self, text, indent=0): """Write 'text' word-wrapped at self.width characters.""" leading_space = " " * indent while len(leading_space) + len(text) > self.width: # The text is too wide; wrap if possible. # Find the rightmost space that would obey our width constraint and # that's not an escaped space. available_space = self.width - len(leading_space) - len(" $") space = available_space while True: space = text.rfind(" ", 0, space) if space < 0 or self._count_dollars_before_index(text, space) % 2 == 0: break if space < 0: # No such space; just use the first unescaped space we can find. space = available_space - 1 while True: space = text.find(" ", space + 1) if ( space < 0 or self._count_dollars_before_index(text, space) % 2 == 0 ): break if space < 0: # Give up on breaking. break self.output.write(leading_space + text[0:space] + " $\n") text = text[space + 1 :] # Subsequent lines are continuations, so indent them. leading_space = " " * (indent + 2) self.output.write(leading_space + text + "\n") def _as_list(self, input): if input is None: return [] if isinstance(input, list): return input return [input] def escape(string): """Escape a string such that it can be embedded into a Ninja file without further interpretation.""" assert "\n" not in string, "Ninja syntax does not allow newlines" # We only have one special metacharacter: '$'. return string.replace("$", "$$") PK ~\&&`p9"9"+node-gyp/gyp/pylib/gyp/MSVSSettings_test.pynu[#!/usr/bin/env python3 # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Unit tests for the MSVSSettings.py file.""" import unittest import gyp.MSVSSettings as MSVSSettings from io import StringIO class TestSequenceFunctions(unittest.TestCase): def setUp(self): self.stderr = StringIO() def _ExpectedWarnings(self, expected): """Compares recorded lines to expected warnings.""" self.stderr.seek(0) actual = self.stderr.read().split("\n") actual = [line for line in actual if line] self.assertEqual(sorted(expected), sorted(actual)) def testValidateMSVSSettings_tool_names(self): """Tests that only MSVS tool names are allowed.""" MSVSSettings.ValidateMSVSSettings( { "VCCLCompilerTool": {}, "VCLinkerTool": {}, "VCMIDLTool": {}, "foo": {}, "VCResourceCompilerTool": {}, "VCLibrarianTool": {}, "VCManifestTool": {}, "ClCompile": {}, }, self.stderr, ) self._ExpectedWarnings( ["Warning: unrecognized tool foo", "Warning: unrecognized tool ClCompile"] ) def testValidateMSVSSettings_settings(self): """Tests that for invalid MSVS settings.""" MSVSSettings.ValidateMSVSSettings( { "VCCLCompilerTool": { "AdditionalIncludeDirectories": "folder1;folder2", "AdditionalOptions": ["string1", "string2"], "AdditionalUsingDirectories": "folder1;folder2", "AssemblerListingLocation": "a_file_name", "AssemblerOutput": "0", "BasicRuntimeChecks": "5", "BrowseInformation": "fdkslj", "BrowseInformationFile": "a_file_name", "BufferSecurityCheck": "true", "CallingConvention": "-1", "CompileAs": "1", "DebugInformationFormat": "2", "DefaultCharIsUnsigned": "true", "Detect64BitPortabilityProblems": "true", "DisableLanguageExtensions": "true", "DisableSpecificWarnings": "string1;string2", "EnableEnhancedInstructionSet": "1", "EnableFiberSafeOptimizations": "true", "EnableFunctionLevelLinking": "true", "EnableIntrinsicFunctions": "true", "EnablePREfast": "true", "Enableprefast": "bogus", "ErrorReporting": "1", "ExceptionHandling": "1", "ExpandAttributedSource": "true", "FavorSizeOrSpeed": "1", "FloatingPointExceptions": "true", "FloatingPointModel": "1", "ForceConformanceInForLoopScope": "true", "ForcedIncludeFiles": "file1;file2", "ForcedUsingFiles": "file1;file2", "GeneratePreprocessedFile": "1", "GenerateXMLDocumentationFiles": "true", "IgnoreStandardIncludePath": "true", "InlineFunctionExpansion": "1", "KeepComments": "true", "MinimalRebuild": "true", "ObjectFile": "a_file_name", "OmitDefaultLibName": "true", "OmitFramePointers": "true", "OpenMP": "true", "Optimization": "1", "PrecompiledHeaderFile": "a_file_name", "PrecompiledHeaderThrough": "a_file_name", "PreprocessorDefinitions": "string1;string2", "ProgramDataBaseFileName": "a_file_name", "RuntimeLibrary": "1", "RuntimeTypeInfo": "true", "ShowIncludes": "true", "SmallerTypeCheck": "true", "StringPooling": "true", "StructMemberAlignment": "1", "SuppressStartupBanner": "true", "TreatWChar_tAsBuiltInType": "true", "UndefineAllPreprocessorDefinitions": "true", "UndefinePreprocessorDefinitions": "string1;string2", "UseFullPaths": "true", "UsePrecompiledHeader": "1", "UseUnicodeResponseFiles": "true", "WarnAsError": "true", "WarningLevel": "1", "WholeProgramOptimization": "true", "XMLDocumentationFileName": "a_file_name", "ZZXYZ": "bogus", }, "VCLinkerTool": { "AdditionalDependencies": "file1;file2", "AdditionalDependencies_excluded": "file3", "AdditionalLibraryDirectories": "folder1;folder2", "AdditionalManifestDependencies": "file1;file2", "AdditionalOptions": "a string1", "AddModuleNamesToAssembly": "file1;file2", "AllowIsolation": "true", "AssemblyDebug": "2", "AssemblyLinkResource": "file1;file2", "BaseAddress": "a string1", "CLRImageType": "2", "CLRThreadAttribute": "2", "CLRUnmanagedCodeCheck": "true", "DataExecutionPrevention": "2", "DelayLoadDLLs": "file1;file2", "DelaySign": "true", "Driver": "2", "EmbedManagedResourceFile": "file1;file2", "EnableCOMDATFolding": "2", "EnableUAC": "true", "EntryPointSymbol": "a string1", "ErrorReporting": "2", "FixedBaseAddress": "2", "ForceSymbolReferences": "file1;file2", "FunctionOrder": "a_file_name", "GenerateDebugInformation": "true", "GenerateManifest": "true", "GenerateMapFile": "true", "HeapCommitSize": "a string1", "HeapReserveSize": "a string1", "IgnoreAllDefaultLibraries": "true", "IgnoreDefaultLibraryNames": "file1;file2", "IgnoreEmbeddedIDL": "true", "IgnoreImportLibrary": "true", "ImportLibrary": "a_file_name", "KeyContainer": "a_file_name", "KeyFile": "a_file_name", "LargeAddressAware": "2", "LinkIncremental": "2", "LinkLibraryDependencies": "true", "LinkTimeCodeGeneration": "2", "ManifestFile": "a_file_name", "MapExports": "true", "MapFileName": "a_file_name", "MergedIDLBaseFileName": "a_file_name", "MergeSections": "a string1", "MidlCommandFile": "a_file_name", "ModuleDefinitionFile": "a_file_name", "OptimizeForWindows98": "1", "OptimizeReferences": "2", "OutputFile": "a_file_name", "PerUserRedirection": "true", "Profile": "true", "ProfileGuidedDatabase": "a_file_name", "ProgramDatabaseFile": "a_file_name", "RandomizedBaseAddress": "2", "RegisterOutput": "true", "ResourceOnlyDLL": "true", "SetChecksum": "true", "ShowProgress": "2", "StackCommitSize": "a string1", "StackReserveSize": "a string1", "StripPrivateSymbols": "a_file_name", "SubSystem": "2", "SupportUnloadOfDelayLoadedDLL": "true", "SuppressStartupBanner": "true", "SwapRunFromCD": "true", "SwapRunFromNet": "true", "TargetMachine": "2", "TerminalServerAware": "2", "TurnOffAssemblyGeneration": "true", "TypeLibraryFile": "a_file_name", "TypeLibraryResourceID": "33", "UACExecutionLevel": "2", "UACUIAccess": "true", "UseLibraryDependencyInputs": "true", "UseUnicodeResponseFiles": "true", "Version": "a string1", }, "VCMIDLTool": { "AdditionalIncludeDirectories": "folder1;folder2", "AdditionalOptions": "a string1", "CPreprocessOptions": "a string1", "DefaultCharType": "1", "DLLDataFileName": "a_file_name", "EnableErrorChecks": "1", "ErrorCheckAllocations": "true", "ErrorCheckBounds": "true", "ErrorCheckEnumRange": "true", "ErrorCheckRefPointers": "true", "ErrorCheckStubData": "true", "GenerateStublessProxies": "true", "GenerateTypeLibrary": "true", "HeaderFileName": "a_file_name", "IgnoreStandardIncludePath": "true", "InterfaceIdentifierFileName": "a_file_name", "MkTypLibCompatible": "true", "notgood": "bogus", "OutputDirectory": "a string1", "PreprocessorDefinitions": "string1;string2", "ProxyFileName": "a_file_name", "RedirectOutputAndErrors": "a_file_name", "StructMemberAlignment": "1", "SuppressStartupBanner": "true", "TargetEnvironment": "1", "TypeLibraryName": "a_file_name", "UndefinePreprocessorDefinitions": "string1;string2", "ValidateParameters": "true", "WarnAsError": "true", "WarningLevel": "1", }, "VCResourceCompilerTool": { "AdditionalOptions": "a string1", "AdditionalIncludeDirectories": "folder1;folder2", "Culture": "1003", "IgnoreStandardIncludePath": "true", "notgood2": "bogus", "PreprocessorDefinitions": "string1;string2", "ResourceOutputFileName": "a string1", "ShowProgress": "true", "SuppressStartupBanner": "true", "UndefinePreprocessorDefinitions": "string1;string2", }, "VCLibrarianTool": { "AdditionalDependencies": "file1;file2", "AdditionalLibraryDirectories": "folder1;folder2", "AdditionalOptions": "a string1", "ExportNamedFunctions": "string1;string2", "ForceSymbolReferences": "a string1", "IgnoreAllDefaultLibraries": "true", "IgnoreSpecificDefaultLibraries": "file1;file2", "LinkLibraryDependencies": "true", "ModuleDefinitionFile": "a_file_name", "OutputFile": "a_file_name", "SuppressStartupBanner": "true", "UseUnicodeResponseFiles": "true", }, "VCManifestTool": { "AdditionalManifestFiles": "file1;file2", "AdditionalOptions": "a string1", "AssemblyIdentity": "a string1", "ComponentFileName": "a_file_name", "DependencyInformationFile": "a_file_name", "GenerateCatalogFiles": "true", "InputResourceManifests": "a string1", "ManifestResourceFile": "a_file_name", "OutputManifestFile": "a_file_name", "RegistrarScriptFile": "a_file_name", "ReplacementsFile": "a_file_name", "SuppressStartupBanner": "true", "TypeLibraryFile": "a_file_name", "UpdateFileHashes": "truel", "UpdateFileHashesSearchPath": "a_file_name", "UseFAT32Workaround": "true", "UseUnicodeResponseFiles": "true", "VerboseOutput": "true", }, }, self.stderr, ) self._ExpectedWarnings( [ "Warning: for VCCLCompilerTool/BasicRuntimeChecks, " "index value (5) not in expected range [0, 4)", "Warning: for VCCLCompilerTool/BrowseInformation, " "invalid literal for int() with base 10: 'fdkslj'", "Warning: for VCCLCompilerTool/CallingConvention, " "index value (-1) not in expected range [0, 4)", "Warning: for VCCLCompilerTool/DebugInformationFormat, " "converted value for 2 not specified.", "Warning: unrecognized setting VCCLCompilerTool/Enableprefast", "Warning: unrecognized setting VCCLCompilerTool/ZZXYZ", "Warning: for VCLinkerTool/TargetMachine, " "converted value for 2 not specified.", "Warning: unrecognized setting VCMIDLTool/notgood", "Warning: unrecognized setting VCResourceCompilerTool/notgood2", "Warning: for VCManifestTool/UpdateFileHashes, " "expected bool; got 'truel'" "", ] ) def testValidateMSBuildSettings_settings(self): """Tests that for invalid MSBuild settings.""" MSVSSettings.ValidateMSBuildSettings( { "ClCompile": { "AdditionalIncludeDirectories": "folder1;folder2", "AdditionalOptions": ["string1", "string2"], "AdditionalUsingDirectories": "folder1;folder2", "AssemblerListingLocation": "a_file_name", "AssemblerOutput": "NoListing", "BasicRuntimeChecks": "StackFrameRuntimeCheck", "BrowseInformation": "false", "BrowseInformationFile": "a_file_name", "BufferSecurityCheck": "true", "BuildingInIDE": "true", "CallingConvention": "Cdecl", "CompileAs": "CompileAsC", "CompileAsManaged": "true", "CreateHotpatchableImage": "true", "DebugInformationFormat": "ProgramDatabase", "DisableLanguageExtensions": "true", "DisableSpecificWarnings": "string1;string2", "EnableEnhancedInstructionSet": "StreamingSIMDExtensions", "EnableFiberSafeOptimizations": "true", "EnablePREfast": "true", "Enableprefast": "bogus", "ErrorReporting": "Prompt", "ExceptionHandling": "SyncCThrow", "ExpandAttributedSource": "true", "FavorSizeOrSpeed": "Neither", "FloatingPointExceptions": "true", "FloatingPointModel": "Precise", "ForceConformanceInForLoopScope": "true", "ForcedIncludeFiles": "file1;file2", "ForcedUsingFiles": "file1;file2", "FunctionLevelLinking": "false", "GenerateXMLDocumentationFiles": "true", "IgnoreStandardIncludePath": "true", "InlineFunctionExpansion": "OnlyExplicitInline", "IntrinsicFunctions": "false", "MinimalRebuild": "true", "MultiProcessorCompilation": "true", "ObjectFileName": "a_file_name", "OmitDefaultLibName": "true", "OmitFramePointers": "true", "OpenMPSupport": "true", "Optimization": "Disabled", "PrecompiledHeader": "NotUsing", "PrecompiledHeaderFile": "a_file_name", "PrecompiledHeaderOutputFile": "a_file_name", "PreprocessKeepComments": "true", "PreprocessorDefinitions": "string1;string2", "PreprocessOutputPath": "a string1", "PreprocessSuppressLineNumbers": "false", "PreprocessToFile": "false", "ProcessorNumber": "33", "ProgramDataBaseFileName": "a_file_name", "RuntimeLibrary": "MultiThreaded", "RuntimeTypeInfo": "true", "ShowIncludes": "true", "SmallerTypeCheck": "true", "StringPooling": "true", "StructMemberAlignment": "1Byte", "SuppressStartupBanner": "true", "TrackerLogDirectory": "a_folder", "TreatSpecificWarningsAsErrors": "string1;string2", "TreatWarningAsError": "true", "TreatWChar_tAsBuiltInType": "true", "UndefineAllPreprocessorDefinitions": "true", "UndefinePreprocessorDefinitions": "string1;string2", "UseFullPaths": "true", "UseUnicodeForAssemblerListing": "true", "WarningLevel": "TurnOffAllWarnings", "WholeProgramOptimization": "true", "XMLDocumentationFileName": "a_file_name", "ZZXYZ": "bogus", }, "Link": { "AdditionalDependencies": "file1;file2", "AdditionalLibraryDirectories": "folder1;folder2", "AdditionalManifestDependencies": "file1;file2", "AdditionalOptions": "a string1", "AddModuleNamesToAssembly": "file1;file2", "AllowIsolation": "true", "AssemblyDebug": "", "AssemblyLinkResource": "file1;file2", "BaseAddress": "a string1", "BuildingInIDE": "true", "CLRImageType": "ForceIJWImage", "CLRSupportLastError": "Enabled", "CLRThreadAttribute": "MTAThreadingAttribute", "CLRUnmanagedCodeCheck": "true", "CreateHotPatchableImage": "X86Image", "DataExecutionPrevention": "false", "DelayLoadDLLs": "file1;file2", "DelaySign": "true", "Driver": "NotSet", "EmbedManagedResourceFile": "file1;file2", "EnableCOMDATFolding": "false", "EnableUAC": "true", "EntryPointSymbol": "a string1", "FixedBaseAddress": "false", "ForceFileOutput": "Enabled", "ForceSymbolReferences": "file1;file2", "FunctionOrder": "a_file_name", "GenerateDebugInformation": "true", "GenerateMapFile": "true", "HeapCommitSize": "a string1", "HeapReserveSize": "a string1", "IgnoreAllDefaultLibraries": "true", "IgnoreEmbeddedIDL": "true", "IgnoreSpecificDefaultLibraries": "a_file_list", "ImageHasSafeExceptionHandlers": "true", "ImportLibrary": "a_file_name", "KeyContainer": "a_file_name", "KeyFile": "a_file_name", "LargeAddressAware": "false", "LinkDLL": "true", "LinkErrorReporting": "SendErrorReport", "LinkStatus": "true", "LinkTimeCodeGeneration": "UseLinkTimeCodeGeneration", "ManifestFile": "a_file_name", "MapExports": "true", "MapFileName": "a_file_name", "MergedIDLBaseFileName": "a_file_name", "MergeSections": "a string1", "MidlCommandFile": "a_file_name", "MinimumRequiredVersion": "a string1", "ModuleDefinitionFile": "a_file_name", "MSDOSStubFileName": "a_file_name", "NoEntryPoint": "true", "OptimizeReferences": "false", "OutputFile": "a_file_name", "PerUserRedirection": "true", "PreventDllBinding": "true", "Profile": "true", "ProfileGuidedDatabase": "a_file_name", "ProgramDatabaseFile": "a_file_name", "RandomizedBaseAddress": "false", "RegisterOutput": "true", "SectionAlignment": "33", "SetChecksum": "true", "ShowProgress": "LinkVerboseREF", "SpecifySectionAttributes": "a string1", "StackCommitSize": "a string1", "StackReserveSize": "a string1", "StripPrivateSymbols": "a_file_name", "SubSystem": "Console", "SupportNobindOfDelayLoadedDLL": "true", "SupportUnloadOfDelayLoadedDLL": "true", "SuppressStartupBanner": "true", "SwapRunFromCD": "true", "SwapRunFromNET": "true", "TargetMachine": "MachineX86", "TerminalServerAware": "false", "TrackerLogDirectory": "a_folder", "TreatLinkerWarningAsErrors": "true", "TurnOffAssemblyGeneration": "true", "TypeLibraryFile": "a_file_name", "TypeLibraryResourceID": "33", "UACExecutionLevel": "AsInvoker", "UACUIAccess": "true", "Version": "a string1", }, "ResourceCompile": { "AdditionalIncludeDirectories": "folder1;folder2", "AdditionalOptions": "a string1", "Culture": "0x236", "IgnoreStandardIncludePath": "true", "NullTerminateStrings": "true", "PreprocessorDefinitions": "string1;string2", "ResourceOutputFileName": "a string1", "ShowProgress": "true", "SuppressStartupBanner": "true", "TrackerLogDirectory": "a_folder", "UndefinePreprocessorDefinitions": "string1;string2", }, "Midl": { "AdditionalIncludeDirectories": "folder1;folder2", "AdditionalOptions": "a string1", "ApplicationConfigurationMode": "true", "ClientStubFile": "a_file_name", "CPreprocessOptions": "a string1", "DefaultCharType": "Signed", "DllDataFileName": "a_file_name", "EnableErrorChecks": "EnableCustom", "ErrorCheckAllocations": "true", "ErrorCheckBounds": "true", "ErrorCheckEnumRange": "true", "ErrorCheckRefPointers": "true", "ErrorCheckStubData": "true", "GenerateClientFiles": "Stub", "GenerateServerFiles": "None", "GenerateStublessProxies": "true", "GenerateTypeLibrary": "true", "HeaderFileName": "a_file_name", "IgnoreStandardIncludePath": "true", "InterfaceIdentifierFileName": "a_file_name", "LocaleID": "33", "MkTypLibCompatible": "true", "OutputDirectory": "a string1", "PreprocessorDefinitions": "string1;string2", "ProxyFileName": "a_file_name", "RedirectOutputAndErrors": "a_file_name", "ServerStubFile": "a_file_name", "StructMemberAlignment": "NotSet", "SuppressCompilerWarnings": "true", "SuppressStartupBanner": "true", "TargetEnvironment": "Itanium", "TrackerLogDirectory": "a_folder", "TypeLibFormat": "NewFormat", "TypeLibraryName": "a_file_name", "UndefinePreprocessorDefinitions": "string1;string2", "ValidateAllParameters": "true", "WarnAsError": "true", "WarningLevel": "1", }, "Lib": { "AdditionalDependencies": "file1;file2", "AdditionalLibraryDirectories": "folder1;folder2", "AdditionalOptions": "a string1", "DisplayLibrary": "a string1", "ErrorReporting": "PromptImmediately", "ExportNamedFunctions": "string1;string2", "ForceSymbolReferences": "a string1", "IgnoreAllDefaultLibraries": "true", "IgnoreSpecificDefaultLibraries": "file1;file2", "LinkTimeCodeGeneration": "true", "MinimumRequiredVersion": "a string1", "ModuleDefinitionFile": "a_file_name", "Name": "a_file_name", "OutputFile": "a_file_name", "RemoveObjects": "file1;file2", "SubSystem": "Console", "SuppressStartupBanner": "true", "TargetMachine": "MachineX86i", "TrackerLogDirectory": "a_folder", "TreatLibWarningAsErrors": "true", "UseUnicodeResponseFiles": "true", "Verbose": "true", }, "Manifest": { "AdditionalManifestFiles": "file1;file2", "AdditionalOptions": "a string1", "AssemblyIdentity": "a string1", "ComponentFileName": "a_file_name", "EnableDPIAwareness": "fal", "GenerateCatalogFiles": "truel", "GenerateCategoryTags": "true", "InputResourceManifests": "a string1", "ManifestFromManagedAssembly": "a_file_name", "notgood3": "bogus", "OutputManifestFile": "a_file_name", "OutputResourceManifests": "a string1", "RegistrarScriptFile": "a_file_name", "ReplacementsFile": "a_file_name", "SuppressDependencyElement": "true", "SuppressStartupBanner": "true", "TrackerLogDirectory": "a_folder", "TypeLibraryFile": "a_file_name", "UpdateFileHashes": "true", "UpdateFileHashesSearchPath": "a_file_name", "VerboseOutput": "true", }, "ProjectReference": { "LinkLibraryDependencies": "true", "UseLibraryDependencyInputs": "true", }, "ManifestResourceCompile": {"ResourceOutputFileName": "a_file_name"}, "": { "EmbedManifest": "true", "GenerateManifest": "true", "IgnoreImportLibrary": "true", "LinkIncremental": "false", }, }, self.stderr, ) self._ExpectedWarnings( [ "Warning: unrecognized setting ClCompile/Enableprefast", "Warning: unrecognized setting ClCompile/ZZXYZ", "Warning: unrecognized setting Manifest/notgood3", "Warning: for Manifest/GenerateCatalogFiles, " "expected bool; got 'truel'", "Warning: for Lib/TargetMachine, unrecognized enumerated value " "MachineX86i", "Warning: for Manifest/EnableDPIAwareness, expected bool; got 'fal'", ] ) def testConvertToMSBuildSettings_empty(self): """Tests an empty conversion.""" msvs_settings = {} expected_msbuild_settings = {} actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings( msvs_settings, self.stderr ) self.assertEqual(expected_msbuild_settings, actual_msbuild_settings) self._ExpectedWarnings([]) def testConvertToMSBuildSettings_minimal(self): """Tests a minimal conversion.""" msvs_settings = { "VCCLCompilerTool": { "AdditionalIncludeDirectories": "dir1", "AdditionalOptions": "/foo", "BasicRuntimeChecks": "0", }, "VCLinkerTool": { "LinkTimeCodeGeneration": "1", "ErrorReporting": "1", "DataExecutionPrevention": "2", }, } expected_msbuild_settings = { "ClCompile": { "AdditionalIncludeDirectories": "dir1", "AdditionalOptions": "/foo", "BasicRuntimeChecks": "Default", }, "Link": { "LinkTimeCodeGeneration": "UseLinkTimeCodeGeneration", "LinkErrorReporting": "PromptImmediately", "DataExecutionPrevention": "true", }, } actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings( msvs_settings, self.stderr ) self.assertEqual(expected_msbuild_settings, actual_msbuild_settings) self._ExpectedWarnings([]) def testConvertToMSBuildSettings_warnings(self): """Tests conversion that generates warnings.""" msvs_settings = { "VCCLCompilerTool": { "AdditionalIncludeDirectories": "1", "AdditionalOptions": "2", # These are incorrect values: "BasicRuntimeChecks": "12", "BrowseInformation": "21", "UsePrecompiledHeader": "13", "GeneratePreprocessedFile": "14", }, "VCLinkerTool": { # These are incorrect values: "Driver": "10", "LinkTimeCodeGeneration": "31", "ErrorReporting": "21", "FixedBaseAddress": "6", }, "VCResourceCompilerTool": { # Custom "Culture": "1003" }, } expected_msbuild_settings = { "ClCompile": { "AdditionalIncludeDirectories": "1", "AdditionalOptions": "2", }, "Link": {}, "ResourceCompile": { # Custom "Culture": "0x03eb" }, } actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings( msvs_settings, self.stderr ) self.assertEqual(expected_msbuild_settings, actual_msbuild_settings) self._ExpectedWarnings( [ "Warning: while converting VCCLCompilerTool/BasicRuntimeChecks to " "MSBuild, index value (12) not in expected range [0, 4)", "Warning: while converting VCCLCompilerTool/BrowseInformation to " "MSBuild, index value (21) not in expected range [0, 3)", "Warning: while converting VCCLCompilerTool/UsePrecompiledHeader to " "MSBuild, index value (13) not in expected range [0, 3)", "Warning: while converting " "VCCLCompilerTool/GeneratePreprocessedFile to " "MSBuild, value must be one of [0, 1, 2]; got 14", "Warning: while converting VCLinkerTool/Driver to " "MSBuild, index value (10) not in expected range [0, 4)", "Warning: while converting VCLinkerTool/LinkTimeCodeGeneration to " "MSBuild, index value (31) not in expected range [0, 5)", "Warning: while converting VCLinkerTool/ErrorReporting to " "MSBuild, index value (21) not in expected range [0, 3)", "Warning: while converting VCLinkerTool/FixedBaseAddress to " "MSBuild, index value (6) not in expected range [0, 3)", ] ) def testConvertToMSBuildSettings_full_synthetic(self): """Tests conversion of all the MSBuild settings.""" msvs_settings = { "VCCLCompilerTool": { "AdditionalIncludeDirectories": "folder1;folder2;folder3", "AdditionalOptions": "a_string", "AdditionalUsingDirectories": "folder1;folder2;folder3", "AssemblerListingLocation": "a_file_name", "AssemblerOutput": "0", "BasicRuntimeChecks": "1", "BrowseInformation": "2", "BrowseInformationFile": "a_file_name", "BufferSecurityCheck": "true", "CallingConvention": "0", "CompileAs": "1", "DebugInformationFormat": "4", "DefaultCharIsUnsigned": "true", "Detect64BitPortabilityProblems": "true", "DisableLanguageExtensions": "true", "DisableSpecificWarnings": "d1;d2;d3", "EnableEnhancedInstructionSet": "0", "EnableFiberSafeOptimizations": "true", "EnableFunctionLevelLinking": "true", "EnableIntrinsicFunctions": "true", "EnablePREfast": "true", "ErrorReporting": "1", "ExceptionHandling": "2", "ExpandAttributedSource": "true", "FavorSizeOrSpeed": "0", "FloatingPointExceptions": "true", "FloatingPointModel": "1", "ForceConformanceInForLoopScope": "true", "ForcedIncludeFiles": "file1;file2;file3", "ForcedUsingFiles": "file1;file2;file3", "GeneratePreprocessedFile": "1", "GenerateXMLDocumentationFiles": "true", "IgnoreStandardIncludePath": "true", "InlineFunctionExpansion": "2", "KeepComments": "true", "MinimalRebuild": "true", "ObjectFile": "a_file_name", "OmitDefaultLibName": "true", "OmitFramePointers": "true", "OpenMP": "true", "Optimization": "3", "PrecompiledHeaderFile": "a_file_name", "PrecompiledHeaderThrough": "a_file_name", "PreprocessorDefinitions": "d1;d2;d3", "ProgramDataBaseFileName": "a_file_name", "RuntimeLibrary": "0", "RuntimeTypeInfo": "true", "ShowIncludes": "true", "SmallerTypeCheck": "true", "StringPooling": "true", "StructMemberAlignment": "1", "SuppressStartupBanner": "true", "TreatWChar_tAsBuiltInType": "true", "UndefineAllPreprocessorDefinitions": "true", "UndefinePreprocessorDefinitions": "d1;d2;d3", "UseFullPaths": "true", "UsePrecompiledHeader": "1", "UseUnicodeResponseFiles": "true", "WarnAsError": "true", "WarningLevel": "2", "WholeProgramOptimization": "true", "XMLDocumentationFileName": "a_file_name", }, "VCLinkerTool": { "AdditionalDependencies": "file1;file2;file3", "AdditionalLibraryDirectories": "folder1;folder2;folder3", "AdditionalLibraryDirectories_excluded": "folder1;folder2;folder3", "AdditionalManifestDependencies": "file1;file2;file3", "AdditionalOptions": "a_string", "AddModuleNamesToAssembly": "file1;file2;file3", "AllowIsolation": "true", "AssemblyDebug": "0", "AssemblyLinkResource": "file1;file2;file3", "BaseAddress": "a_string", "CLRImageType": "1", "CLRThreadAttribute": "2", "CLRUnmanagedCodeCheck": "true", "DataExecutionPrevention": "0", "DelayLoadDLLs": "file1;file2;file3", "DelaySign": "true", "Driver": "1", "EmbedManagedResourceFile": "file1;file2;file3", "EnableCOMDATFolding": "0", "EnableUAC": "true", "EntryPointSymbol": "a_string", "ErrorReporting": "0", "FixedBaseAddress": "1", "ForceSymbolReferences": "file1;file2;file3", "FunctionOrder": "a_file_name", "GenerateDebugInformation": "true", "GenerateManifest": "true", "GenerateMapFile": "true", "HeapCommitSize": "a_string", "HeapReserveSize": "a_string", "IgnoreAllDefaultLibraries": "true", "IgnoreDefaultLibraryNames": "file1;file2;file3", "IgnoreEmbeddedIDL": "true", "IgnoreImportLibrary": "true", "ImportLibrary": "a_file_name", "KeyContainer": "a_file_name", "KeyFile": "a_file_name", "LargeAddressAware": "2", "LinkIncremental": "1", "LinkLibraryDependencies": "true", "LinkTimeCodeGeneration": "2", "ManifestFile": "a_file_name", "MapExports": "true", "MapFileName": "a_file_name", "MergedIDLBaseFileName": "a_file_name", "MergeSections": "a_string", "MidlCommandFile": "a_file_name", "ModuleDefinitionFile": "a_file_name", "OptimizeForWindows98": "1", "OptimizeReferences": "0", "OutputFile": "a_file_name", "PerUserRedirection": "true", "Profile": "true", "ProfileGuidedDatabase": "a_file_name", "ProgramDatabaseFile": "a_file_name", "RandomizedBaseAddress": "1", "RegisterOutput": "true", "ResourceOnlyDLL": "true", "SetChecksum": "true", "ShowProgress": "0", "StackCommitSize": "a_string", "StackReserveSize": "a_string", "StripPrivateSymbols": "a_file_name", "SubSystem": "2", "SupportUnloadOfDelayLoadedDLL": "true", "SuppressStartupBanner": "true", "SwapRunFromCD": "true", "SwapRunFromNet": "true", "TargetMachine": "3", "TerminalServerAware": "2", "TurnOffAssemblyGeneration": "true", "TypeLibraryFile": "a_file_name", "TypeLibraryResourceID": "33", "UACExecutionLevel": "1", "UACUIAccess": "true", "UseLibraryDependencyInputs": "false", "UseUnicodeResponseFiles": "true", "Version": "a_string", }, "VCResourceCompilerTool": { "AdditionalIncludeDirectories": "folder1;folder2;folder3", "AdditionalOptions": "a_string", "Culture": "1003", "IgnoreStandardIncludePath": "true", "PreprocessorDefinitions": "d1;d2;d3", "ResourceOutputFileName": "a_string", "ShowProgress": "true", "SuppressStartupBanner": "true", "UndefinePreprocessorDefinitions": "d1;d2;d3", }, "VCMIDLTool": { "AdditionalIncludeDirectories": "folder1;folder2;folder3", "AdditionalOptions": "a_string", "CPreprocessOptions": "a_string", "DefaultCharType": "0", "DLLDataFileName": "a_file_name", "EnableErrorChecks": "2", "ErrorCheckAllocations": "true", "ErrorCheckBounds": "true", "ErrorCheckEnumRange": "true", "ErrorCheckRefPointers": "true", "ErrorCheckStubData": "true", "GenerateStublessProxies": "true", "GenerateTypeLibrary": "true", "HeaderFileName": "a_file_name", "IgnoreStandardIncludePath": "true", "InterfaceIdentifierFileName": "a_file_name", "MkTypLibCompatible": "true", "OutputDirectory": "a_string", "PreprocessorDefinitions": "d1;d2;d3", "ProxyFileName": "a_file_name", "RedirectOutputAndErrors": "a_file_name", "StructMemberAlignment": "3", "SuppressStartupBanner": "true", "TargetEnvironment": "1", "TypeLibraryName": "a_file_name", "UndefinePreprocessorDefinitions": "d1;d2;d3", "ValidateParameters": "true", "WarnAsError": "true", "WarningLevel": "4", }, "VCLibrarianTool": { "AdditionalDependencies": "file1;file2;file3", "AdditionalLibraryDirectories": "folder1;folder2;folder3", "AdditionalLibraryDirectories_excluded": "folder1;folder2;folder3", "AdditionalOptions": "a_string", "ExportNamedFunctions": "d1;d2;d3", "ForceSymbolReferences": "a_string", "IgnoreAllDefaultLibraries": "true", "IgnoreSpecificDefaultLibraries": "file1;file2;file3", "LinkLibraryDependencies": "true", "ModuleDefinitionFile": "a_file_name", "OutputFile": "a_file_name", "SuppressStartupBanner": "true", "UseUnicodeResponseFiles": "true", }, "VCManifestTool": { "AdditionalManifestFiles": "file1;file2;file3", "AdditionalOptions": "a_string", "AssemblyIdentity": "a_string", "ComponentFileName": "a_file_name", "DependencyInformationFile": "a_file_name", "EmbedManifest": "true", "GenerateCatalogFiles": "true", "InputResourceManifests": "a_string", "ManifestResourceFile": "my_name", "OutputManifestFile": "a_file_name", "RegistrarScriptFile": "a_file_name", "ReplacementsFile": "a_file_name", "SuppressStartupBanner": "true", "TypeLibraryFile": "a_file_name", "UpdateFileHashes": "true", "UpdateFileHashesSearchPath": "a_file_name", "UseFAT32Workaround": "true", "UseUnicodeResponseFiles": "true", "VerboseOutput": "true", }, } expected_msbuild_settings = { "ClCompile": { "AdditionalIncludeDirectories": "folder1;folder2;folder3", "AdditionalOptions": "a_string /J", "AdditionalUsingDirectories": "folder1;folder2;folder3", "AssemblerListingLocation": "a_file_name", "AssemblerOutput": "NoListing", "BasicRuntimeChecks": "StackFrameRuntimeCheck", "BrowseInformation": "true", "BrowseInformationFile": "a_file_name", "BufferSecurityCheck": "true", "CallingConvention": "Cdecl", "CompileAs": "CompileAsC", "DebugInformationFormat": "EditAndContinue", "DisableLanguageExtensions": "true", "DisableSpecificWarnings": "d1;d2;d3", "EnableEnhancedInstructionSet": "NotSet", "EnableFiberSafeOptimizations": "true", "EnablePREfast": "true", "ErrorReporting": "Prompt", "ExceptionHandling": "Async", "ExpandAttributedSource": "true", "FavorSizeOrSpeed": "Neither", "FloatingPointExceptions": "true", "FloatingPointModel": "Strict", "ForceConformanceInForLoopScope": "true", "ForcedIncludeFiles": "file1;file2;file3", "ForcedUsingFiles": "file1;file2;file3", "FunctionLevelLinking": "true", "GenerateXMLDocumentationFiles": "true", "IgnoreStandardIncludePath": "true", "InlineFunctionExpansion": "AnySuitable", "IntrinsicFunctions": "true", "MinimalRebuild": "true", "ObjectFileName": "a_file_name", "OmitDefaultLibName": "true", "OmitFramePointers": "true", "OpenMPSupport": "true", "Optimization": "Full", "PrecompiledHeader": "Create", "PrecompiledHeaderFile": "a_file_name", "PrecompiledHeaderOutputFile": "a_file_name", "PreprocessKeepComments": "true", "PreprocessorDefinitions": "d1;d2;d3", "PreprocessSuppressLineNumbers": "false", "PreprocessToFile": "true", "ProgramDataBaseFileName": "a_file_name", "RuntimeLibrary": "MultiThreaded", "RuntimeTypeInfo": "true", "ShowIncludes": "true", "SmallerTypeCheck": "true", "StringPooling": "true", "StructMemberAlignment": "1Byte", "SuppressStartupBanner": "true", "TreatWarningAsError": "true", "TreatWChar_tAsBuiltInType": "true", "UndefineAllPreprocessorDefinitions": "true", "UndefinePreprocessorDefinitions": "d1;d2;d3", "UseFullPaths": "true", "WarningLevel": "Level2", "WholeProgramOptimization": "true", "XMLDocumentationFileName": "a_file_name", }, "Link": { "AdditionalDependencies": "file1;file2;file3", "AdditionalLibraryDirectories": "folder1;folder2;folder3", "AdditionalManifestDependencies": "file1;file2;file3", "AdditionalOptions": "a_string", "AddModuleNamesToAssembly": "file1;file2;file3", "AllowIsolation": "true", "AssemblyDebug": "", "AssemblyLinkResource": "file1;file2;file3", "BaseAddress": "a_string", "CLRImageType": "ForceIJWImage", "CLRThreadAttribute": "STAThreadingAttribute", "CLRUnmanagedCodeCheck": "true", "DataExecutionPrevention": "", "DelayLoadDLLs": "file1;file2;file3", "DelaySign": "true", "Driver": "Driver", "EmbedManagedResourceFile": "file1;file2;file3", "EnableCOMDATFolding": "", "EnableUAC": "true", "EntryPointSymbol": "a_string", "FixedBaseAddress": "false", "ForceSymbolReferences": "file1;file2;file3", "FunctionOrder": "a_file_name", "GenerateDebugInformation": "true", "GenerateMapFile": "true", "HeapCommitSize": "a_string", "HeapReserveSize": "a_string", "IgnoreAllDefaultLibraries": "true", "IgnoreEmbeddedIDL": "true", "IgnoreSpecificDefaultLibraries": "file1;file2;file3", "ImportLibrary": "a_file_name", "KeyContainer": "a_file_name", "KeyFile": "a_file_name", "LargeAddressAware": "true", "LinkErrorReporting": "NoErrorReport", "LinkTimeCodeGeneration": "PGInstrument", "ManifestFile": "a_file_name", "MapExports": "true", "MapFileName": "a_file_name", "MergedIDLBaseFileName": "a_file_name", "MergeSections": "a_string", "MidlCommandFile": "a_file_name", "ModuleDefinitionFile": "a_file_name", "NoEntryPoint": "true", "OptimizeReferences": "", "OutputFile": "a_file_name", "PerUserRedirection": "true", "Profile": "true", "ProfileGuidedDatabase": "a_file_name", "ProgramDatabaseFile": "a_file_name", "RandomizedBaseAddress": "false", "RegisterOutput": "true", "SetChecksum": "true", "ShowProgress": "NotSet", "StackCommitSize": "a_string", "StackReserveSize": "a_string", "StripPrivateSymbols": "a_file_name", "SubSystem": "Windows", "SupportUnloadOfDelayLoadedDLL": "true", "SuppressStartupBanner": "true", "SwapRunFromCD": "true", "SwapRunFromNET": "true", "TargetMachine": "MachineARM", "TerminalServerAware": "true", "TurnOffAssemblyGeneration": "true", "TypeLibraryFile": "a_file_name", "TypeLibraryResourceID": "33", "UACExecutionLevel": "HighestAvailable", "UACUIAccess": "true", "Version": "a_string", }, "ResourceCompile": { "AdditionalIncludeDirectories": "folder1;folder2;folder3", "AdditionalOptions": "a_string", "Culture": "0x03eb", "IgnoreStandardIncludePath": "true", "PreprocessorDefinitions": "d1;d2;d3", "ResourceOutputFileName": "a_string", "ShowProgress": "true", "SuppressStartupBanner": "true", "UndefinePreprocessorDefinitions": "d1;d2;d3", }, "Midl": { "AdditionalIncludeDirectories": "folder1;folder2;folder3", "AdditionalOptions": "a_string", "CPreprocessOptions": "a_string", "DefaultCharType": "Unsigned", "DllDataFileName": "a_file_name", "EnableErrorChecks": "All", "ErrorCheckAllocations": "true", "ErrorCheckBounds": "true", "ErrorCheckEnumRange": "true", "ErrorCheckRefPointers": "true", "ErrorCheckStubData": "true", "GenerateStublessProxies": "true", "GenerateTypeLibrary": "true", "HeaderFileName": "a_file_name", "IgnoreStandardIncludePath": "true", "InterfaceIdentifierFileName": "a_file_name", "MkTypLibCompatible": "true", "OutputDirectory": "a_string", "PreprocessorDefinitions": "d1;d2;d3", "ProxyFileName": "a_file_name", "RedirectOutputAndErrors": "a_file_name", "StructMemberAlignment": "4", "SuppressStartupBanner": "true", "TargetEnvironment": "Win32", "TypeLibraryName": "a_file_name", "UndefinePreprocessorDefinitions": "d1;d2;d3", "ValidateAllParameters": "true", "WarnAsError": "true", "WarningLevel": "4", }, "Lib": { "AdditionalDependencies": "file1;file2;file3", "AdditionalLibraryDirectories": "folder1;folder2;folder3", "AdditionalOptions": "a_string", "ExportNamedFunctions": "d1;d2;d3", "ForceSymbolReferences": "a_string", "IgnoreAllDefaultLibraries": "true", "IgnoreSpecificDefaultLibraries": "file1;file2;file3", "ModuleDefinitionFile": "a_file_name", "OutputFile": "a_file_name", "SuppressStartupBanner": "true", "UseUnicodeResponseFiles": "true", }, "Manifest": { "AdditionalManifestFiles": "file1;file2;file3", "AdditionalOptions": "a_string", "AssemblyIdentity": "a_string", "ComponentFileName": "a_file_name", "GenerateCatalogFiles": "true", "InputResourceManifests": "a_string", "OutputManifestFile": "a_file_name", "RegistrarScriptFile": "a_file_name", "ReplacementsFile": "a_file_name", "SuppressStartupBanner": "true", "TypeLibraryFile": "a_file_name", "UpdateFileHashes": "true", "UpdateFileHashesSearchPath": "a_file_name", "VerboseOutput": "true", }, "ManifestResourceCompile": {"ResourceOutputFileName": "my_name"}, "ProjectReference": { "LinkLibraryDependencies": "true", "UseLibraryDependencyInputs": "false", }, "": { "EmbedManifest": "true", "GenerateManifest": "true", "IgnoreImportLibrary": "true", "LinkIncremental": "false", }, } self.maxDiff = 9999 # on failure display a long diff actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings( msvs_settings, self.stderr ) self.assertEqual(expected_msbuild_settings, actual_msbuild_settings) self._ExpectedWarnings([]) def testConvertToMSBuildSettings_actual(self): """Tests the conversion of an actual project. A VS2008 project with most of the options defined was created through the VS2008 IDE. It was then converted to VS2010. The tool settings found in the .vcproj and .vcxproj files were converted to the two dictionaries msvs_settings and expected_msbuild_settings. Note that for many settings, the VS2010 converter adds macros like %(AdditionalIncludeDirectories) to make sure than inherited values are included. Since the Gyp projects we generate do not use inheritance, we removed these macros. They were: ClCompile: AdditionalIncludeDirectories: ';%(AdditionalIncludeDirectories)' AdditionalOptions: ' %(AdditionalOptions)' AdditionalUsingDirectories: ';%(AdditionalUsingDirectories)' DisableSpecificWarnings: ';%(DisableSpecificWarnings)', ForcedIncludeFiles: ';%(ForcedIncludeFiles)', ForcedUsingFiles: ';%(ForcedUsingFiles)', PreprocessorDefinitions: ';%(PreprocessorDefinitions)', UndefinePreprocessorDefinitions: ';%(UndefinePreprocessorDefinitions)', Link: AdditionalDependencies: ';%(AdditionalDependencies)', AdditionalLibraryDirectories: ';%(AdditionalLibraryDirectories)', AdditionalManifestDependencies: ';%(AdditionalManifestDependencies)', AdditionalOptions: ' %(AdditionalOptions)', AddModuleNamesToAssembly: ';%(AddModuleNamesToAssembly)', AssemblyLinkResource: ';%(AssemblyLinkResource)', DelayLoadDLLs: ';%(DelayLoadDLLs)', EmbedManagedResourceFile: ';%(EmbedManagedResourceFile)', ForceSymbolReferences: ';%(ForceSymbolReferences)', IgnoreSpecificDefaultLibraries: ';%(IgnoreSpecificDefaultLibraries)', ResourceCompile: AdditionalIncludeDirectories: ';%(AdditionalIncludeDirectories)', AdditionalOptions: ' %(AdditionalOptions)', PreprocessorDefinitions: ';%(PreprocessorDefinitions)', Manifest: AdditionalManifestFiles: ';%(AdditionalManifestFiles)', AdditionalOptions: ' %(AdditionalOptions)', InputResourceManifests: ';%(InputResourceManifests)', """ msvs_settings = { "VCCLCompilerTool": { "AdditionalIncludeDirectories": "dir1", "AdditionalOptions": "/more", "AdditionalUsingDirectories": "test", "AssemblerListingLocation": "$(IntDir)\\a", "AssemblerOutput": "1", "BasicRuntimeChecks": "3", "BrowseInformation": "1", "BrowseInformationFile": "$(IntDir)\\e", "BufferSecurityCheck": "false", "CallingConvention": "1", "CompileAs": "1", "DebugInformationFormat": "4", "DefaultCharIsUnsigned": "true", "Detect64BitPortabilityProblems": "true", "DisableLanguageExtensions": "true", "DisableSpecificWarnings": "abc", "EnableEnhancedInstructionSet": "1", "EnableFiberSafeOptimizations": "true", "EnableFunctionLevelLinking": "true", "EnableIntrinsicFunctions": "true", "EnablePREfast": "true", "ErrorReporting": "2", "ExceptionHandling": "2", "ExpandAttributedSource": "true", "FavorSizeOrSpeed": "2", "FloatingPointExceptions": "true", "FloatingPointModel": "1", "ForceConformanceInForLoopScope": "false", "ForcedIncludeFiles": "def", "ForcedUsingFiles": "ge", "GeneratePreprocessedFile": "2", "GenerateXMLDocumentationFiles": "true", "IgnoreStandardIncludePath": "true", "InlineFunctionExpansion": "1", "KeepComments": "true", "MinimalRebuild": "true", "ObjectFile": "$(IntDir)\\b", "OmitDefaultLibName": "true", "OmitFramePointers": "true", "OpenMP": "true", "Optimization": "3", "PrecompiledHeaderFile": "$(IntDir)\\$(TargetName).pche", "PrecompiledHeaderThrough": "StdAfx.hd", "PreprocessorDefinitions": "WIN32;_DEBUG;_CONSOLE", "ProgramDataBaseFileName": "$(IntDir)\\vc90b.pdb", "RuntimeLibrary": "3", "RuntimeTypeInfo": "false", "ShowIncludes": "true", "SmallerTypeCheck": "true", "StringPooling": "true", "StructMemberAlignment": "3", "SuppressStartupBanner": "false", "TreatWChar_tAsBuiltInType": "false", "UndefineAllPreprocessorDefinitions": "true", "UndefinePreprocessorDefinitions": "wer", "UseFullPaths": "true", "UsePrecompiledHeader": "0", "UseUnicodeResponseFiles": "false", "WarnAsError": "true", "WarningLevel": "3", "WholeProgramOptimization": "true", "XMLDocumentationFileName": "$(IntDir)\\c", }, "VCLinkerTool": { "AdditionalDependencies": "zx", "AdditionalLibraryDirectories": "asd", "AdditionalManifestDependencies": "s2", "AdditionalOptions": "/mor2", "AddModuleNamesToAssembly": "d1", "AllowIsolation": "false", "AssemblyDebug": "1", "AssemblyLinkResource": "d5", "BaseAddress": "23423", "CLRImageType": "3", "CLRThreadAttribute": "1", "CLRUnmanagedCodeCheck": "true", "DataExecutionPrevention": "0", "DelayLoadDLLs": "d4", "DelaySign": "true", "Driver": "2", "EmbedManagedResourceFile": "d2", "EnableCOMDATFolding": "1", "EnableUAC": "false", "EntryPointSymbol": "f5", "ErrorReporting": "2", "FixedBaseAddress": "1", "ForceSymbolReferences": "d3", "FunctionOrder": "fssdfsd", "GenerateDebugInformation": "true", "GenerateManifest": "false", "GenerateMapFile": "true", "HeapCommitSize": "13", "HeapReserveSize": "12", "IgnoreAllDefaultLibraries": "true", "IgnoreDefaultLibraryNames": "flob;flok", "IgnoreEmbeddedIDL": "true", "IgnoreImportLibrary": "true", "ImportLibrary": "f4", "KeyContainer": "f7", "KeyFile": "f6", "LargeAddressAware": "2", "LinkIncremental": "0", "LinkLibraryDependencies": "false", "LinkTimeCodeGeneration": "1", "ManifestFile": "$(IntDir)\\$(TargetFileName).2intermediate.manifest", "MapExports": "true", "MapFileName": "d5", "MergedIDLBaseFileName": "f2", "MergeSections": "f5", "MidlCommandFile": "f1", "ModuleDefinitionFile": "sdsd", "OptimizeForWindows98": "2", "OptimizeReferences": "2", "OutputFile": "$(OutDir)\\$(ProjectName)2.exe", "PerUserRedirection": "true", "Profile": "true", "ProfileGuidedDatabase": "$(TargetDir)$(TargetName).pgdd", "ProgramDatabaseFile": "Flob.pdb", "RandomizedBaseAddress": "1", "RegisterOutput": "true", "ResourceOnlyDLL": "true", "SetChecksum": "false", "ShowProgress": "1", "StackCommitSize": "15", "StackReserveSize": "14", "StripPrivateSymbols": "d3", "SubSystem": "1", "SupportUnloadOfDelayLoadedDLL": "true", "SuppressStartupBanner": "false", "SwapRunFromCD": "true", "SwapRunFromNet": "true", "TargetMachine": "1", "TerminalServerAware": "1", "TurnOffAssemblyGeneration": "true", "TypeLibraryFile": "f3", "TypeLibraryResourceID": "12", "UACExecutionLevel": "2", "UACUIAccess": "true", "UseLibraryDependencyInputs": "true", "UseUnicodeResponseFiles": "false", "Version": "333", }, "VCResourceCompilerTool": { "AdditionalIncludeDirectories": "f3", "AdditionalOptions": "/more3", "Culture": "3084", "IgnoreStandardIncludePath": "true", "PreprocessorDefinitions": "_UNICODE;UNICODE2", "ResourceOutputFileName": "$(IntDir)/$(InputName)3.res", "ShowProgress": "true", }, "VCManifestTool": { "AdditionalManifestFiles": "sfsdfsd", "AdditionalOptions": "afdsdafsd", "AssemblyIdentity": "sddfdsadfsa", "ComponentFileName": "fsdfds", "DependencyInformationFile": "$(IntDir)\\mt.depdfd", "EmbedManifest": "false", "GenerateCatalogFiles": "true", "InputResourceManifests": "asfsfdafs", "ManifestResourceFile": "$(IntDir)\\$(TargetFileName).embed.manifest.resfdsf", "OutputManifestFile": "$(TargetPath).manifestdfs", "RegistrarScriptFile": "sdfsfd", "ReplacementsFile": "sdffsd", "SuppressStartupBanner": "false", "TypeLibraryFile": "sfsd", "UpdateFileHashes": "true", "UpdateFileHashesSearchPath": "sfsd", "UseFAT32Workaround": "true", "UseUnicodeResponseFiles": "false", "VerboseOutput": "true", }, } expected_msbuild_settings = { "ClCompile": { "AdditionalIncludeDirectories": "dir1", "AdditionalOptions": "/more /J", "AdditionalUsingDirectories": "test", "AssemblerListingLocation": "$(IntDir)a", "AssemblerOutput": "AssemblyCode", "BasicRuntimeChecks": "EnableFastChecks", "BrowseInformation": "true", "BrowseInformationFile": "$(IntDir)e", "BufferSecurityCheck": "false", "CallingConvention": "FastCall", "CompileAs": "CompileAsC", "DebugInformationFormat": "EditAndContinue", "DisableLanguageExtensions": "true", "DisableSpecificWarnings": "abc", "EnableEnhancedInstructionSet": "StreamingSIMDExtensions", "EnableFiberSafeOptimizations": "true", "EnablePREfast": "true", "ErrorReporting": "Queue", "ExceptionHandling": "Async", "ExpandAttributedSource": "true", "FavorSizeOrSpeed": "Size", "FloatingPointExceptions": "true", "FloatingPointModel": "Strict", "ForceConformanceInForLoopScope": "false", "ForcedIncludeFiles": "def", "ForcedUsingFiles": "ge", "FunctionLevelLinking": "true", "GenerateXMLDocumentationFiles": "true", "IgnoreStandardIncludePath": "true", "InlineFunctionExpansion": "OnlyExplicitInline", "IntrinsicFunctions": "true", "MinimalRebuild": "true", "ObjectFileName": "$(IntDir)b", "OmitDefaultLibName": "true", "OmitFramePointers": "true", "OpenMPSupport": "true", "Optimization": "Full", "PrecompiledHeader": "NotUsing", # Actual conversion gives '' "PrecompiledHeaderFile": "StdAfx.hd", "PrecompiledHeaderOutputFile": "$(IntDir)$(TargetName).pche", "PreprocessKeepComments": "true", "PreprocessorDefinitions": "WIN32;_DEBUG;_CONSOLE", "PreprocessSuppressLineNumbers": "true", "PreprocessToFile": "true", "ProgramDataBaseFileName": "$(IntDir)vc90b.pdb", "RuntimeLibrary": "MultiThreadedDebugDLL", "RuntimeTypeInfo": "false", "ShowIncludes": "true", "SmallerTypeCheck": "true", "StringPooling": "true", "StructMemberAlignment": "4Bytes", "SuppressStartupBanner": "false", "TreatWarningAsError": "true", "TreatWChar_tAsBuiltInType": "false", "UndefineAllPreprocessorDefinitions": "true", "UndefinePreprocessorDefinitions": "wer", "UseFullPaths": "true", "WarningLevel": "Level3", "WholeProgramOptimization": "true", "XMLDocumentationFileName": "$(IntDir)c", }, "Link": { "AdditionalDependencies": "zx", "AdditionalLibraryDirectories": "asd", "AdditionalManifestDependencies": "s2", "AdditionalOptions": "/mor2", "AddModuleNamesToAssembly": "d1", "AllowIsolation": "false", "AssemblyDebug": "true", "AssemblyLinkResource": "d5", "BaseAddress": "23423", "CLRImageType": "ForceSafeILImage", "CLRThreadAttribute": "MTAThreadingAttribute", "CLRUnmanagedCodeCheck": "true", "DataExecutionPrevention": "", "DelayLoadDLLs": "d4", "DelaySign": "true", "Driver": "UpOnly", "EmbedManagedResourceFile": "d2", "EnableCOMDATFolding": "false", "EnableUAC": "false", "EntryPointSymbol": "f5", "FixedBaseAddress": "false", "ForceSymbolReferences": "d3", "FunctionOrder": "fssdfsd", "GenerateDebugInformation": "true", "GenerateMapFile": "true", "HeapCommitSize": "13", "HeapReserveSize": "12", "IgnoreAllDefaultLibraries": "true", "IgnoreEmbeddedIDL": "true", "IgnoreSpecificDefaultLibraries": "flob;flok", "ImportLibrary": "f4", "KeyContainer": "f7", "KeyFile": "f6", "LargeAddressAware": "true", "LinkErrorReporting": "QueueForNextLogin", "LinkTimeCodeGeneration": "UseLinkTimeCodeGeneration", "ManifestFile": "$(IntDir)$(TargetFileName).2intermediate.manifest", "MapExports": "true", "MapFileName": "d5", "MergedIDLBaseFileName": "f2", "MergeSections": "f5", "MidlCommandFile": "f1", "ModuleDefinitionFile": "sdsd", "NoEntryPoint": "true", "OptimizeReferences": "true", "OutputFile": "$(OutDir)$(ProjectName)2.exe", "PerUserRedirection": "true", "Profile": "true", "ProfileGuidedDatabase": "$(TargetDir)$(TargetName).pgdd", "ProgramDatabaseFile": "Flob.pdb", "RandomizedBaseAddress": "false", "RegisterOutput": "true", "SetChecksum": "false", "ShowProgress": "LinkVerbose", "StackCommitSize": "15", "StackReserveSize": "14", "StripPrivateSymbols": "d3", "SubSystem": "Console", "SupportUnloadOfDelayLoadedDLL": "true", "SuppressStartupBanner": "false", "SwapRunFromCD": "true", "SwapRunFromNET": "true", "TargetMachine": "MachineX86", "TerminalServerAware": "false", "TurnOffAssemblyGeneration": "true", "TypeLibraryFile": "f3", "TypeLibraryResourceID": "12", "UACExecutionLevel": "RequireAdministrator", "UACUIAccess": "true", "Version": "333", }, "ResourceCompile": { "AdditionalIncludeDirectories": "f3", "AdditionalOptions": "/more3", "Culture": "0x0c0c", "IgnoreStandardIncludePath": "true", "PreprocessorDefinitions": "_UNICODE;UNICODE2", "ResourceOutputFileName": "$(IntDir)%(Filename)3.res", "ShowProgress": "true", }, "Manifest": { "AdditionalManifestFiles": "sfsdfsd", "AdditionalOptions": "afdsdafsd", "AssemblyIdentity": "sddfdsadfsa", "ComponentFileName": "fsdfds", "GenerateCatalogFiles": "true", "InputResourceManifests": "asfsfdafs", "OutputManifestFile": "$(TargetPath).manifestdfs", "RegistrarScriptFile": "sdfsfd", "ReplacementsFile": "sdffsd", "SuppressStartupBanner": "false", "TypeLibraryFile": "sfsd", "UpdateFileHashes": "true", "UpdateFileHashesSearchPath": "sfsd", "VerboseOutput": "true", }, "ProjectReference": { "LinkLibraryDependencies": "false", "UseLibraryDependencyInputs": "true", }, "": { "EmbedManifest": "false", "GenerateManifest": "false", "IgnoreImportLibrary": "true", "LinkIncremental": "", }, "ManifestResourceCompile": { "ResourceOutputFileName": "$(IntDir)$(TargetFileName).embed.manifest.resfdsf" }, } self.maxDiff = 9999 # on failure display a long diff actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings( msvs_settings, self.stderr ) self.assertEqual(expected_msbuild_settings, actual_msbuild_settings) self._ExpectedWarnings([]) if __name__ == "__main__": unittest.main() PK ~\Bp@?@?)node-gyp/gyp/pylib/gyp/xcode_emulation.pynu[# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ This module contains classes that help to emulate xcodebuild behavior on top of other build systems, such as make and ninja. """ import copy import gyp.common import os import os.path import re import shlex import subprocess import sys from gyp.common import GypError # Populated lazily by XcodeVersion, for efficiency, and to fix an issue when # "xcodebuild" is called too quickly (it has been found to return incorrect # version number). XCODE_VERSION_CACHE = None # Populated lazily by GetXcodeArchsDefault, to an |XcodeArchsDefault| instance # corresponding to the installed version of Xcode. XCODE_ARCHS_DEFAULT_CACHE = None def XcodeArchsVariableMapping(archs, archs_including_64_bit=None): """Constructs a dictionary with expansion for $(ARCHS_STANDARD) variable, and optionally for $(ARCHS_STANDARD_INCLUDING_64_BIT).""" mapping = {"$(ARCHS_STANDARD)": archs} if archs_including_64_bit: mapping["$(ARCHS_STANDARD_INCLUDING_64_BIT)"] = archs_including_64_bit return mapping class XcodeArchsDefault: """A class to resolve ARCHS variable from xcode_settings, resolving Xcode macros and implementing filtering by VALID_ARCHS. The expansion of macros depends on the SDKROOT used ("macosx", "iphoneos", "iphonesimulator") and on the version of Xcode. """ # Match variable like $(ARCHS_STANDARD). variable_pattern = re.compile(r"\$\([a-zA-Z_][a-zA-Z0-9_]*\)$") def __init__(self, default, mac, iphonesimulator, iphoneos): self._default = (default,) self._archs = {"mac": mac, "ios": iphoneos, "iossim": iphonesimulator} def _VariableMapping(self, sdkroot): """Returns the dictionary of variable mapping depending on the SDKROOT.""" sdkroot = sdkroot.lower() if "iphoneos" in sdkroot: return self._archs["ios"] elif "iphonesimulator" in sdkroot: return self._archs["iossim"] else: return self._archs["mac"] def _ExpandArchs(self, archs, sdkroot): """Expands variables references in ARCHS, and remove duplicates.""" variable_mapping = self._VariableMapping(sdkroot) expanded_archs = [] for arch in archs: if self.variable_pattern.match(arch): variable = arch try: variable_expansion = variable_mapping[variable] for arch in variable_expansion: if arch not in expanded_archs: expanded_archs.append(arch) except KeyError: print('Warning: Ignoring unsupported variable "%s".' % variable) elif arch not in expanded_archs: expanded_archs.append(arch) return expanded_archs def ActiveArchs(self, archs, valid_archs, sdkroot): """Expands variables references in ARCHS, and filter by VALID_ARCHS if it is defined (if not set, Xcode accept any value in ARCHS, otherwise, only values present in VALID_ARCHS are kept).""" expanded_archs = self._ExpandArchs(archs or self._default, sdkroot or "") if valid_archs: filtered_archs = [] for arch in expanded_archs: if arch in valid_archs: filtered_archs.append(arch) expanded_archs = filtered_archs return expanded_archs def GetXcodeArchsDefault(): """Returns the |XcodeArchsDefault| object to use to expand ARCHS for the installed version of Xcode. The default values used by Xcode for ARCHS and the expansion of the variables depends on the version of Xcode used. For all version anterior to Xcode 5.0 or posterior to Xcode 5.1 included uses $(ARCHS_STANDARD) if ARCHS is unset, while Xcode 5.0 to 5.0.2 uses $(ARCHS_STANDARD_INCLUDING_64_BIT). This variable was added to Xcode 5.0 and deprecated with Xcode 5.1. For "macosx" SDKROOT, all version starting with Xcode 5.0 includes 64-bit architecture as part of $(ARCHS_STANDARD) and default to only building it. For "iphoneos" and "iphonesimulator" SDKROOT, 64-bit architectures are part of $(ARCHS_STANDARD_INCLUDING_64_BIT) from Xcode 5.0. From Xcode 5.1, they are also part of $(ARCHS_STANDARD). All these rules are coded in the construction of the |XcodeArchsDefault| object to use depending on the version of Xcode detected. The object is for performance reason.""" global XCODE_ARCHS_DEFAULT_CACHE if XCODE_ARCHS_DEFAULT_CACHE: return XCODE_ARCHS_DEFAULT_CACHE xcode_version, _ = XcodeVersion() if xcode_version < "0500": XCODE_ARCHS_DEFAULT_CACHE = XcodeArchsDefault( "$(ARCHS_STANDARD)", XcodeArchsVariableMapping(["i386"]), XcodeArchsVariableMapping(["i386"]), XcodeArchsVariableMapping(["armv7"]), ) elif xcode_version < "0510": XCODE_ARCHS_DEFAULT_CACHE = XcodeArchsDefault( "$(ARCHS_STANDARD_INCLUDING_64_BIT)", XcodeArchsVariableMapping(["x86_64"], ["x86_64"]), XcodeArchsVariableMapping(["i386"], ["i386", "x86_64"]), XcodeArchsVariableMapping( ["armv7", "armv7s"], ["armv7", "armv7s", "arm64"] ), ) else: XCODE_ARCHS_DEFAULT_CACHE = XcodeArchsDefault( "$(ARCHS_STANDARD)", XcodeArchsVariableMapping(["x86_64"], ["x86_64"]), XcodeArchsVariableMapping(["i386", "x86_64"], ["i386", "x86_64"]), XcodeArchsVariableMapping( ["armv7", "armv7s", "arm64"], ["armv7", "armv7s", "arm64"] ), ) return XCODE_ARCHS_DEFAULT_CACHE class XcodeSettings: """A class that understands the gyp 'xcode_settings' object.""" # Populated lazily by _SdkPath(). Shared by all XcodeSettings, so cached # at class-level for efficiency. _sdk_path_cache = {} _platform_path_cache = {} _sdk_root_cache = {} # Populated lazily by GetExtraPlistItems(). Shared by all XcodeSettings, so # cached at class-level for efficiency. _plist_cache = {} # Populated lazily by GetIOSPostbuilds. Shared by all XcodeSettings, so # cached at class-level for efficiency. _codesigning_key_cache = {} def __init__(self, spec): self.spec = spec self.isIOS = False self.mac_toolchain_dir = None self.header_map_path = None # Per-target 'xcode_settings' are pushed down into configs earlier by gyp. # This means self.xcode_settings[config] always contains all settings # for that config -- the per-target settings as well. Settings that are # the same for all configs are implicitly per-target settings. self.xcode_settings = {} configs = spec["configurations"] for configname, config in configs.items(): self.xcode_settings[configname] = config.get("xcode_settings", {}) self._ConvertConditionalKeys(configname) if self.xcode_settings[configname].get("IPHONEOS_DEPLOYMENT_TARGET", None): self.isIOS = True # This is only non-None temporarily during the execution of some methods. self.configname = None # Used by _AdjustLibrary to match .a and .dylib entries in libraries. self.library_re = re.compile(r"^lib([^/]+)\.(a|dylib)$") def _ConvertConditionalKeys(self, configname): """Converts or warns on conditional keys. Xcode supports conditional keys, such as CODE_SIGN_IDENTITY[sdk=iphoneos*]. This is a partial implementation with some keys converted while the rest force a warning.""" settings = self.xcode_settings[configname] conditional_keys = [key for key in settings if key.endswith("]")] for key in conditional_keys: # If you need more, speak up at http://crbug.com/122592 if key.endswith("[sdk=iphoneos*]"): if configname.endswith("iphoneos"): new_key = key.split("[")[0] settings[new_key] = settings[key] else: print( "Warning: Conditional keys not implemented, ignoring:", " ".join(conditional_keys), ) del settings[key] def _Settings(self): assert self.configname return self.xcode_settings[self.configname] def _Test(self, test_key, cond_key, default): return self._Settings().get(test_key, default) == cond_key def _Appendf(self, lst, test_key, format_str, default=None): if test_key in self._Settings(): lst.append(format_str % str(self._Settings()[test_key])) elif default: lst.append(format_str % str(default)) def _WarnUnimplemented(self, test_key): if test_key in self._Settings(): print('Warning: Ignoring not yet implemented key "%s".' % test_key) def IsBinaryOutputFormat(self, configname): default = "binary" if self.isIOS else "xml" format = self.xcode_settings[configname].get("INFOPLIST_OUTPUT_FORMAT", default) return format == "binary" def IsIosFramework(self): return self.spec["type"] == "shared_library" and self._IsBundle() and self.isIOS def _IsBundle(self): return ( int(self.spec.get("mac_bundle", 0)) != 0 or self._IsXCTest() or self._IsXCUiTest() ) def _IsXCTest(self): return int(self.spec.get("mac_xctest_bundle", 0)) != 0 def _IsXCUiTest(self): return int(self.spec.get("mac_xcuitest_bundle", 0)) != 0 def _IsIosAppExtension(self): return int(self.spec.get("ios_app_extension", 0)) != 0 def _IsIosWatchKitExtension(self): return int(self.spec.get("ios_watchkit_extension", 0)) != 0 def _IsIosWatchApp(self): return int(self.spec.get("ios_watch_app", 0)) != 0 def GetFrameworkVersion(self): """Returns the framework version of the current target. Only valid for bundles.""" assert self._IsBundle() return self.GetPerTargetSetting("FRAMEWORK_VERSION", default="A") def GetWrapperExtension(self): """Returns the bundle extension (.app, .framework, .plugin, etc). Only valid for bundles.""" assert self._IsBundle() if self.spec["type"] in ("loadable_module", "shared_library"): default_wrapper_extension = { "loadable_module": "bundle", "shared_library": "framework", }[self.spec["type"]] wrapper_extension = self.GetPerTargetSetting( "WRAPPER_EXTENSION", default=default_wrapper_extension ) return "." + self.spec.get("product_extension", wrapper_extension) elif self.spec["type"] == "executable": if self._IsIosAppExtension() or self._IsIosWatchKitExtension(): return "." + self.spec.get("product_extension", "appex") else: return "." + self.spec.get("product_extension", "app") else: assert False, "Don't know extension for '{}', target '{}'".format( self.spec["type"], self.spec["target_name"], ) def GetProductName(self): """Returns PRODUCT_NAME.""" return self.spec.get("product_name", self.spec["target_name"]) def GetFullProductName(self): """Returns FULL_PRODUCT_NAME.""" if self._IsBundle(): return self.GetWrapperName() else: return self._GetStandaloneBinaryPath() def GetWrapperName(self): """Returns the directory name of the bundle represented by this target. Only valid for bundles.""" assert self._IsBundle() return self.GetProductName() + self.GetWrapperExtension() def GetBundleContentsFolderPath(self): """Returns the qualified path to the bundle's contents folder. E.g. Chromium.app/Contents or Foo.bundle/Versions/A. Only valid for bundles.""" if self.isIOS: return self.GetWrapperName() assert self._IsBundle() if self.spec["type"] == "shared_library": return os.path.join( self.GetWrapperName(), "Versions", self.GetFrameworkVersion() ) else: # loadable_modules have a 'Contents' folder like executables. return os.path.join(self.GetWrapperName(), "Contents") def GetBundleResourceFolder(self): """Returns the qualified path to the bundle's resource folder. E.g. Chromium.app/Contents/Resources. Only valid for bundles.""" assert self._IsBundle() if self.isIOS: return self.GetBundleContentsFolderPath() return os.path.join(self.GetBundleContentsFolderPath(), "Resources") def GetBundleExecutableFolderPath(self): """Returns the qualified path to the bundle's executables folder. E.g. Chromium.app/Contents/MacOS. Only valid for bundles.""" assert self._IsBundle() if self.spec["type"] in ("shared_library") or self.isIOS: return self.GetBundleContentsFolderPath() elif self.spec["type"] in ("executable", "loadable_module"): return os.path.join(self.GetBundleContentsFolderPath(), "MacOS") def GetBundleJavaFolderPath(self): """Returns the qualified path to the bundle's Java resource folder. E.g. Chromium.app/Contents/Resources/Java. Only valid for bundles.""" assert self._IsBundle() return os.path.join(self.GetBundleResourceFolder(), "Java") def GetBundleFrameworksFolderPath(self): """Returns the qualified path to the bundle's frameworks folder. E.g, Chromium.app/Contents/Frameworks. Only valid for bundles.""" assert self._IsBundle() return os.path.join(self.GetBundleContentsFolderPath(), "Frameworks") def GetBundleSharedFrameworksFolderPath(self): """Returns the qualified path to the bundle's frameworks folder. E.g, Chromium.app/Contents/SharedFrameworks. Only valid for bundles.""" assert self._IsBundle() return os.path.join(self.GetBundleContentsFolderPath(), "SharedFrameworks") def GetBundleSharedSupportFolderPath(self): """Returns the qualified path to the bundle's shared support folder. E.g, Chromium.app/Contents/SharedSupport. Only valid for bundles.""" assert self._IsBundle() if self.spec["type"] == "shared_library": return self.GetBundleResourceFolder() else: return os.path.join(self.GetBundleContentsFolderPath(), "SharedSupport") def GetBundlePlugInsFolderPath(self): """Returns the qualified path to the bundle's plugins folder. E.g, Chromium.app/Contents/PlugIns. Only valid for bundles.""" assert self._IsBundle() return os.path.join(self.GetBundleContentsFolderPath(), "PlugIns") def GetBundleXPCServicesFolderPath(self): """Returns the qualified path to the bundle's XPC services folder. E.g, Chromium.app/Contents/XPCServices. Only valid for bundles.""" assert self._IsBundle() return os.path.join(self.GetBundleContentsFolderPath(), "XPCServices") def GetBundlePlistPath(self): """Returns the qualified path to the bundle's plist file. E.g. Chromium.app/Contents/Info.plist. Only valid for bundles.""" assert self._IsBundle() if ( self.spec["type"] in ("executable", "loadable_module") or self.IsIosFramework() ): return os.path.join(self.GetBundleContentsFolderPath(), "Info.plist") else: return os.path.join( self.GetBundleContentsFolderPath(), "Resources", "Info.plist" ) def GetProductType(self): """Returns the PRODUCT_TYPE of this target.""" if self._IsIosAppExtension(): assert self._IsBundle(), ( "ios_app_extension flag requires mac_bundle " "(target %s)" % self.spec["target_name"] ) return "com.apple.product-type.app-extension" if self._IsIosWatchKitExtension(): assert self._IsBundle(), ( "ios_watchkit_extension flag requires " "mac_bundle (target %s)" % self.spec["target_name"] ) return "com.apple.product-type.watchkit-extension" if self._IsIosWatchApp(): assert self._IsBundle(), ( "ios_watch_app flag requires mac_bundle " "(target %s)" % self.spec["target_name"] ) return "com.apple.product-type.application.watchapp" if self._IsXCUiTest(): assert self._IsBundle(), ( "mac_xcuitest_bundle flag requires mac_bundle " "(target %s)" % self.spec["target_name"] ) return "com.apple.product-type.bundle.ui-testing" if self._IsBundle(): return { "executable": "com.apple.product-type.application", "loadable_module": "com.apple.product-type.bundle", "shared_library": "com.apple.product-type.framework", }[self.spec["type"]] else: return { "executable": "com.apple.product-type.tool", "loadable_module": "com.apple.product-type.library.dynamic", "shared_library": "com.apple.product-type.library.dynamic", "static_library": "com.apple.product-type.library.static", }[self.spec["type"]] def GetMachOType(self): """Returns the MACH_O_TYPE of this target.""" # Weird, but matches Xcode. if not self._IsBundle() and self.spec["type"] == "executable": return "" return { "executable": "mh_execute", "static_library": "staticlib", "shared_library": "mh_dylib", "loadable_module": "mh_bundle", }[self.spec["type"]] def _GetBundleBinaryPath(self): """Returns the name of the bundle binary of by this target. E.g. Chromium.app/Contents/MacOS/Chromium. Only valid for bundles.""" assert self._IsBundle() return os.path.join( self.GetBundleExecutableFolderPath(), self.GetExecutableName() ) def _GetStandaloneExecutableSuffix(self): if "product_extension" in self.spec: return "." + self.spec["product_extension"] return { "executable": "", "static_library": ".a", "shared_library": ".dylib", "loadable_module": ".so", }[self.spec["type"]] def _GetStandaloneExecutablePrefix(self): return self.spec.get( "product_prefix", { "executable": "", "static_library": "lib", "shared_library": "lib", # Non-bundled loadable_modules are called foo.so for some reason # (that is, .so and no prefix) with the xcode build -- match that. "loadable_module": "", }[self.spec["type"]], ) def _GetStandaloneBinaryPath(self): """Returns the name of the non-bundle binary represented by this target. E.g. hello_world. Only valid for non-bundles.""" assert not self._IsBundle() assert self.spec["type"] in ( "executable", "shared_library", "static_library", "loadable_module", ), ("Unexpected type %s" % self.spec["type"]) target = self.spec["target_name"] if self.spec["type"] == "static_library": if target[:3] == "lib": target = target[3:] elif self.spec["type"] in ("loadable_module", "shared_library"): if target[:3] == "lib": target = target[3:] target_prefix = self._GetStandaloneExecutablePrefix() target = self.spec.get("product_name", target) target_ext = self._GetStandaloneExecutableSuffix() return target_prefix + target + target_ext def GetExecutableName(self): """Returns the executable name of the bundle represented by this target. E.g. Chromium.""" if self._IsBundle(): return self.spec.get("product_name", self.spec["target_name"]) else: return self._GetStandaloneBinaryPath() def GetExecutablePath(self): """Returns the qualified path to the primary executable of the bundle represented by this target. E.g. Chromium.app/Contents/MacOS/Chromium.""" if self._IsBundle(): return self._GetBundleBinaryPath() else: return self._GetStandaloneBinaryPath() def GetActiveArchs(self, configname): """Returns the architectures this target should be built for.""" config_settings = self.xcode_settings[configname] xcode_archs_default = GetXcodeArchsDefault() return xcode_archs_default.ActiveArchs( config_settings.get("ARCHS"), config_settings.get("VALID_ARCHS"), config_settings.get("SDKROOT"), ) def _GetSdkVersionInfoItem(self, sdk, infoitem): # xcodebuild requires Xcode and can't run on Command Line Tools-only # systems from 10.7 onward. # Since the CLT has no SDK paths anyway, returning None is the # most sensible route and should still do the right thing. try: return GetStdoutQuiet(["xcrun", "--sdk", sdk, infoitem]) except GypError: pass def _SdkRoot(self, configname): if configname is None: configname = self.configname return self.GetPerConfigSetting("SDKROOT", configname, default="") def _XcodePlatformPath(self, configname=None): sdk_root = self._SdkRoot(configname) if sdk_root not in XcodeSettings._platform_path_cache: platform_path = self._GetSdkVersionInfoItem( sdk_root, "--show-sdk-platform-path" ) XcodeSettings._platform_path_cache[sdk_root] = platform_path return XcodeSettings._platform_path_cache[sdk_root] def _SdkPath(self, configname=None): sdk_root = self._SdkRoot(configname) if sdk_root.startswith("/"): return sdk_root return self._XcodeSdkPath(sdk_root) def _XcodeSdkPath(self, sdk_root): if sdk_root not in XcodeSettings._sdk_path_cache: sdk_path = self._GetSdkVersionInfoItem(sdk_root, "--show-sdk-path") XcodeSettings._sdk_path_cache[sdk_root] = sdk_path if sdk_root: XcodeSettings._sdk_root_cache[sdk_path] = sdk_root return XcodeSettings._sdk_path_cache[sdk_root] def _AppendPlatformVersionMinFlags(self, lst): self._Appendf(lst, "MACOSX_DEPLOYMENT_TARGET", "-mmacosx-version-min=%s") if "IPHONEOS_DEPLOYMENT_TARGET" in self._Settings(): # TODO: Implement this better? sdk_path_basename = os.path.basename(self._SdkPath()) if sdk_path_basename.lower().startswith("iphonesimulator"): self._Appendf( lst, "IPHONEOS_DEPLOYMENT_TARGET", "-mios-simulator-version-min=%s" ) else: self._Appendf( lst, "IPHONEOS_DEPLOYMENT_TARGET", "-miphoneos-version-min=%s" ) def GetCflags(self, configname, arch=None): """Returns flags that need to be added to .c, .cc, .m, and .mm compilations.""" # This functions (and the similar ones below) do not offer complete # emulation of all xcode_settings keys. They're implemented on demand. self.configname = configname cflags = [] sdk_root = self._SdkPath() if "SDKROOT" in self._Settings() and sdk_root: cflags.append("-isysroot %s" % sdk_root) if self.header_map_path: cflags.append("-I%s" % self.header_map_path) if self._Test("CLANG_WARN_CONSTANT_CONVERSION", "YES", default="NO"): cflags.append("-Wconstant-conversion") if self._Test("GCC_CHAR_IS_UNSIGNED_CHAR", "YES", default="NO"): cflags.append("-funsigned-char") if self._Test("GCC_CW_ASM_SYNTAX", "YES", default="YES"): cflags.append("-fasm-blocks") if "GCC_DYNAMIC_NO_PIC" in self._Settings(): if self._Settings()["GCC_DYNAMIC_NO_PIC"] == "YES": cflags.append("-mdynamic-no-pic") else: pass # TODO: In this case, it depends on the target. xcode passes # mdynamic-no-pic by default for executable and possibly static lib # according to mento if self._Test("GCC_ENABLE_PASCAL_STRINGS", "YES", default="YES"): cflags.append("-mpascal-strings") self._Appendf(cflags, "GCC_OPTIMIZATION_LEVEL", "-O%s", default="s") if self._Test("GCC_GENERATE_DEBUGGING_SYMBOLS", "YES", default="YES"): dbg_format = self._Settings().get("DEBUG_INFORMATION_FORMAT", "dwarf") if dbg_format == "dwarf": cflags.append("-gdwarf-2") elif dbg_format == "stabs": raise NotImplementedError("stabs debug format is not supported yet.") elif dbg_format == "dwarf-with-dsym": cflags.append("-gdwarf-2") else: raise NotImplementedError("Unknown debug format %s" % dbg_format) if self._Settings().get("GCC_STRICT_ALIASING") == "YES": cflags.append("-fstrict-aliasing") elif self._Settings().get("GCC_STRICT_ALIASING") == "NO": cflags.append("-fno-strict-aliasing") if self._Test("GCC_SYMBOLS_PRIVATE_EXTERN", "YES", default="NO"): cflags.append("-fvisibility=hidden") if self._Test("GCC_TREAT_WARNINGS_AS_ERRORS", "YES", default="NO"): cflags.append("-Werror") if self._Test("GCC_WARN_ABOUT_MISSING_NEWLINE", "YES", default="NO"): cflags.append("-Wnewline-eof") # In Xcode, this is only activated when GCC_COMPILER_VERSION is clang or # llvm-gcc. It also requires a fairly recent libtool, and # if the system clang isn't used, DYLD_LIBRARY_PATH needs to contain the # path to the libLTO.dylib that matches the used clang. if self._Test("LLVM_LTO", "YES", default="NO"): cflags.append("-flto") self._AppendPlatformVersionMinFlags(cflags) # TODO: if self._Test("COPY_PHASE_STRIP", "YES", default="NO"): self._WarnUnimplemented("COPY_PHASE_STRIP") self._WarnUnimplemented("GCC_DEBUGGING_SYMBOLS") self._WarnUnimplemented("GCC_ENABLE_OBJC_EXCEPTIONS") # TODO: This is exported correctly, but assigning to it is not supported. self._WarnUnimplemented("MACH_O_TYPE") self._WarnUnimplemented("PRODUCT_TYPE") # If GYP_CROSSCOMPILE (--cross-compiling), disable architecture-specific # additions and assume these will be provided as required via CC_host, # CXX_host, CC_target and CXX_target. if not gyp.common.CrossCompileRequested(): if arch is not None: archs = [arch] else: assert self.configname archs = self.GetActiveArchs(self.configname) if len(archs) != 1: # TODO: Supporting fat binaries will be annoying. self._WarnUnimplemented("ARCHS") archs = ["i386"] cflags.append("-arch " + archs[0]) if archs[0] in ("i386", "x86_64"): if self._Test("GCC_ENABLE_SSE3_EXTENSIONS", "YES", default="NO"): cflags.append("-msse3") if self._Test( "GCC_ENABLE_SUPPLEMENTAL_SSE3_INSTRUCTIONS", "YES", default="NO" ): cflags.append("-mssse3") # Note 3rd 's'. if self._Test("GCC_ENABLE_SSE41_EXTENSIONS", "YES", default="NO"): cflags.append("-msse4.1") if self._Test("GCC_ENABLE_SSE42_EXTENSIONS", "YES", default="NO"): cflags.append("-msse4.2") cflags += self._Settings().get("WARNING_CFLAGS", []) if self._IsXCTest(): platform_root = self._XcodePlatformPath(configname) if platform_root: cflags.append("-F" + platform_root + "/Developer/Library/Frameworks/") framework_root = sdk_root if sdk_root else "" config = self.spec["configurations"][self.configname] framework_dirs = config.get("mac_framework_dirs", []) for directory in framework_dirs: cflags.append("-F" + directory.replace("$(SDKROOT)", framework_root)) self.configname = None return cflags def GetCflagsC(self, configname): """Returns flags that need to be added to .c, and .m compilations.""" self.configname = configname cflags_c = [] if self._Settings().get("GCC_C_LANGUAGE_STANDARD", "") == "ansi": cflags_c.append("-ansi") else: self._Appendf(cflags_c, "GCC_C_LANGUAGE_STANDARD", "-std=%s") cflags_c += self._Settings().get("OTHER_CFLAGS", []) self.configname = None return cflags_c def GetCflagsCC(self, configname): """Returns flags that need to be added to .cc, and .mm compilations.""" self.configname = configname cflags_cc = [] clang_cxx_language_standard = self._Settings().get( "CLANG_CXX_LANGUAGE_STANDARD" ) # Note: Don't make c++0x to c++11 so that c++0x can be used with older # clangs that don't understand c++11 yet (like Xcode 4.2's). if clang_cxx_language_standard: cflags_cc.append("-std=%s" % clang_cxx_language_standard) self._Appendf(cflags_cc, "CLANG_CXX_LIBRARY", "-stdlib=%s") if self._Test("GCC_ENABLE_CPP_RTTI", "NO", default="YES"): cflags_cc.append("-fno-rtti") if self._Test("GCC_ENABLE_CPP_EXCEPTIONS", "NO", default="YES"): cflags_cc.append("-fno-exceptions") if self._Test("GCC_INLINES_ARE_PRIVATE_EXTERN", "YES", default="NO"): cflags_cc.append("-fvisibility-inlines-hidden") if self._Test("GCC_THREADSAFE_STATICS", "NO", default="YES"): cflags_cc.append("-fno-threadsafe-statics") # Note: This flag is a no-op for clang, it only has an effect for gcc. if self._Test("GCC_WARN_ABOUT_INVALID_OFFSETOF_MACRO", "NO", default="YES"): cflags_cc.append("-Wno-invalid-offsetof") other_ccflags = [] for flag in self._Settings().get("OTHER_CPLUSPLUSFLAGS", ["$(inherited)"]): # TODO: More general variable expansion. Missing in many other places too. if flag in ("$inherited", "$(inherited)", "${inherited}"): flag = "$OTHER_CFLAGS" if flag in ("$OTHER_CFLAGS", "$(OTHER_CFLAGS)", "${OTHER_CFLAGS}"): other_ccflags += self._Settings().get("OTHER_CFLAGS", []) else: other_ccflags.append(flag) cflags_cc += other_ccflags self.configname = None return cflags_cc def _AddObjectiveCGarbageCollectionFlags(self, flags): gc_policy = self._Settings().get("GCC_ENABLE_OBJC_GC", "unsupported") if gc_policy == "supported": flags.append("-fobjc-gc") elif gc_policy == "required": flags.append("-fobjc-gc-only") def _AddObjectiveCARCFlags(self, flags): if self._Test("CLANG_ENABLE_OBJC_ARC", "YES", default="NO"): flags.append("-fobjc-arc") def _AddObjectiveCMissingPropertySynthesisFlags(self, flags): if self._Test( "CLANG_WARN_OBJC_MISSING_PROPERTY_SYNTHESIS", "YES", default="NO" ): flags.append("-Wobjc-missing-property-synthesis") def GetCflagsObjC(self, configname): """Returns flags that need to be added to .m compilations.""" self.configname = configname cflags_objc = [] self._AddObjectiveCGarbageCollectionFlags(cflags_objc) self._AddObjectiveCARCFlags(cflags_objc) self._AddObjectiveCMissingPropertySynthesisFlags(cflags_objc) self.configname = None return cflags_objc def GetCflagsObjCC(self, configname): """Returns flags that need to be added to .mm compilations.""" self.configname = configname cflags_objcc = [] self._AddObjectiveCGarbageCollectionFlags(cflags_objcc) self._AddObjectiveCARCFlags(cflags_objcc) self._AddObjectiveCMissingPropertySynthesisFlags(cflags_objcc) if self._Test("GCC_OBJC_CALL_CXX_CDTORS", "YES", default="NO"): cflags_objcc.append("-fobjc-call-cxx-cdtors") self.configname = None return cflags_objcc def GetInstallNameBase(self): """Return DYLIB_INSTALL_NAME_BASE for this target.""" # Xcode sets this for shared_libraries, and for nonbundled loadable_modules. if self.spec["type"] != "shared_library" and ( self.spec["type"] != "loadable_module" or self._IsBundle() ): return None install_base = self.GetPerTargetSetting( "DYLIB_INSTALL_NAME_BASE", default="/Library/Frameworks" if self._IsBundle() else "/usr/local/lib", ) return install_base def _StandardizePath(self, path): """Do :standardizepath processing for path.""" # I'm not quite sure what :standardizepath does. Just call normpath(), # but don't let @executable_path/../foo collapse to foo. if "/" in path: prefix, rest = "", path if path.startswith("@"): prefix, rest = path.split("/", 1) rest = os.path.normpath(rest) # :standardizepath path = os.path.join(prefix, rest) return path def GetInstallName(self): """Return LD_DYLIB_INSTALL_NAME for this target.""" # Xcode sets this for shared_libraries, and for nonbundled loadable_modules. if self.spec["type"] != "shared_library" and ( self.spec["type"] != "loadable_module" or self._IsBundle() ): return None default_install_name = ( "$(DYLIB_INSTALL_NAME_BASE:standardizepath)/$(EXECUTABLE_PATH)" ) install_name = self.GetPerTargetSetting( "LD_DYLIB_INSTALL_NAME", default=default_install_name ) # Hardcode support for the variables used in chromium for now, to # unblock people using the make build. if "$" in install_name: assert install_name in ( "$(DYLIB_INSTALL_NAME_BASE:standardizepath)/" "$(WRAPPER_NAME)/$(PRODUCT_NAME)", default_install_name, ), ( "Variables in LD_DYLIB_INSTALL_NAME are not generally supported " "yet in target '%s' (got '%s')" % (self.spec["target_name"], install_name) ) install_name = install_name.replace( "$(DYLIB_INSTALL_NAME_BASE:standardizepath)", self._StandardizePath(self.GetInstallNameBase()), ) if self._IsBundle(): # These are only valid for bundles, hence the |if|. install_name = install_name.replace( "$(WRAPPER_NAME)", self.GetWrapperName() ) install_name = install_name.replace( "$(PRODUCT_NAME)", self.GetProductName() ) else: assert "$(WRAPPER_NAME)" not in install_name assert "$(PRODUCT_NAME)" not in install_name install_name = install_name.replace( "$(EXECUTABLE_PATH)", self.GetExecutablePath() ) return install_name def _MapLinkerFlagFilename(self, ldflag, gyp_to_build_path): """Checks if ldflag contains a filename and if so remaps it from gyp-directory-relative to build-directory-relative.""" # This list is expanded on demand. # They get matched as: # -exported_symbols_list file # -Wl,exported_symbols_list file # -Wl,exported_symbols_list,file LINKER_FILE = r"(\S+)" WORD = r"\S+" linker_flags = [ ["-exported_symbols_list", LINKER_FILE], # Needed for NaCl. ["-unexported_symbols_list", LINKER_FILE], ["-reexported_symbols_list", LINKER_FILE], ["-sectcreate", WORD, WORD, LINKER_FILE], # Needed for remoting. ] for flag_pattern in linker_flags: regex = re.compile("(?:-Wl,)?" + "[ ,]".join(flag_pattern)) m = regex.match(ldflag) if m: ldflag = ( ldflag[: m.start(1)] + gyp_to_build_path(m.group(1)) + ldflag[m.end(1) :] ) # Required for ffmpeg (no idea why they don't use LIBRARY_SEARCH_PATHS, # TODO(thakis): Update ffmpeg.gyp): if ldflag.startswith("-L"): ldflag = "-L" + gyp_to_build_path(ldflag[len("-L") :]) return ldflag def GetLdflags(self, configname, product_dir, gyp_to_build_path, arch=None): """Returns flags that need to be passed to the linker. Args: configname: The name of the configuration to get ld flags for. product_dir: The directory where products such static and dynamic libraries are placed. This is added to the library search path. gyp_to_build_path: A function that converts paths relative to the current gyp file to paths relative to the build directory. """ self.configname = configname ldflags = [] # The xcode build is relative to a gyp file's directory, and OTHER_LDFLAGS # can contain entries that depend on this. Explicitly absolutify these. for ldflag in self._Settings().get("OTHER_LDFLAGS", []): ldflags.append(self._MapLinkerFlagFilename(ldflag, gyp_to_build_path)) if self._Test("DEAD_CODE_STRIPPING", "YES", default="NO"): ldflags.append("-Wl,-dead_strip") if self._Test("PREBINDING", "YES", default="NO"): ldflags.append("-Wl,-prebind") self._Appendf( ldflags, "DYLIB_COMPATIBILITY_VERSION", "-compatibility_version %s" ) self._Appendf(ldflags, "DYLIB_CURRENT_VERSION", "-current_version %s") self._AppendPlatformVersionMinFlags(ldflags) if "SDKROOT" in self._Settings() and self._SdkPath(): ldflags.append("-isysroot " + self._SdkPath()) for library_path in self._Settings().get("LIBRARY_SEARCH_PATHS", []): ldflags.append("-L" + gyp_to_build_path(library_path)) if "ORDER_FILE" in self._Settings(): ldflags.append( "-Wl,-order_file " + "-Wl," + gyp_to_build_path(self._Settings()["ORDER_FILE"]) ) if not gyp.common.CrossCompileRequested(): if arch is not None: archs = [arch] else: assert self.configname archs = self.GetActiveArchs(self.configname) if len(archs) != 1: # TODO: Supporting fat binaries will be annoying. self._WarnUnimplemented("ARCHS") archs = ["i386"] ldflags.append("-arch " + archs[0]) # Xcode adds the product directory by default. # Rewrite -L. to -L./ to work around http://www.openradar.me/25313838 ldflags.append("-L" + (product_dir if product_dir != "." else "./")) install_name = self.GetInstallName() if install_name and self.spec["type"] != "loadable_module": ldflags.append("-install_name " + install_name.replace(" ", r"\ ")) for rpath in self._Settings().get("LD_RUNPATH_SEARCH_PATHS", []): ldflags.append("-Wl,-rpath," + rpath) sdk_root = self._SdkPath() if not sdk_root: sdk_root = "" config = self.spec["configurations"][self.configname] framework_dirs = config.get("mac_framework_dirs", []) for directory in framework_dirs: ldflags.append("-F" + directory.replace("$(SDKROOT)", sdk_root)) if self._IsXCTest(): platform_root = self._XcodePlatformPath(configname) if sdk_root and platform_root: ldflags.append("-F" + platform_root + "/Developer/Library/Frameworks/") ldflags.append("-framework XCTest") is_extension = self._IsIosAppExtension() or self._IsIosWatchKitExtension() if sdk_root and is_extension: # Adds the link flags for extensions. These flags are common for all # extensions and provide loader and main function. # These flags reflect the compilation options used by xcode to compile # extensions. xcode_version, _ = XcodeVersion() if xcode_version < "0900": ldflags.append("-lpkstart") ldflags.append( sdk_root + "/System/Library/PrivateFrameworks/PlugInKit.framework/PlugInKit" ) else: ldflags.append("-e _NSExtensionMain") ldflags.append("-fapplication-extension") self._Appendf(ldflags, "CLANG_CXX_LIBRARY", "-stdlib=%s") self.configname = None return ldflags def GetLibtoolflags(self, configname): """Returns flags that need to be passed to the static linker. Args: configname: The name of the configuration to get ld flags for. """ self.configname = configname libtoolflags = [] for libtoolflag in self._Settings().get("OTHER_LDFLAGS", []): libtoolflags.append(libtoolflag) # TODO(thakis): ARCHS? self.configname = None return libtoolflags def GetPerTargetSettings(self): """Gets a list of all the per-target settings. This will only fetch keys whose values are the same across all configurations.""" first_pass = True result = {} for configname in sorted(self.xcode_settings.keys()): if first_pass: result = dict(self.xcode_settings[configname]) first_pass = False else: for key, value in self.xcode_settings[configname].items(): if key not in result: continue elif result[key] != value: del result[key] return result def GetPerConfigSetting(self, setting, configname, default=None): if configname in self.xcode_settings: return self.xcode_settings[configname].get(setting, default) else: return self.GetPerTargetSetting(setting, default) def GetPerTargetSetting(self, setting, default=None): """Tries to get xcode_settings.setting from spec. Assumes that the setting has the same value in all configurations and throws otherwise.""" is_first_pass = True result = None for configname in sorted(self.xcode_settings.keys()): if is_first_pass: result = self.xcode_settings[configname].get(setting, None) is_first_pass = False else: assert result == self.xcode_settings[configname].get(setting, None), ( "Expected per-target setting for '%s', got per-config setting " "(target %s)" % (setting, self.spec["target_name"]) ) if result is None: return default return result def _GetStripPostbuilds(self, configname, output_binary, quiet): """Returns a list of shell commands that contain the shell commands necessary to strip this target's binary. These should be run as postbuilds before the actual postbuilds run.""" self.configname = configname result = [] if self._Test("DEPLOYMENT_POSTPROCESSING", "YES", default="NO") and self._Test( "STRIP_INSTALLED_PRODUCT", "YES", default="NO" ): default_strip_style = "debugging" if ( self.spec["type"] == "loadable_module" or self._IsIosAppExtension() ) and self._IsBundle(): default_strip_style = "non-global" elif self.spec["type"] == "executable": default_strip_style = "all" strip_style = self._Settings().get("STRIP_STYLE", default_strip_style) strip_flags = {"all": "", "non-global": "-x", "debugging": "-S"}[ strip_style ] explicit_strip_flags = self._Settings().get("STRIPFLAGS", "") if explicit_strip_flags: strip_flags += " " + _NormalizeEnvVarReferences(explicit_strip_flags) if not quiet: result.append("echo STRIP\\(%s\\)" % self.spec["target_name"]) result.append(f"strip {strip_flags} {output_binary}") self.configname = None return result def _GetDebugInfoPostbuilds(self, configname, output, output_binary, quiet): """Returns a list of shell commands that contain the shell commands necessary to massage this target's debug information. These should be run as postbuilds before the actual postbuilds run.""" self.configname = configname # For static libraries, no dSYMs are created. result = [] if ( self._Test("GCC_GENERATE_DEBUGGING_SYMBOLS", "YES", default="YES") and self._Test( "DEBUG_INFORMATION_FORMAT", "dwarf-with-dsym", default="dwarf" ) and self.spec["type"] != "static_library" ): if not quiet: result.append("echo DSYMUTIL\\(%s\\)" % self.spec["target_name"]) result.append("dsymutil {} -o {}".format(output_binary, output + ".dSYM")) self.configname = None return result def _GetTargetPostbuilds(self, configname, output, output_binary, quiet=False): """Returns a list of shell commands that contain the shell commands to run as postbuilds for this target, before the actual postbuilds.""" # dSYMs need to build before stripping happens. return self._GetDebugInfoPostbuilds( configname, output, output_binary, quiet ) + self._GetStripPostbuilds(configname, output_binary, quiet) def _GetIOSPostbuilds(self, configname, output_binary): """Return a shell command to codesign the iOS output binary so it can be deployed to a device. This should be run as the very last step of the build.""" if not ( self.isIOS and (self.spec["type"] == "executable" or self._IsXCTest()) or self.IsIosFramework() ): return [] postbuilds = [] product_name = self.GetFullProductName() settings = self.xcode_settings[configname] # Xcode expects XCTests to be copied into the TEST_HOST dir. if self._IsXCTest(): source = os.path.join("${BUILT_PRODUCTS_DIR}", product_name) test_host = os.path.dirname(settings.get("TEST_HOST")) xctest_destination = os.path.join(test_host, "PlugIns", product_name) postbuilds.extend([f"ditto {source} {xctest_destination}"]) key = self._GetIOSCodeSignIdentityKey(settings) if not key: return postbuilds # Warn for any unimplemented signing xcode keys. unimpl = ["OTHER_CODE_SIGN_FLAGS"] unimpl = set(unimpl) & set(self.xcode_settings[configname].keys()) if unimpl: print( "Warning: Some codesign keys not implemented, ignoring: %s" % ", ".join(sorted(unimpl)) ) if self._IsXCTest(): # For device xctests, Xcode copies two extra frameworks into $TEST_HOST. test_host = os.path.dirname(settings.get("TEST_HOST")) frameworks_dir = os.path.join(test_host, "Frameworks") platform_root = self._XcodePlatformPath(configname) frameworks = [ "Developer/Library/PrivateFrameworks/IDEBundleInjection.framework", "Developer/Library/Frameworks/XCTest.framework", ] for framework in frameworks: source = os.path.join(platform_root, framework) destination = os.path.join(frameworks_dir, os.path.basename(framework)) postbuilds.extend([f"ditto {source} {destination}"]) # Then re-sign everything with 'preserve=True' postbuilds.extend( [ '%s code-sign-bundle "%s" "%s" "%s" "%s" %s' % ( os.path.join("${TARGET_BUILD_DIR}", "gyp-mac-tool"), key, settings.get("CODE_SIGN_ENTITLEMENTS", ""), settings.get("PROVISIONING_PROFILE", ""), destination, True, ) ] ) plugin_dir = os.path.join(test_host, "PlugIns") targets = [os.path.join(plugin_dir, product_name), test_host] for target in targets: postbuilds.extend( [ '%s code-sign-bundle "%s" "%s" "%s" "%s" %s' % ( os.path.join("${TARGET_BUILD_DIR}", "gyp-mac-tool"), key, settings.get("CODE_SIGN_ENTITLEMENTS", ""), settings.get("PROVISIONING_PROFILE", ""), target, True, ) ] ) postbuilds.extend( [ '%s code-sign-bundle "%s" "%s" "%s" "%s" %s' % ( os.path.join("${TARGET_BUILD_DIR}", "gyp-mac-tool"), key, settings.get("CODE_SIGN_ENTITLEMENTS", ""), settings.get("PROVISIONING_PROFILE", ""), os.path.join("${BUILT_PRODUCTS_DIR}", product_name), False, ) ] ) return postbuilds def _GetIOSCodeSignIdentityKey(self, settings): identity = settings.get("CODE_SIGN_IDENTITY") if not identity: return None if identity not in XcodeSettings._codesigning_key_cache: output = subprocess.check_output( ["security", "find-identity", "-p", "codesigning", "-v"] ) for line in output.splitlines(): if identity in line: fingerprint = line.split()[1] cache = XcodeSettings._codesigning_key_cache assert identity not in cache or fingerprint == cache[identity], ( "Multiple codesigning fingerprints for identity: %s" % identity ) XcodeSettings._codesigning_key_cache[identity] = fingerprint return XcodeSettings._codesigning_key_cache.get(identity, "") def AddImplicitPostbuilds( self, configname, output, output_binary, postbuilds=[], quiet=False ): """Returns a list of shell commands that should run before and after |postbuilds|.""" assert output_binary is not None pre = self._GetTargetPostbuilds(configname, output, output_binary, quiet) post = self._GetIOSPostbuilds(configname, output_binary) return pre + postbuilds + post def _AdjustLibrary(self, library, config_name=None): if library.endswith(".framework"): l_flag = "-framework " + os.path.splitext(os.path.basename(library))[0] else: m = self.library_re.match(library) l_flag = "-l" + m.group(1) if m else library sdk_root = self._SdkPath(config_name) if not sdk_root: sdk_root = "" # Xcode 7 started shipping with ".tbd" (text based stubs) files instead of # ".dylib" without providing a real support for them. What it does, for # "/usr/lib" libraries, is do "-L/usr/lib -lname" which is dependent on the # library order and cause collision when building Chrome. # # Instead substitute ".tbd" to ".dylib" in the generated project when the # following conditions are both true: # - library is referenced in the gyp file as "$(SDKROOT)/**/*.dylib", # - the ".dylib" file does not exists but a ".tbd" file do. library = l_flag.replace("$(SDKROOT)", sdk_root) if l_flag.startswith("$(SDKROOT)"): basename, ext = os.path.splitext(library) if ext == ".dylib" and not os.path.exists(library): tbd_library = basename + ".tbd" if os.path.exists(tbd_library): library = tbd_library return library def AdjustLibraries(self, libraries, config_name=None): """Transforms entries like 'Cocoa.framework' in libraries into entries like '-framework Cocoa', 'libcrypto.dylib' into '-lcrypto', etc. """ libraries = [self._AdjustLibrary(library, config_name) for library in libraries] return libraries def _BuildMachineOSBuild(self): return GetStdout(["sw_vers", "-buildVersion"]) def _XcodeIOSDeviceFamily(self, configname): family = self.xcode_settings[configname].get("TARGETED_DEVICE_FAMILY", "1") return [int(x) for x in family.split(",")] def GetExtraPlistItems(self, configname=None): """Returns a dictionary with extra items to insert into Info.plist.""" if configname not in XcodeSettings._plist_cache: cache = {} cache["BuildMachineOSBuild"] = self._BuildMachineOSBuild() xcode_version, xcode_build = XcodeVersion() cache["DTXcode"] = xcode_version cache["DTXcodeBuild"] = xcode_build compiler = self.xcode_settings[configname].get("GCC_VERSION") if compiler is not None: cache["DTCompiler"] = compiler sdk_root = self._SdkRoot(configname) if not sdk_root: sdk_root = self._DefaultSdkRoot() sdk_version = self._GetSdkVersionInfoItem(sdk_root, "--show-sdk-version") cache["DTSDKName"] = sdk_root + (sdk_version or "") if xcode_version >= "0720": cache["DTSDKBuild"] = self._GetSdkVersionInfoItem( sdk_root, "--show-sdk-build-version" ) elif xcode_version >= "0430": cache["DTSDKBuild"] = sdk_version else: cache["DTSDKBuild"] = cache["BuildMachineOSBuild"] if self.isIOS: cache["MinimumOSVersion"] = self.xcode_settings[configname].get( "IPHONEOS_DEPLOYMENT_TARGET" ) cache["DTPlatformName"] = sdk_root cache["DTPlatformVersion"] = sdk_version if configname.endswith("iphoneos"): cache["CFBundleSupportedPlatforms"] = ["iPhoneOS"] cache["DTPlatformBuild"] = cache["DTSDKBuild"] else: cache["CFBundleSupportedPlatforms"] = ["iPhoneSimulator"] # This is weird, but Xcode sets DTPlatformBuild to an empty field # for simulator builds. cache["DTPlatformBuild"] = "" XcodeSettings._plist_cache[configname] = cache # Include extra plist items that are per-target, not per global # XcodeSettings. items = dict(XcodeSettings._plist_cache[configname]) if self.isIOS: items["UIDeviceFamily"] = self._XcodeIOSDeviceFamily(configname) return items def _DefaultSdkRoot(self): """Returns the default SDKROOT to use. Prior to version 5.0.0, if SDKROOT was not explicitly set in the Xcode project, then the environment variable was empty. Starting with this version, Xcode uses the name of the newest SDK installed. """ xcode_version, _ = XcodeVersion() if xcode_version < "0500": return "" default_sdk_path = self._XcodeSdkPath("") default_sdk_root = XcodeSettings._sdk_root_cache.get(default_sdk_path) if default_sdk_root: return default_sdk_root try: all_sdks = GetStdout(["xcodebuild", "-showsdks"]) except GypError: # If xcodebuild fails, there will be no valid SDKs return "" for line in all_sdks.splitlines(): items = line.split() if len(items) >= 3 and items[-2] == "-sdk": sdk_root = items[-1] sdk_path = self._XcodeSdkPath(sdk_root) if sdk_path == default_sdk_path: return sdk_root return "" class MacPrefixHeader: """A class that helps with emulating Xcode's GCC_PREFIX_HEADER feature. This feature consists of several pieces: * If GCC_PREFIX_HEADER is present, all compilations in that project get an additional |-include path_to_prefix_header| cflag. * If GCC_PRECOMPILE_PREFIX_HEADER is present too, then the prefix header is instead compiled, and all other compilations in the project get an additional |-include path_to_compiled_header| instead. + Compiled prefix headers have the extension gch. There is one gch file for every language used in the project (c, cc, m, mm), since gch files for different languages aren't compatible. + gch files themselves are built with the target's normal cflags, but they obviously don't get the |-include| flag. Instead, they need a -x flag that describes their language. + All o files in the target need to depend on the gch file, to make sure it's built before any o file is built. This class helps with some of these tasks, but it needs help from the build system for writing dependencies to the gch files, for writing build commands for the gch files, and for figuring out the location of the gch files. """ def __init__( self, xcode_settings, gyp_path_to_build_path, gyp_path_to_build_output ): """If xcode_settings is None, all methods on this class are no-ops. Args: gyp_path_to_build_path: A function that takes a gyp-relative path, and returns a path relative to the build directory. gyp_path_to_build_output: A function that takes a gyp-relative path and a language code ('c', 'cc', 'm', or 'mm'), and that returns a path to where the output of precompiling that path for that language should be placed (without the trailing '.gch'). """ # This doesn't support per-configuration prefix headers. Good enough # for now. self.header = None self.compile_headers = False if xcode_settings: self.header = xcode_settings.GetPerTargetSetting("GCC_PREFIX_HEADER") self.compile_headers = ( xcode_settings.GetPerTargetSetting( "GCC_PRECOMPILE_PREFIX_HEADER", default="NO" ) != "NO" ) self.compiled_headers = {} if self.header: if self.compile_headers: for lang in ["c", "cc", "m", "mm"]: self.compiled_headers[lang] = gyp_path_to_build_output( self.header, lang ) self.header = gyp_path_to_build_path(self.header) def _CompiledHeader(self, lang, arch): assert self.compile_headers h = self.compiled_headers[lang] if arch: h += "." + arch return h def GetInclude(self, lang, arch=None): """Gets the cflags to include the prefix header for language |lang|.""" if self.compile_headers and lang in self.compiled_headers: return "-include %s" % self._CompiledHeader(lang, arch) elif self.header: return "-include %s" % self.header else: return "" def _Gch(self, lang, arch): """Returns the actual file name of the prefix header for language |lang|.""" assert self.compile_headers return self._CompiledHeader(lang, arch) + ".gch" def GetObjDependencies(self, sources, objs, arch=None): """Given a list of source files and the corresponding object files, returns a list of (source, object, gch) tuples, where |gch| is the build-directory relative path to the gch file each object file depends on. |compilable[i]| has to be the source file belonging to |objs[i]|.""" if not self.header or not self.compile_headers: return [] result = [] for source, obj in zip(sources, objs): ext = os.path.splitext(source)[1] lang = { ".c": "c", ".cpp": "cc", ".cc": "cc", ".cxx": "cc", ".m": "m", ".mm": "mm", }.get(ext, None) if lang: result.append((source, obj, self._Gch(lang, arch))) return result def GetPchBuildCommands(self, arch=None): """Returns [(path_to_gch, language_flag, language, header)]. |path_to_gch| and |header| are relative to the build directory. """ if not self.header or not self.compile_headers: return [] return [ (self._Gch("c", arch), "-x c-header", "c", self.header), (self._Gch("cc", arch), "-x c++-header", "cc", self.header), (self._Gch("m", arch), "-x objective-c-header", "m", self.header), (self._Gch("mm", arch), "-x objective-c++-header", "mm", self.header), ] def XcodeVersion(): """Returns a tuple of version and build version of installed Xcode.""" # `xcodebuild -version` output looks like # Xcode 4.6.3 # Build version 4H1503 # or like # Xcode 3.2.6 # Component versions: DevToolsCore-1809.0; DevToolsSupport-1806.0 # BuildVersion: 10M2518 # Convert that to ('0463', '4H1503') or ('0326', '10M2518'). global XCODE_VERSION_CACHE if XCODE_VERSION_CACHE: return XCODE_VERSION_CACHE version = "" build = "" try: version_list = GetStdoutQuiet(["xcodebuild", "-version"]).splitlines() # In some circumstances xcodebuild exits 0 but doesn't return # the right results; for example, a user on 10.7 or 10.8 with # a bogus path set via xcode-select # In that case this may be a CLT-only install so fall back to # checking that version. if len(version_list) < 2: raise GypError("xcodebuild returned unexpected results") version = version_list[0].split()[-1] # Last word on first line build = version_list[-1].split()[-1] # Last word on last line except GypError: # Xcode not installed so look for XCode Command Line Tools version = CLTVersion() # macOS Catalina returns 11.0.0.0.1.1567737322 if not version: raise GypError("No Xcode or CLT version detected!") # Be careful to convert "4.2.3" to "0423" and "11.0.0" to "1100": version = version.split(".")[:3] # Just major, minor, micro version[0] = version[0].zfill(2) # Add a leading zero if major is one digit version = ("".join(version) + "00")[:4] # Limit to exactly four characters XCODE_VERSION_CACHE = (version, build) return XCODE_VERSION_CACHE # This function ported from the logic in Homebrew's CLT version check def CLTVersion(): """Returns the version of command-line tools from pkgutil.""" # pkgutil output looks like # package-id: com.apple.pkg.CLTools_Executables # version: 5.0.1.0.1.1382131676 # volume: / # location: / # install-time: 1382544035 # groups: com.apple.FindSystemFiles.pkg-group # com.apple.DevToolsBoth.pkg-group # com.apple.DevToolsNonRelocatableShared.pkg-group STANDALONE_PKG_ID = "com.apple.pkg.DeveloperToolsCLILeo" FROM_XCODE_PKG_ID = "com.apple.pkg.DeveloperToolsCLI" MAVERICKS_PKG_ID = "com.apple.pkg.CLTools_Executables" regex = re.compile("version: (?P.+)") for key in [MAVERICKS_PKG_ID, STANDALONE_PKG_ID, FROM_XCODE_PKG_ID]: try: output = GetStdout(["/usr/sbin/pkgutil", "--pkg-info", key]) return re.search(regex, output).groupdict()["version"] except GypError: continue regex = re.compile(r"Command Line Tools for Xcode\s+(?P\S+)") try: output = GetStdout(["/usr/sbin/softwareupdate", "--history"]) return re.search(regex, output).groupdict()["version"] except GypError: return None def GetStdoutQuiet(cmdlist): """Returns the content of standard output returned by invoking |cmdlist|. Ignores the stderr. Raises |GypError| if the command return with a non-zero return code.""" job = subprocess.Popen(cmdlist, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out = job.communicate()[0].decode("utf-8") if job.returncode != 0: raise GypError("Error %d running %s" % (job.returncode, cmdlist[0])) return out.rstrip("\n") def GetStdout(cmdlist): """Returns the content of standard output returned by invoking |cmdlist|. Raises |GypError| if the command return with a non-zero return code.""" job = subprocess.Popen(cmdlist, stdout=subprocess.PIPE) out = job.communicate()[0].decode("utf-8") if job.returncode != 0: sys.stderr.write(out + "\n") raise GypError("Error %d running %s" % (job.returncode, cmdlist[0])) return out.rstrip("\n") def MergeGlobalXcodeSettingsToSpec(global_dict, spec): """Merges the global xcode_settings dictionary into each configuration of the target represented by spec. For keys that are both in the global and the local xcode_settings dict, the local key gets precedence. """ # The xcode generator special-cases global xcode_settings and does something # that amounts to merging in the global xcode_settings into each local # xcode_settings dict. global_xcode_settings = global_dict.get("xcode_settings", {}) for config in spec["configurations"].values(): if "xcode_settings" in config: new_settings = global_xcode_settings.copy() new_settings.update(config["xcode_settings"]) config["xcode_settings"] = new_settings def IsMacBundle(flavor, spec): """Returns if |spec| should be treated as a bundle. Bundles are directories with a certain subdirectory structure, instead of just a single file. Bundle rules do not produce a binary but also package resources into that directory.""" is_mac_bundle = ( int(spec.get("mac_xctest_bundle", 0)) != 0 or int(spec.get("mac_xcuitest_bundle", 0)) != 0 or (int(spec.get("mac_bundle", 0)) != 0 and flavor == "mac") ) if is_mac_bundle: assert spec["type"] != "none", ( 'mac_bundle targets cannot have type none (target "%s")' % spec["target_name"] ) return is_mac_bundle def GetMacBundleResources(product_dir, xcode_settings, resources): """Yields (output, resource) pairs for every resource in |resources|. Only call this for mac bundle targets. Args: product_dir: Path to the directory containing the output bundle, relative to the build directory. xcode_settings: The XcodeSettings of the current target. resources: A list of bundle resources, relative to the build directory. """ dest = os.path.join(product_dir, xcode_settings.GetBundleResourceFolder()) for res in resources: output = dest # The make generator doesn't support it, so forbid it everywhere # to keep the generators more interchangeable. assert " " not in res, "Spaces in resource filenames not supported (%s)" % res # Split into (path,file). res_parts = os.path.split(res) # Now split the path into (prefix,maybe.lproj). lproj_parts = os.path.split(res_parts[0]) # If the resource lives in a .lproj bundle, add that to the destination. if lproj_parts[1].endswith(".lproj"): output = os.path.join(output, lproj_parts[1]) output = os.path.join(output, res_parts[1]) # Compiled XIB files are referred to by .nib. if output.endswith(".xib"): output = os.path.splitext(output)[0] + ".nib" # Compiled storyboard files are referred to by .storyboardc. if output.endswith(".storyboard"): output = os.path.splitext(output)[0] + ".storyboardc" yield output, res def GetMacInfoPlist(product_dir, xcode_settings, gyp_path_to_build_path): """Returns (info_plist, dest_plist, defines, extra_env), where: * |info_plist| is the source plist path, relative to the build directory, * |dest_plist| is the destination plist path, relative to the build directory, * |defines| is a list of preprocessor defines (empty if the plist shouldn't be preprocessed, * |extra_env| is a dict of env variables that should be exported when invoking |mac_tool copy-info-plist|. Only call this for mac bundle targets. Args: product_dir: Path to the directory containing the output bundle, relative to the build directory. xcode_settings: The XcodeSettings of the current target. gyp_to_build_path: A function that converts paths relative to the current gyp file to paths relative to the build directory. """ info_plist = xcode_settings.GetPerTargetSetting("INFOPLIST_FILE") if not info_plist: return None, None, [], {} # The make generator doesn't support it, so forbid it everywhere # to keep the generators more interchangeable. assert " " not in info_plist, ( "Spaces in Info.plist filenames not supported (%s)" % info_plist ) info_plist = gyp_path_to_build_path(info_plist) # If explicitly set to preprocess the plist, invoke the C preprocessor and # specify any defines as -D flags. if ( xcode_settings.GetPerTargetSetting("INFOPLIST_PREPROCESS", default="NO") == "YES" ): # Create an intermediate file based on the path. defines = shlex.split( xcode_settings.GetPerTargetSetting( "INFOPLIST_PREPROCESSOR_DEFINITIONS", default="" ) ) else: defines = [] dest_plist = os.path.join(product_dir, xcode_settings.GetBundlePlistPath()) extra_env = xcode_settings.GetPerTargetSettings() return info_plist, dest_plist, defines, extra_env def _GetXcodeEnv( xcode_settings, built_products_dir, srcroot, configuration, additional_settings=None ): """Return the environment variables that Xcode would set. See http://developer.apple.com/library/mac/#documentation/DeveloperTools/Reference/XcodeBuildSettingRef/1-Build_Setting_Reference/build_setting_ref.html#//apple_ref/doc/uid/TP40003931-CH3-SW153 for a full list. Args: xcode_settings: An XcodeSettings object. If this is None, this function returns an empty dict. built_products_dir: Absolute path to the built products dir. srcroot: Absolute path to the source root. configuration: The build configuration name. additional_settings: An optional dict with more values to add to the result. """ if not xcode_settings: return {} # This function is considered a friend of XcodeSettings, so let it reach into # its implementation details. spec = xcode_settings.spec # These are filled in on an as-needed basis. env = { "BUILT_FRAMEWORKS_DIR": built_products_dir, "BUILT_PRODUCTS_DIR": built_products_dir, "CONFIGURATION": configuration, "PRODUCT_NAME": xcode_settings.GetProductName(), # For FULL_PRODUCT_NAME see: # /Developer/Platforms/MacOSX.platform/Developer/Library/Xcode/Specifications/MacOSX\ Product\ Types.xcspec # noqa: E501 "SRCROOT": srcroot, "SOURCE_ROOT": "${SRCROOT}", # This is not true for static libraries, but currently the env is only # written for bundles: "TARGET_BUILD_DIR": built_products_dir, "TEMP_DIR": "${TMPDIR}", "XCODE_VERSION_ACTUAL": XcodeVersion()[0], } if xcode_settings.GetPerConfigSetting("SDKROOT", configuration): env["SDKROOT"] = xcode_settings._SdkPath(configuration) else: env["SDKROOT"] = "" if xcode_settings.mac_toolchain_dir: env["DEVELOPER_DIR"] = xcode_settings.mac_toolchain_dir if spec["type"] in ( "executable", "static_library", "shared_library", "loadable_module", ): env["EXECUTABLE_NAME"] = xcode_settings.GetExecutableName() env["EXECUTABLE_PATH"] = xcode_settings.GetExecutablePath() env["FULL_PRODUCT_NAME"] = xcode_settings.GetFullProductName() mach_o_type = xcode_settings.GetMachOType() if mach_o_type: env["MACH_O_TYPE"] = mach_o_type env["PRODUCT_TYPE"] = xcode_settings.GetProductType() if xcode_settings._IsBundle(): # xcodeproj_file.py sets the same Xcode subfolder value for this as for # FRAMEWORKS_FOLDER_PATH so Xcode builds will actually use FFP's value. env["BUILT_FRAMEWORKS_DIR"] = os.path.join( built_products_dir + os.sep + xcode_settings.GetBundleFrameworksFolderPath() ) env["CONTENTS_FOLDER_PATH"] = xcode_settings.GetBundleContentsFolderPath() env["EXECUTABLE_FOLDER_PATH"] = xcode_settings.GetBundleExecutableFolderPath() env[ "UNLOCALIZED_RESOURCES_FOLDER_PATH" ] = xcode_settings.GetBundleResourceFolder() env["JAVA_FOLDER_PATH"] = xcode_settings.GetBundleJavaFolderPath() env["FRAMEWORKS_FOLDER_PATH"] = xcode_settings.GetBundleFrameworksFolderPath() env[ "SHARED_FRAMEWORKS_FOLDER_PATH" ] = xcode_settings.GetBundleSharedFrameworksFolderPath() env[ "SHARED_SUPPORT_FOLDER_PATH" ] = xcode_settings.GetBundleSharedSupportFolderPath() env["PLUGINS_FOLDER_PATH"] = xcode_settings.GetBundlePlugInsFolderPath() env["XPCSERVICES_FOLDER_PATH"] = xcode_settings.GetBundleXPCServicesFolderPath() env["INFOPLIST_PATH"] = xcode_settings.GetBundlePlistPath() env["WRAPPER_NAME"] = xcode_settings.GetWrapperName() install_name = xcode_settings.GetInstallName() if install_name: env["LD_DYLIB_INSTALL_NAME"] = install_name install_name_base = xcode_settings.GetInstallNameBase() if install_name_base: env["DYLIB_INSTALL_NAME_BASE"] = install_name_base xcode_version, _ = XcodeVersion() if xcode_version >= "0500" and not env.get("SDKROOT"): sdk_root = xcode_settings._SdkRoot(configuration) if not sdk_root: sdk_root = xcode_settings._XcodeSdkPath("") if sdk_root is None: sdk_root = "" env["SDKROOT"] = sdk_root if not additional_settings: additional_settings = {} else: # Flatten lists to strings. for k in additional_settings: if not isinstance(additional_settings[k], str): additional_settings[k] = " ".join(additional_settings[k]) additional_settings.update(env) for k in additional_settings: additional_settings[k] = _NormalizeEnvVarReferences(additional_settings[k]) return additional_settings def _NormalizeEnvVarReferences(str): """Takes a string containing variable references in the form ${FOO}, $(FOO), or $FOO, and returns a string with all variable references in the form ${FOO}. """ # $FOO -> ${FOO} str = re.sub(r"\$([a-zA-Z_][a-zA-Z0-9_]*)", r"${\1}", str) # $(FOO) -> ${FOO} matches = re.findall(r"(\$\(([a-zA-Z0-9\-_]+)\))", str) for match in matches: to_replace, variable = match assert "$(" not in match, "$($(FOO)) variables not supported: " + match str = str.replace(to_replace, "${" + variable + "}") return str def ExpandEnvVars(string, expansions): """Expands ${VARIABLES}, $(VARIABLES), and $VARIABLES in string per the expansions list. If the variable expands to something that references another variable, this variable is expanded as well if it's in env -- until no variables present in env are left.""" for k, v in reversed(expansions): string = string.replace("${" + k + "}", v) string = string.replace("$(" + k + ")", v) string = string.replace("$" + k, v) return string def _TopologicallySortedEnvVarKeys(env): """Takes a dict |env| whose values are strings that can refer to other keys, for example env['foo'] = '$(bar) and $(baz)'. Returns a list L of all keys of env such that key2 is after key1 in L if env[key2] refers to env[key1]. Throws an Exception in case of dependency cycles. """ # Since environment variables can refer to other variables, the evaluation # order is important. Below is the logic to compute the dependency graph # and sort it. regex = re.compile(r"\$\{([a-zA-Z0-9\-_]+)\}") def GetEdges(node): # Use a definition of edges such that user_of_variable -> used_varible. # This happens to be easier in this case, since a variable's # definition contains all variables it references in a single string. # We can then reverse the result of the topological sort at the end. # Since: reverse(topsort(DAG)) = topsort(reverse_edges(DAG)) matches = {v for v in regex.findall(env[node]) if v in env} for dependee in matches: assert "${" not in dependee, "Nested variables not supported: " + dependee return matches try: # Topologically sort, and then reverse, because we used an edge definition # that's inverted from the expected result of this function (see comment # above). order = gyp.common.TopologicallySorted(env.keys(), GetEdges) order.reverse() return order except gyp.common.CycleError as e: raise GypError( "Xcode environment variables are cyclically dependent: " + str(e.nodes) ) def GetSortedXcodeEnv( xcode_settings, built_products_dir, srcroot, configuration, additional_settings=None ): env = _GetXcodeEnv( xcode_settings, built_products_dir, srcroot, configuration, additional_settings ) return [(key, env[key]) for key in _TopologicallySortedEnvVarKeys(env)] def GetSpecPostbuildCommands(spec, quiet=False): """Returns the list of postbuilds explicitly defined on |spec|, in a form executable by a shell.""" postbuilds = [] for postbuild in spec.get("postbuilds", []): if not quiet: postbuilds.append( "echo POSTBUILD\\(%s\\) %s" % (spec["target_name"], postbuild["postbuild_name"]) ) postbuilds.append(gyp.common.EncodePOSIXShellList(postbuild["action"])) return postbuilds def _HasIOSTarget(targets): """Returns true if any target contains the iOS specific key IPHONEOS_DEPLOYMENT_TARGET.""" for target_dict in targets.values(): for config in target_dict["configurations"].values(): if config.get("xcode_settings", {}).get("IPHONEOS_DEPLOYMENT_TARGET"): return True return False def _AddIOSDeviceConfigurations(targets): """Clone all targets and append -iphoneos to the name. Configure these targets to build for iOS devices and use correct architectures for those builds.""" for target_dict in targets.values(): toolset = target_dict["toolset"] configs = target_dict["configurations"] for config_name, simulator_config_dict in dict(configs).items(): iphoneos_config_dict = copy.deepcopy(simulator_config_dict) configs[config_name + "-iphoneos"] = iphoneos_config_dict configs[config_name + "-iphonesimulator"] = simulator_config_dict if toolset == "target": simulator_config_dict["xcode_settings"]["SDKROOT"] = "iphonesimulator" iphoneos_config_dict["xcode_settings"]["SDKROOT"] = "iphoneos" return targets def CloneConfigurationForDeviceAndEmulator(target_dicts): """If |target_dicts| contains any iOS targets, automatically create -iphoneos targets for iOS device builds.""" if _HasIOSTarget(target_dicts): return _AddIOSDeviceConfigurations(target_dicts) return target_dicts PK ~\0ҋJJ(node-gyp/gyp/pylib/gyp/msvs_emulation.pynu[# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ This module helps emulate Visual Studio 2008 behavior on top of other build systems, primarily ninja. """ import collections import os import re import subprocess import sys from gyp.common import OrderedSet import gyp.MSVSUtil import gyp.MSVSVersion windows_quoter_regex = re.compile(r'(\\*)"') def QuoteForRspFile(arg, quote_cmd=True): """Quote a command line argument so that it appears as one argument when processed via cmd.exe and parsed by CommandLineToArgvW (as is typical for Windows programs).""" # See http://goo.gl/cuFbX and http://goo.gl/dhPnp including the comment # threads. This is actually the quoting rules for CommandLineToArgvW, not # for the shell, because the shell doesn't do anything in Windows. This # works more or less because most programs (including the compiler, etc.) # use that function to handle command line arguments. # Use a heuristic to try to find args that are paths, and normalize them if arg.find("/") > 0 or arg.count("/") > 1: arg = os.path.normpath(arg) # For a literal quote, CommandLineToArgvW requires 2n+1 backslashes # preceding it, and results in n backslashes + the quote. So we substitute # in 2* what we match, +1 more, plus the quote. if quote_cmd: arg = windows_quoter_regex.sub(lambda mo: 2 * mo.group(1) + '\\"', arg) # %'s also need to be doubled otherwise they're interpreted as batch # positional arguments. Also make sure to escape the % so that they're # passed literally through escaping so they can be singled to just the # original %. Otherwise, trying to pass the literal representation that # looks like an environment variable to the shell (e.g. %PATH%) would fail. arg = arg.replace("%", "%%") # These commands are used in rsp files, so no escaping for the shell (via ^) # is necessary. # As a workaround for programs that don't use CommandLineToArgvW, gyp # supports msvs_quote_cmd=0, which simply disables all quoting. if quote_cmd: # Finally, wrap the whole thing in quotes so that the above quote rule # applies and whitespace isn't a word break. return f'"{arg}"' return arg def EncodeRspFileList(args, quote_cmd): """Process a list of arguments using QuoteCmdExeArgument.""" # Note that the first argument is assumed to be the command. Don't add # quotes around it because then built-ins like 'echo', etc. won't work. # Take care to normpath only the path in the case of 'call ../x.bat' because # otherwise the whole thing is incorrectly interpreted as a path and not # normalized correctly. if not args: return "" if args[0].startswith("call "): call, program = args[0].split(" ", 1) program = call + " " + os.path.normpath(program) else: program = os.path.normpath(args[0]) return (program + " " + " ".join(QuoteForRspFile(arg, quote_cmd) for arg in args[1:])) def _GenericRetrieve(root, default, path): """Given a list of dictionary keys |path| and a tree of dicts |root|, find value at path, or return |default| if any of the path doesn't exist.""" if not root: return default if not path: return root return _GenericRetrieve(root.get(path[0]), default, path[1:]) def _AddPrefix(element, prefix): """Add |prefix| to |element| or each subelement if element is iterable.""" if element is None: return element # Note, not Iterable because we don't want to handle strings like that. if isinstance(element, (list, tuple)): return [prefix + e for e in element] else: return prefix + element def _DoRemapping(element, map): """If |element| then remap it through |map|. If |element| is iterable then each item will be remapped. Any elements not found will be removed.""" if map is not None and element is not None: if not callable(map): map = map.get # Assume it's a dict, otherwise a callable to do the remap. if isinstance(element, (list, tuple)): element = filter(None, [map(elem) for elem in element]) else: element = map(element) return element def _AppendOrReturn(append, element): """If |append| is None, simply return |element|. If |append| is not None, then add |element| to it, adding each item in |element| if it's a list or tuple.""" if append is not None and element is not None: if isinstance(element, (list, tuple)): append.extend(element) else: append.append(element) else: return element def _FindDirectXInstallation(): """Try to find an installation location for the DirectX SDK. Check for the standard environment variable, and if that doesn't exist, try to find via the registry. May return None if not found in either location.""" # Return previously calculated value, if there is one if hasattr(_FindDirectXInstallation, "dxsdk_dir"): return _FindDirectXInstallation.dxsdk_dir dxsdk_dir = os.environ.get("DXSDK_DIR") if not dxsdk_dir: # Setup params to pass to and attempt to launch reg.exe. cmd = ["reg.exe", "query", r"HKLM\Software\Microsoft\DirectX", "/s"] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = p.communicate()[0].decode("utf-8") for line in stdout.splitlines(): if "InstallPath" in line: dxsdk_dir = line.split(" ")[3] + "\\" # Cache return value _FindDirectXInstallation.dxsdk_dir = dxsdk_dir return dxsdk_dir def GetGlobalVSMacroEnv(vs_version): """Get a dict of variables mapping internal VS macro names to their gyp equivalents. Returns all variables that are independent of the target.""" env = {} # '$(VSInstallDir)' and '$(VCInstallDir)' are available when and only when # Visual Studio is actually installed. if vs_version.Path(): env["$(VSInstallDir)"] = vs_version.Path() env["$(VCInstallDir)"] = os.path.join(vs_version.Path(), "VC") + "\\" # Chromium uses DXSDK_DIR in include/lib paths, but it may or may not be # set. This happens when the SDK is sync'd via src-internal, rather than # by typical end-user installation of the SDK. If it's not set, we don't # want to leave the unexpanded variable in the path, so simply strip it. dxsdk_dir = _FindDirectXInstallation() env["$(DXSDK_DIR)"] = dxsdk_dir if dxsdk_dir else "" # Try to find an installation location for the Windows DDK by checking # the WDK_DIR environment variable, may be None. env["$(WDK_DIR)"] = os.environ.get("WDK_DIR", "") return env def ExtractSharedMSVSSystemIncludes(configs, generator_flags): """Finds msvs_system_include_dirs that are common to all targets, removes them from all targets, and returns an OrderedSet containing them.""" all_system_includes = OrderedSet(configs[0].get("msvs_system_include_dirs", [])) for config in configs[1:]: system_includes = config.get("msvs_system_include_dirs", []) all_system_includes = all_system_includes & OrderedSet(system_includes) if not all_system_includes: return None # Expand macros in all_system_includes. env = GetGlobalVSMacroEnv(GetVSVersion(generator_flags)) expanded_system_includes = OrderedSet( [ExpandMacros(include, env) for include in all_system_includes] ) if any("$" in include for include in expanded_system_includes): # Some path relies on target-specific variables, bail. return None # Remove system includes shared by all targets from the targets. for config in configs: includes = config.get("msvs_system_include_dirs", []) if includes: # Don't insert a msvs_system_include_dirs key if not needed. # This must check the unexpanded includes list: new_includes = [i for i in includes if i not in all_system_includes] config["msvs_system_include_dirs"] = new_includes return expanded_system_includes class MsvsSettings: """A class that understands the gyp 'msvs_...' values (especially the msvs_settings field). They largely correpond to the VS2008 IDE DOM. This class helps map those settings to command line options.""" def __init__(self, spec, generator_flags): self.spec = spec self.vs_version = GetVSVersion(generator_flags) supported_fields = [ ("msvs_configuration_attributes", dict), ("msvs_settings", dict), ("msvs_system_include_dirs", list), ("msvs_disabled_warnings", list), ("msvs_precompiled_header", str), ("msvs_precompiled_source", str), ("msvs_configuration_platform", str), ("msvs_target_platform", str), ] configs = spec["configurations"] for field, default in supported_fields: setattr(self, field, {}) for configname, config in configs.items(): getattr(self, field)[configname] = config.get(field, default()) self.msvs_cygwin_dirs = spec.get("msvs_cygwin_dirs", ["."]) unsupported_fields = [ "msvs_prebuild", "msvs_postbuild", ] unsupported = [] for field in unsupported_fields: for config in configs.values(): if field in config: unsupported += [ "{} not supported (target {}).".format( field, spec["target_name"] ) ] if unsupported: raise Exception("\n".join(unsupported)) def GetExtension(self): """Returns the extension for the target, with no leading dot. Uses 'product_extension' if specified, otherwise uses MSVS defaults based on the target type. """ ext = self.spec.get("product_extension", None) if ext: return ext return gyp.MSVSUtil.TARGET_TYPE_EXT.get(self.spec["type"], "") def GetVSMacroEnv(self, base_to_build=None, config=None): """Get a dict of variables mapping internal VS macro names to their gyp equivalents.""" target_arch = self.GetArch(config) target_platform = "Win32" if target_arch == "x86" else target_arch target_name = self.spec.get("product_prefix", "") + self.spec.get( "product_name", self.spec["target_name"] ) target_dir = base_to_build + "\\" if base_to_build else "" target_ext = "." + self.GetExtension() target_file_name = target_name + target_ext replacements = { "$(InputName)": "${root}", "$(InputPath)": "${source}", "$(IntDir)": "$!INTERMEDIATE_DIR", "$(OutDir)\\": target_dir, "$(PlatformName)": target_platform, "$(ProjectDir)\\": "", "$(ProjectName)": self.spec["target_name"], "$(TargetDir)\\": target_dir, "$(TargetExt)": target_ext, "$(TargetFileName)": target_file_name, "$(TargetName)": target_name, "$(TargetPath)": os.path.join(target_dir, target_file_name), } replacements.update(GetGlobalVSMacroEnv(self.vs_version)) return replacements def ConvertVSMacros(self, s, base_to_build=None, config=None): """Convert from VS macro names to something equivalent.""" env = self.GetVSMacroEnv(base_to_build, config=config) return ExpandMacros(s, env) def AdjustLibraries(self, libraries): """Strip -l from library if it's specified with that.""" libs = [lib[2:] if lib.startswith("-l") else lib for lib in libraries] return [ lib + ".lib" if not lib.lower().endswith(".lib") and not lib.lower().endswith(".obj") else lib for lib in libs ] def _GetAndMunge(self, field, path, default, prefix, append, map): """Retrieve a value from |field| at |path| or return |default|. If |append| is specified, and the item is found, it will be appended to that object instead of returned. If |map| is specified, results will be remapped through |map| before being returned or appended.""" result = _GenericRetrieve(field, default, path) result = _DoRemapping(result, map) result = _AddPrefix(result, prefix) return _AppendOrReturn(append, result) class _GetWrapper: def __init__(self, parent, field, base_path, append=None): self.parent = parent self.field = field self.base_path = [base_path] self.append = append def __call__(self, name, map=None, prefix="", default=None): return self.parent._GetAndMunge( self.field, self.base_path + [name], default=default, prefix=prefix, append=self.append, map=map, ) def GetArch(self, config): """Get architecture based on msvs_configuration_platform and msvs_target_platform. Returns either 'x86' or 'x64'.""" configuration_platform = self.msvs_configuration_platform.get(config, "") platform = self.msvs_target_platform.get(config, "") if not platform: # If no specific override, use the configuration's. platform = configuration_platform # Map from platform to architecture. return {"Win32": "x86", "x64": "x64", "ARM64": "arm64"}.get(platform, "x86") def _TargetConfig(self, config): """Returns the target-specific configuration.""" # There's two levels of architecture/platform specification in VS. The # first level is globally for the configuration (this is what we consider # "the" config at the gyp level, which will be something like 'Debug' or # 'Release'), VS2015 and later only use this level if int(self.vs_version.short_name) >= 2015: return config # and a second target-specific configuration, which is an # override for the global one. |config| is remapped here to take into # account the local target-specific overrides to the global configuration. arch = self.GetArch(config) if arch == "x64" and not config.endswith("_x64"): config += "_x64" if arch == "x86" and config.endswith("_x64"): config = config.rsplit("_", 1)[0] return config def _Setting(self, path, config, default=None, prefix="", append=None, map=None): """_GetAndMunge for msvs_settings.""" return self._GetAndMunge( self.msvs_settings[config], path, default, prefix, append, map ) def _ConfigAttrib( self, path, config, default=None, prefix="", append=None, map=None ): """_GetAndMunge for msvs_configuration_attributes.""" return self._GetAndMunge( self.msvs_configuration_attributes[config], path, default, prefix, append, map, ) def AdjustIncludeDirs(self, include_dirs, config): """Updates include_dirs to expand VS specific paths, and adds the system include dirs used for platform SDK and similar.""" config = self._TargetConfig(config) includes = include_dirs + self.msvs_system_include_dirs[config] includes.extend( self._Setting( ("VCCLCompilerTool", "AdditionalIncludeDirectories"), config, default=[] ) ) return [self.ConvertVSMacros(p, config=config) for p in includes] def AdjustMidlIncludeDirs(self, midl_include_dirs, config): """Updates midl_include_dirs to expand VS specific paths, and adds the system include dirs used for platform SDK and similar.""" config = self._TargetConfig(config) includes = midl_include_dirs + self.msvs_system_include_dirs[config] includes.extend( self._Setting( ("VCMIDLTool", "AdditionalIncludeDirectories"), config, default=[] ) ) return [self.ConvertVSMacros(p, config=config) for p in includes] def GetComputedDefines(self, config): """Returns the set of defines that are injected to the defines list based on other VS settings.""" config = self._TargetConfig(config) defines = [] if self._ConfigAttrib(["CharacterSet"], config) == "1": defines.extend(("_UNICODE", "UNICODE")) if self._ConfigAttrib(["CharacterSet"], config) == "2": defines.append("_MBCS") defines.extend( self._Setting( ("VCCLCompilerTool", "PreprocessorDefinitions"), config, default=[] ) ) return defines def GetCompilerPdbName(self, config, expand_special): """Get the pdb file name that should be used for compiler invocations, or None if there's no explicit name specified.""" config = self._TargetConfig(config) pdbname = self._Setting(("VCCLCompilerTool", "ProgramDataBaseFileName"), config) if pdbname: pdbname = expand_special(self.ConvertVSMacros(pdbname)) return pdbname def GetMapFileName(self, config, expand_special): """Gets the explicitly overridden map file name for a target or returns None if it's not set.""" config = self._TargetConfig(config) map_file = self._Setting(("VCLinkerTool", "MapFileName"), config) if map_file: map_file = expand_special(self.ConvertVSMacros(map_file, config=config)) return map_file def GetOutputName(self, config, expand_special): """Gets the explicitly overridden output name for a target or returns None if it's not overridden.""" config = self._TargetConfig(config) type = self.spec["type"] root = "VCLibrarianTool" if type == "static_library" else "VCLinkerTool" # TODO(scottmg): Handle OutputDirectory without OutputFile. output_file = self._Setting((root, "OutputFile"), config) if output_file: output_file = expand_special( self.ConvertVSMacros(output_file, config=config) ) return output_file def GetPDBName(self, config, expand_special, default): """Gets the explicitly overridden pdb name for a target or returns default if it's not overridden, or if no pdb will be generated.""" config = self._TargetConfig(config) output_file = self._Setting(("VCLinkerTool", "ProgramDatabaseFile"), config) generate_debug_info = self._Setting( ("VCLinkerTool", "GenerateDebugInformation"), config ) if generate_debug_info == "true": if output_file: return expand_special(self.ConvertVSMacros(output_file, config=config)) else: return default else: return None def GetNoImportLibrary(self, config): """If NoImportLibrary: true, ninja will not expect the output to include an import library.""" config = self._TargetConfig(config) noimplib = self._Setting(("NoImportLibrary",), config) return noimplib == "true" def GetAsmflags(self, config): """Returns the flags that need to be added to ml invocations.""" config = self._TargetConfig(config) asmflags = [] safeseh = self._Setting(("MASM", "UseSafeExceptionHandlers"), config) if safeseh == "true": asmflags.append("/safeseh") return asmflags def GetCflags(self, config): """Returns the flags that need to be added to .c and .cc compilations.""" config = self._TargetConfig(config) cflags = [] cflags.extend(["/wd" + w for w in self.msvs_disabled_warnings[config]]) cl = self._GetWrapper( self, self.msvs_settings[config], "VCCLCompilerTool", append=cflags ) cl( "Optimization", map={"0": "d", "1": "1", "2": "2", "3": "x"}, prefix="/O", default="2", ) cl("InlineFunctionExpansion", prefix="/Ob") cl("DisableSpecificWarnings", prefix="/wd") cl("StringPooling", map={"true": "/GF"}) cl("EnableFiberSafeOptimizations", map={"true": "/GT"}) cl("OmitFramePointers", map={"false": "-", "true": ""}, prefix="/Oy") cl("EnableIntrinsicFunctions", map={"false": "-", "true": ""}, prefix="/Oi") cl("FavorSizeOrSpeed", map={"1": "t", "2": "s"}, prefix="/O") cl( "FloatingPointModel", map={"0": "precise", "1": "strict", "2": "fast"}, prefix="/fp:", default="0", ) cl("CompileAsManaged", map={"false": "", "true": "/clr"}) cl("WholeProgramOptimization", map={"true": "/GL"}) cl("WarningLevel", prefix="/W") cl("WarnAsError", map={"true": "/WX"}) cl( "CallingConvention", map={"0": "d", "1": "r", "2": "z", "3": "v"}, prefix="/G", ) cl("DebugInformationFormat", map={"1": "7", "3": "i", "4": "I"}, prefix="/Z") cl("RuntimeTypeInfo", map={"true": "/GR", "false": "/GR-"}) cl("EnableFunctionLevelLinking", map={"true": "/Gy", "false": "/Gy-"}) cl("MinimalRebuild", map={"true": "/Gm"}) cl("BufferSecurityCheck", map={"true": "/GS", "false": "/GS-"}) cl("BasicRuntimeChecks", map={"1": "s", "2": "u", "3": "1"}, prefix="/RTC") cl( "RuntimeLibrary", map={"0": "T", "1": "Td", "2": "D", "3": "Dd"}, prefix="/M", ) cl("ExceptionHandling", map={"1": "sc", "2": "a"}, prefix="/EH") cl("DefaultCharIsUnsigned", map={"true": "/J"}) cl( "TreatWChar_tAsBuiltInType", map={"false": "-", "true": ""}, prefix="/Zc:wchar_t", ) cl("EnablePREfast", map={"true": "/analyze"}) cl("AdditionalOptions", prefix="") cl( "EnableEnhancedInstructionSet", map={"1": "SSE", "2": "SSE2", "3": "AVX", "4": "IA32", "5": "AVX2"}, prefix="/arch:", ) cflags.extend( [ "/FI" + f for f in self._Setting( ("VCCLCompilerTool", "ForcedIncludeFiles"), config, default=[] ) ] ) if float(self.vs_version.project_version) >= 12.0: # New flag introduced in VS2013 (project version 12.0) Forces writes to # the program database (PDB) to be serialized through MSPDBSRV.EXE. # https://msdn.microsoft.com/en-us/library/dn502518.aspx cflags.append("/FS") # ninja handles parallelism by itself, don't have the compiler do it too. cflags = [x for x in cflags if not x.startswith("/MP")] return cflags def _GetPchFlags(self, config, extension): """Get the flags to be added to the cflags for precompiled header support.""" config = self._TargetConfig(config) # The PCH is only built once by a particular source file. Usage of PCH must # only be for the same language (i.e. C vs. C++), so only include the pch # flags when the language matches. if self.msvs_precompiled_header[config]: source_ext = os.path.splitext(self.msvs_precompiled_source[config])[1] if _LanguageMatchesForPch(source_ext, extension): pch = self.msvs_precompiled_header[config] pchbase = os.path.split(pch)[1] return ["/Yu" + pch, "/FI" + pch, "/Fp${pchprefix}." + pchbase + ".pch"] return [] def GetCflagsC(self, config): """Returns the flags that need to be added to .c compilations.""" config = self._TargetConfig(config) return self._GetPchFlags(config, ".c") def GetCflagsCC(self, config): """Returns the flags that need to be added to .cc compilations.""" config = self._TargetConfig(config) return ["/TP"] + self._GetPchFlags(config, ".cc") def _GetAdditionalLibraryDirectories(self, root, config, gyp_to_build_path): """Get and normalize the list of paths in AdditionalLibraryDirectories setting.""" config = self._TargetConfig(config) libpaths = self._Setting( (root, "AdditionalLibraryDirectories"), config, default=[] ) libpaths = [ os.path.normpath(gyp_to_build_path(self.ConvertVSMacros(p, config=config))) for p in libpaths ] return ['/LIBPATH:"' + p + '"' for p in libpaths] def GetLibFlags(self, config, gyp_to_build_path): """Returns the flags that need to be added to lib commands.""" config = self._TargetConfig(config) libflags = [] lib = self._GetWrapper( self, self.msvs_settings[config], "VCLibrarianTool", append=libflags ) libflags.extend( self._GetAdditionalLibraryDirectories( "VCLibrarianTool", config, gyp_to_build_path ) ) lib("LinkTimeCodeGeneration", map={"true": "/LTCG"}) lib( "TargetMachine", map={"1": "X86", "17": "X64", "3": "ARM"}, prefix="/MACHINE:", ) lib("AdditionalOptions") return libflags def GetDefFile(self, gyp_to_build_path): """Returns the .def file from sources, if any. Otherwise returns None.""" spec = self.spec if spec["type"] in ("shared_library", "loadable_module", "executable"): def_files = [ s for s in spec.get("sources", []) if s.lower().endswith(".def") ] if len(def_files) == 1: return gyp_to_build_path(def_files[0]) elif len(def_files) > 1: raise Exception("Multiple .def files") return None def _GetDefFileAsLdflags(self, ldflags, gyp_to_build_path): """.def files get implicitly converted to a ModuleDefinitionFile for the linker in the VS generator. Emulate that behaviour here.""" def_file = self.GetDefFile(gyp_to_build_path) if def_file: ldflags.append('/DEF:"%s"' % def_file) def GetPGDName(self, config, expand_special): """Gets the explicitly overridden pgd name for a target or returns None if it's not overridden.""" config = self._TargetConfig(config) output_file = self._Setting(("VCLinkerTool", "ProfileGuidedDatabase"), config) if output_file: output_file = expand_special( self.ConvertVSMacros(output_file, config=config) ) return output_file def GetLdflags( self, config, gyp_to_build_path, expand_special, manifest_base_name, output_name, is_executable, build_dir, ): """Returns the flags that need to be added to link commands, and the manifest files.""" config = self._TargetConfig(config) ldflags = [] ld = self._GetWrapper( self, self.msvs_settings[config], "VCLinkerTool", append=ldflags ) self._GetDefFileAsLdflags(ldflags, gyp_to_build_path) ld("GenerateDebugInformation", map={"true": "/DEBUG"}) # TODO: These 'map' values come from machineTypeOption enum, # and does not have an official value for ARM64 in VS2017 (yet). # It needs to verify the ARM64 value when machineTypeOption is updated. ld( "TargetMachine", map={"1": "X86", "17": "X64", "3": "ARM", "18": "ARM64"}, prefix="/MACHINE:", ) ldflags.extend( self._GetAdditionalLibraryDirectories( "VCLinkerTool", config, gyp_to_build_path ) ) ld("DelayLoadDLLs", prefix="/DELAYLOAD:") ld("TreatLinkerWarningAsErrors", prefix="/WX", map={"true": "", "false": ":NO"}) out = self.GetOutputName(config, expand_special) if out: ldflags.append("/OUT:" + out) pdb = self.GetPDBName(config, expand_special, output_name + ".pdb") if pdb: ldflags.append("/PDB:" + pdb) pgd = self.GetPGDName(config, expand_special) if pgd: ldflags.append("/PGD:" + pgd) map_file = self.GetMapFileName(config, expand_special) ld("GenerateMapFile", map={"true": "/MAP:" + map_file if map_file else "/MAP"}) ld("MapExports", map={"true": "/MAPINFO:EXPORTS"}) ld("AdditionalOptions", prefix="") minimum_required_version = self._Setting( ("VCLinkerTool", "MinimumRequiredVersion"), config, default="" ) if minimum_required_version: minimum_required_version = "," + minimum_required_version ld( "SubSystem", map={ "1": "CONSOLE%s" % minimum_required_version, "2": "WINDOWS%s" % minimum_required_version, }, prefix="/SUBSYSTEM:", ) stack_reserve_size = self._Setting( ("VCLinkerTool", "StackReserveSize"), config, default="" ) if stack_reserve_size: stack_commit_size = self._Setting( ("VCLinkerTool", "StackCommitSize"), config, default="" ) if stack_commit_size: stack_commit_size = "," + stack_commit_size ldflags.append(f"/STACK:{stack_reserve_size}{stack_commit_size}") ld("TerminalServerAware", map={"1": ":NO", "2": ""}, prefix="/TSAWARE") ld("LinkIncremental", map={"1": ":NO", "2": ""}, prefix="/INCREMENTAL") ld("BaseAddress", prefix="/BASE:") ld("FixedBaseAddress", map={"1": ":NO", "2": ""}, prefix="/FIXED") ld("RandomizedBaseAddress", map={"1": ":NO", "2": ""}, prefix="/DYNAMICBASE") ld("DataExecutionPrevention", map={"1": ":NO", "2": ""}, prefix="/NXCOMPAT") ld("OptimizeReferences", map={"1": "NOREF", "2": "REF"}, prefix="/OPT:") ld("ForceSymbolReferences", prefix="/INCLUDE:") ld("EnableCOMDATFolding", map={"1": "NOICF", "2": "ICF"}, prefix="/OPT:") ld( "LinkTimeCodeGeneration", map={"1": "", "2": ":PGINSTRUMENT", "3": ":PGOPTIMIZE", "4": ":PGUPDATE"}, prefix="/LTCG", ) ld("IgnoreDefaultLibraryNames", prefix="/NODEFAULTLIB:") ld("ResourceOnlyDLL", map={"true": "/NOENTRY"}) ld("EntryPointSymbol", prefix="/ENTRY:") ld("Profile", map={"true": "/PROFILE"}) ld("LargeAddressAware", map={"1": ":NO", "2": ""}, prefix="/LARGEADDRESSAWARE") # TODO(scottmg): This should sort of be somewhere else (not really a flag). ld("AdditionalDependencies", prefix="") safeseh_default = "true" if self.GetArch(config) == "x86" else None ld( "ImageHasSafeExceptionHandlers", map={"false": ":NO", "true": ""}, prefix="/SAFESEH", default=safeseh_default, ) # If the base address is not specifically controlled, DYNAMICBASE should # be on by default. if not any("DYNAMICBASE" in flag or flag == "/FIXED" for flag in ldflags): ldflags.append("/DYNAMICBASE") # If the NXCOMPAT flag has not been specified, default to on. Despite the # documentation that says this only defaults to on when the subsystem is # Vista or greater (which applies to the linker), the IDE defaults it on # unless it's explicitly off. if not any("NXCOMPAT" in flag for flag in ldflags): ldflags.append("/NXCOMPAT") have_def_file = any(flag.startswith("/DEF:") for flag in ldflags) ( manifest_flags, intermediate_manifest, manifest_files, ) = self._GetLdManifestFlags( config, manifest_base_name, gyp_to_build_path, is_executable and not have_def_file, build_dir, ) ldflags.extend(manifest_flags) return ldflags, intermediate_manifest, manifest_files def _GetLdManifestFlags( self, config, name, gyp_to_build_path, allow_isolation, build_dir ): """Returns a 3-tuple: - the set of flags that need to be added to the link to generate a default manifest - the intermediate manifest that the linker will generate that should be used to assert it doesn't add anything to the merged one. - the list of all the manifest files to be merged by the manifest tool and included into the link.""" generate_manifest = self._Setting( ("VCLinkerTool", "GenerateManifest"), config, default="true" ) if generate_manifest != "true": # This means not only that the linker should not generate the intermediate # manifest but also that the manifest tool should do nothing even when # additional manifests are specified. return ["/MANIFEST:NO"], [], [] output_name = name + ".intermediate.manifest" flags = [ "/MANIFEST", "/ManifestFile:" + output_name, ] # Instead of using the MANIFESTUAC flags, we generate a .manifest to # include into the list of manifests. This allows us to avoid the need to # do two passes during linking. The /MANIFEST flag and /ManifestFile are # still used, and the intermediate manifest is used to assert that the # final manifest we get from merging all the additional manifest files # (plus the one we generate here) isn't modified by merging the # intermediate into it. # Always NO, because we generate a manifest file that has what we want. flags.append("/MANIFESTUAC:NO") config = self._TargetConfig(config) enable_uac = self._Setting( ("VCLinkerTool", "EnableUAC"), config, default="true" ) manifest_files = [] generated_manifest_outer = ( "" "" "%s" ) if enable_uac == "true": execution_level = self._Setting( ("VCLinkerTool", "UACExecutionLevel"), config, default="0" ) execution_level_map = { "0": "asInvoker", "1": "highestAvailable", "2": "requireAdministrator", } ui_access = self._Setting( ("VCLinkerTool", "UACUIAccess"), config, default="false" ) inner = f""" """ # noqa: E501 else: inner = "" generated_manifest_contents = generated_manifest_outer % inner generated_name = name + ".generated.manifest" # Need to join with the build_dir here as we're writing it during # generation time, but we return the un-joined version because the build # will occur in that directory. We only write the file if the contents # have changed so that simply regenerating the project files doesn't # cause a relink. build_dir_generated_name = os.path.join(build_dir, generated_name) gyp.common.EnsureDirExists(build_dir_generated_name) f = gyp.common.WriteOnDiff(build_dir_generated_name) f.write(generated_manifest_contents) f.close() manifest_files = [generated_name] if allow_isolation: flags.append("/ALLOWISOLATION") manifest_files += self._GetAdditionalManifestFiles(config, gyp_to_build_path) return flags, output_name, manifest_files def _GetAdditionalManifestFiles(self, config, gyp_to_build_path): """Gets additional manifest files that are added to the default one generated by the linker.""" files = self._Setting( ("VCManifestTool", "AdditionalManifestFiles"), config, default=[] ) if isinstance(files, str): files = files.split(";") return [ os.path.normpath(gyp_to_build_path(self.ConvertVSMacros(f, config=config))) for f in files ] def IsUseLibraryDependencyInputs(self, config): """Returns whether the target should be linked via Use Library Dependency Inputs (using component .objs of a given .lib).""" config = self._TargetConfig(config) uldi = self._Setting(("VCLinkerTool", "UseLibraryDependencyInputs"), config) return uldi == "true" def IsEmbedManifest(self, config): """Returns whether manifest should be linked into binary.""" config = self._TargetConfig(config) embed = self._Setting( ("VCManifestTool", "EmbedManifest"), config, default="true" ) return embed == "true" def IsLinkIncremental(self, config): """Returns whether the target should be linked incrementally.""" config = self._TargetConfig(config) link_inc = self._Setting(("VCLinkerTool", "LinkIncremental"), config) return link_inc != "1" def GetRcflags(self, config, gyp_to_ninja_path): """Returns the flags that need to be added to invocations of the resource compiler.""" config = self._TargetConfig(config) rcflags = [] rc = self._GetWrapper( self, self.msvs_settings[config], "VCResourceCompilerTool", append=rcflags ) rc("AdditionalIncludeDirectories", map=gyp_to_ninja_path, prefix="/I") rcflags.append("/I" + gyp_to_ninja_path(".")) rc("PreprocessorDefinitions", prefix="/d") # /l arg must be in hex without leading '0x' rc("Culture", prefix="/l", map=lambda x: hex(int(x))[2:]) return rcflags def BuildCygwinBashCommandLine(self, args, path_to_base): """Build a command line that runs args via cygwin bash. We assume that all incoming paths are in Windows normpath'd form, so they need to be converted to posix style for the part of the command line that's passed to bash. We also have to do some Visual Studio macro emulation here because various rules use magic VS names for things. Also note that rules that contain ninja variables cannot be fixed here (for example ${source}), so the outer generator needs to make sure that the paths that are written out are in posix style, if the command line will be used here.""" cygwin_dir = os.path.normpath( os.path.join(path_to_base, self.msvs_cygwin_dirs[0]) ) cd = ("cd %s" % path_to_base).replace("\\", "/") args = [a.replace("\\", "/").replace('"', '\\"') for a in args] args = ["'%s'" % a.replace("'", "'\\''") for a in args] bash_cmd = " ".join(args) cmd = ( 'call "%s\\setup_env.bat" && set CYGWIN=nontsec && ' % cygwin_dir + f'bash -c "{cd} ; {bash_cmd}"' ) return cmd RuleShellFlags = collections.namedtuple("RuleShellFlags", ["cygwin", "quote"]) def GetRuleShellFlags(self, rule): """Return RuleShellFlags about how the given rule should be run. This includes whether it should run under cygwin (msvs_cygwin_shell), and whether the commands should be quoted (msvs_quote_cmd).""" # If the variable is unset, or set to 1 we use cygwin cygwin = int(rule.get("msvs_cygwin_shell", self.spec.get("msvs_cygwin_shell", 1))) != 0 # Default to quoting. There's only a few special instances where the # target command uses non-standard command line parsing and handle quotes # and quote escaping differently. quote_cmd = int(rule.get("msvs_quote_cmd", 1)) assert quote_cmd != 0 or cygwin != 1, \ "msvs_quote_cmd=0 only applicable for msvs_cygwin_shell=0" return MsvsSettings.RuleShellFlags(cygwin, quote_cmd) def _HasExplicitRuleForExtension(self, spec, extension): """Determine if there's an explicit rule for a particular extension.""" return any(rule["extension"] == extension for rule in spec.get("rules", [])) def _HasExplicitIdlActions(self, spec): """Determine if an action should not run midl for .idl files.""" return any( action.get("explicit_idl_action", 0) for action in spec.get("actions", []) ) def HasExplicitIdlRulesOrActions(self, spec): """Determine if there's an explicit rule or action for idl files. When there isn't we need to generate implicit rules to build MIDL .idl files.""" return self._HasExplicitRuleForExtension( spec, "idl" ) or self._HasExplicitIdlActions(spec) def HasExplicitAsmRules(self, spec): """Determine if there's an explicit rule for asm files. When there isn't we need to generate implicit rules to assemble .asm files.""" return self._HasExplicitRuleForExtension(spec, "asm") def GetIdlBuildData(self, source, config): """Determine the implicit outputs for an idl file. Returns output directory, outputs, and variables and flags that are required.""" config = self._TargetConfig(config) midl_get = self._GetWrapper(self, self.msvs_settings[config], "VCMIDLTool") def midl(name, default=None): return self.ConvertVSMacros(midl_get(name, default=default), config=config) tlb = midl("TypeLibraryName", default="${root}.tlb") header = midl("HeaderFileName", default="${root}.h") dlldata = midl("DLLDataFileName", default="dlldata.c") iid = midl("InterfaceIdentifierFileName", default="${root}_i.c") proxy = midl("ProxyFileName", default="${root}_p.c") # Note that .tlb is not included in the outputs as it is not always # generated depending on the content of the input idl file. outdir = midl("OutputDirectory", default="") output = [header, dlldata, iid, proxy] variables = [ ("tlb", tlb), ("h", header), ("dlldata", dlldata), ("iid", iid), ("proxy", proxy), ] # TODO(scottmg): Are there configuration settings to set these flags? target_platform = self.GetArch(config) if target_platform == "x86": target_platform = "win32" flags = ["/char", "signed", "/env", target_platform, "/Oicf"] return outdir, output, variables, flags def _LanguageMatchesForPch(source_ext, pch_source_ext): c_exts = (".c",) cc_exts = (".cc", ".cxx", ".cpp") return (source_ext in c_exts and pch_source_ext in c_exts) or ( source_ext in cc_exts and pch_source_ext in cc_exts ) class PrecompiledHeader: """Helper to generate dependencies and build rules to handle generation of precompiled headers. Interface matches the GCH handler in xcode_emulation.py. """ def __init__( self, settings, config, gyp_to_build_path, gyp_to_unique_output, obj_ext ): self.settings = settings self.config = config pch_source = self.settings.msvs_precompiled_source[self.config] self.pch_source = gyp_to_build_path(pch_source) filename, _ = os.path.splitext(pch_source) self.output_obj = gyp_to_unique_output(filename + obj_ext).lower() def _PchHeader(self): """Get the header that will appear in an #include line for all source files.""" return self.settings.msvs_precompiled_header[self.config] def GetObjDependencies(self, sources, objs, arch): """Given a list of sources files and the corresponding object files, returns a list of the pch files that should be depended upon. The additional wrapping in the return value is for interface compatibility with make.py on Mac, and xcode_emulation.py.""" assert arch is None if not self._PchHeader(): return [] pch_ext = os.path.splitext(self.pch_source)[1] for source in sources: if _LanguageMatchesForPch(os.path.splitext(source)[1], pch_ext): return [(None, None, self.output_obj)] return [] def GetPchBuildCommands(self, arch): """Not used on Windows as there are no additional build steps required (instead, existing steps are modified in GetFlagsModifications below).""" return [] def GetFlagsModifications( self, input, output, implicit, command, cflags_c, cflags_cc, expand_special ): """Get the modified cflags and implicit dependencies that should be used for the pch compilation step.""" if input == self.pch_source: pch_output = ["/Yc" + self._PchHeader()] if command == "cxx": return ( [("cflags_cc", map(expand_special, cflags_cc + pch_output))], self.output_obj, [], ) elif command == "cc": return ( [("cflags_c", map(expand_special, cflags_c + pch_output))], self.output_obj, [], ) return [], output, implicit vs_version = None def GetVSVersion(generator_flags): global vs_version if not vs_version: vs_version = gyp.MSVSVersion.SelectVisualStudioVersion( generator_flags.get("msvs_version", "auto"), allow_fallback=False ) return vs_version def _GetVsvarsSetupArgs(generator_flags, arch): vs = GetVSVersion(generator_flags) return vs.SetupScript() def ExpandMacros(string, expansions): """Expand $(Variable) per expansions dict. See MsvsSettings.GetVSMacroEnv for the canonical way to retrieve a suitable dict.""" if "$" in string: for old, new in expansions.items(): assert "$(" not in new, new string = string.replace(old, new) return string def _ExtractImportantEnvironment(output_of_set): """Extracts environment variables required for the toolchain to run from a textual dump output by the cmd.exe 'set' command.""" envvars_to_save = ( "goma_.*", # TODO(scottmg): This is ugly, but needed for goma. "include", "lib", "libpath", "path", "pathext", "systemroot", "temp", "tmp", ) env = {} # This occasionally happens and leads to misleading SYSTEMROOT error messages # if not caught here. if output_of_set.count("=") == 0: raise Exception("Invalid output_of_set. Value is:\n%s" % output_of_set) for line in output_of_set.splitlines(): for envvar in envvars_to_save: if re.match(envvar + "=", line.lower()): var, setting = line.split("=", 1) if envvar == "path": # Our own rules (for running gyp-win-tool) and other actions in # Chromium rely on python being in the path. Add the path to this # python here so that if it's not in the path when ninja is run # later, python will still be found. setting = os.path.dirname(sys.executable) + os.pathsep + setting env[var.upper()] = setting break for required in ("SYSTEMROOT", "TEMP", "TMP"): if required not in env: raise Exception( 'Environment variable "%s" ' "required to be set to valid path" % required ) return env def _FormatAsEnvironmentBlock(envvar_dict): """Format as an 'environment block' directly suitable for CreateProcess. Briefly this is a list of key=value\0, terminated by an additional \0. See CreateProcess documentation for more details.""" block = "" nul = "\0" for key, value in envvar_dict.items(): block += key + "=" + value + nul block += nul return block def _ExtractCLPath(output_of_where): """Gets the path to cl.exe based on the output of calling the environment setup batch file, followed by the equivalent of `where`.""" # Take the first line, as that's the first found in the PATH. for line in output_of_where.strip().splitlines(): if line.startswith("LOC:"): return line[len("LOC:") :].strip() def GenerateEnvironmentFiles( toplevel_build_dir, generator_flags, system_includes, open_out ): """It's not sufficient to have the absolute path to the compiler, linker, etc. on Windows, as those tools rely on .dlls being in the PATH. We also need to support both x86 and x64 compilers within the same build (to support msvs_target_platform hackery). Different architectures require a different compiler binary, and different supporting environment variables (INCLUDE, LIB, LIBPATH). So, we extract the environment here, wrap all invocations of compiler tools (cl, link, lib, rc, midl, etc.) via win_tool.py which sets up the environment, and then we do not prefix the compiler with an absolute path, instead preferring something like "cl.exe" in the rule which will then run whichever the environment setup has put in the path. When the following procedure to generate environment files does not meet your requirement (e.g. for custom toolchains), you can pass "-G ninja_use_custom_environment_files" to the gyp to suppress file generation and use custom environment files prepared by yourself.""" archs = ("x86", "x64") if generator_flags.get("ninja_use_custom_environment_files", 0): cl_paths = {} for arch in archs: cl_paths[arch] = "cl.exe" return cl_paths vs = GetVSVersion(generator_flags) cl_paths = {} for arch in archs: # Extract environment variables for subprocesses. args = vs.SetupScript(arch) args.extend(("&&", "set")) popen = subprocess.Popen( args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) variables = popen.communicate()[0].decode("utf-8") if popen.returncode != 0: raise Exception('"%s" failed with error %d' % (args, popen.returncode)) env = _ExtractImportantEnvironment(variables) # Inject system includes from gyp files into INCLUDE. if system_includes: system_includes = system_includes | OrderedSet( env.get("INCLUDE", "").split(";") ) env["INCLUDE"] = ";".join(system_includes) env_block = _FormatAsEnvironmentBlock(env) f = open_out(os.path.join(toplevel_build_dir, "environment." + arch), "w") f.write(env_block) f.close() # Find cl.exe location for this architecture. args = vs.SetupScript(arch) args.extend( ("&&", "for", "%i", "in", "(cl.exe)", "do", "@echo", "LOC:%~$PATH:i") ) popen = subprocess.Popen(args, shell=True, stdout=subprocess.PIPE) output = popen.communicate()[0].decode("utf-8") cl_paths[arch] = _ExtractCLPath(output) return cl_paths def VerifyMissingSources(sources, build_dir, generator_flags, gyp_to_ninja): """Emulate behavior of msvs_error_on_missing_sources present in the msvs generator: Check that all regular source files, i.e. not created at run time, exist on disk. Missing files cause needless recompilation when building via VS, and we want this check to match for people/bots that build using ninja, so they're not surprised when the VS build fails.""" if int(generator_flags.get("msvs_error_on_missing_sources", 0)): no_specials = filter(lambda x: "$" not in x, sources) relative = [os.path.join(build_dir, gyp_to_ninja(s)) for s in no_specials] missing = [x for x in relative if not os.path.exists(x)] if missing: # They'll look like out\Release\..\..\stuff\things.cc, so normalize the # path for a slightly less crazy looking output. cleaned_up = [os.path.normpath(x) for x in missing] raise Exception("Missing input files:\n%s" % "\n".join(cleaned_up)) # Sets some values in default_variables, which are required for many # generators, run on Windows. def CalculateCommonVariables(default_variables, params): generator_flags = params.get("generator_flags", {}) # Set a variable so conditions can be based on msvs_version. msvs_version = gyp.msvs_emulation.GetVSVersion(generator_flags) default_variables["MSVS_VERSION"] = msvs_version.ShortName() # To determine processor word size on Windows, in addition to checking # PROCESSOR_ARCHITECTURE (which reflects the word size of the current # process), it is also necessary to check PROCESSOR_ARCHITEW6432 (which # contains the actual word size of the system when running thru WOW64). if "64" in os.environ.get("PROCESSOR_ARCHITECTURE", "") or "64" in os.environ.get( "PROCESSOR_ARCHITEW6432", "" ): default_variables["MSVS_OS_BITS"] = 64 else: default_variables["MSVS_OS_BITS"] = 32 PK ~\3G(node-gyp/gyp/pylib/gyp/xcodeproj_file.pynu[# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Xcode project file generator. This module is both an Xcode project file generator and a documentation of the Xcode project file format. Knowledge of the project file format was gained based on extensive experience with Xcode, and by making changes to projects in Xcode.app and observing the resultant changes in the associated project files. XCODE PROJECT FILES The generator targets the file format as written by Xcode 3.2 (specifically, 3.2.6), but past experience has taught that the format has not changed significantly in the past several years, and future versions of Xcode are able to read older project files. Xcode project files are "bundled": the project "file" from an end-user's perspective is actually a directory with an ".xcodeproj" extension. The project file from this module's perspective is actually a file inside this directory, always named "project.pbxproj". This file contains a complete description of the project and is all that is needed to use the xcodeproj. Other files contained in the xcodeproj directory are simply used to store per-user settings, such as the state of various UI elements in the Xcode application. The project.pbxproj file is a property list, stored in a format almost identical to the NeXTstep property list format. The file is able to carry Unicode data, and is encoded in UTF-8. The root element in the property list is a dictionary that contains several properties of minimal interest, and two properties of immense interest. The most important property is a dictionary named "objects". The entire structure of the project is represented by the children of this property. The objects dictionary is keyed by unique 96-bit values represented by 24 uppercase hexadecimal characters. Each value in the objects dictionary is itself a dictionary, describing an individual object. Each object in the dictionary is a member of a class, which is identified by the "isa" property of each object. A variety of classes are represented in a project file. Objects can refer to other objects by ID, using the 24-character hexadecimal object key. A project's objects form a tree, with a root object of class PBXProject at the root. As an example, the PBXProject object serves as parent to an XCConfigurationList object defining the build configurations used in the project, a PBXGroup object serving as a container for all files referenced in the project, and a list of target objects, each of which defines a target in the project. There are several different types of target object, such as PBXNativeTarget and PBXAggregateTarget. In this module, this relationship is expressed by having each target type derive from an abstract base named XCTarget. The project.pbxproj file's root dictionary also contains a property, sibling to the "objects" dictionary, named "rootObject". The value of rootObject is a 24-character object key referring to the root PBXProject object in the objects dictionary. In Xcode, every file used as input to a target or produced as a final product of a target must appear somewhere in the hierarchy rooted at the PBXGroup object referenced by the PBXProject's mainGroup property. A PBXGroup is generally represented as a folder in the Xcode application. PBXGroups can contain other PBXGroups as well as PBXFileReferences, which are pointers to actual files. Each XCTarget contains a list of build phases, represented in this module by the abstract base XCBuildPhase. Examples of concrete XCBuildPhase derivations are PBXSourcesBuildPhase and PBXFrameworksBuildPhase, which correspond to the "Compile Sources" and "Link Binary With Libraries" phases displayed in the Xcode application. Files used as input to these phases (for example, source files in the former case and libraries and frameworks in the latter) are represented by PBXBuildFile objects, referenced by elements of "files" lists in XCTarget objects. Each PBXBuildFile object refers to a PBXBuildFile object as a "weak" reference: it does not "own" the PBXBuildFile, which is owned by the root object's mainGroup or a descendant group. In most cases, the layer of indirection between an XCBuildPhase and a PBXFileReference via a PBXBuildFile appears extraneous, but there's actually one reason for this: file-specific compiler flags are added to the PBXBuildFile object so as to allow a single file to be a member of multiple targets while having distinct compiler flags for each. These flags can be modified in the Xcode applciation in the "Build" tab of a File Info window. When a project is open in the Xcode application, Xcode will rewrite it. As such, this module is careful to adhere to the formatting used by Xcode, to avoid insignificant changes appearing in the file when it is used in the Xcode application. This will keep version control repositories happy, and makes it possible to compare a project file used in Xcode to one generated by this module to determine if any significant changes were made in the application. Xcode has its own way of assigning 24-character identifiers to each object, which is not duplicated here. Because the identifier only is only generated once, when an object is created, and is then left unchanged, there is no need to attempt to duplicate Xcode's behavior in this area. The generator is free to select any identifier, even at random, to refer to the objects it creates, and Xcode will retain those identifiers and use them when subsequently rewriting the project file. However, the generator would choose new random identifiers each time the project files are generated, leading to difficulties comparing "used" project files to "pristine" ones produced by this module, and causing the appearance of changes as every object identifier is changed when updated projects are checked in to a version control repository. To mitigate this problem, this module chooses identifiers in a more deterministic way, by hashing a description of each object as well as its parent and ancestor objects. This strategy should result in minimal "shift" in IDs as successive generations of project files are produced. THIS MODULE This module introduces several classes, all derived from the XCObject class. Nearly all of the "brains" are built into the XCObject class, which understands how to create and modify objects, maintain the proper tree structure, compute identifiers, and print objects. For the most part, classes derived from XCObject need only provide a _schema class object, a dictionary that expresses what properties objects of the class may contain. Given this structure, it's possible to build a minimal project file by creating objects of the appropriate types and making the proper connections: config_list = XCConfigurationList() group = PBXGroup() project = PBXProject({'buildConfigurationList': config_list, 'mainGroup': group}) With the project object set up, it can be added to an XCProjectFile object. XCProjectFile is a pseudo-class in the sense that it is a concrete XCObject subclass that does not actually correspond to a class type found in a project file. Rather, it is used to represent the project file's root dictionary. Printing an XCProjectFile will print the entire project file, including the full "objects" dictionary. project_file = XCProjectFile({'rootObject': project}) project_file.ComputeIDs() project_file.Print() Xcode project files are always encoded in UTF-8. This module will accept strings of either the str class or the unicode class. Strings of class str are assumed to already be encoded in UTF-8. Obviously, if you're just using ASCII, you won't encounter difficulties because ASCII is a UTF-8 subset. Strings of class unicode are handled properly and encoded in UTF-8 when a project file is output. """ import gyp.common from functools import cmp_to_key import hashlib from operator import attrgetter import posixpath import re import struct import sys def cmp(x, y): return (x > y) - (x < y) # See XCObject._EncodeString. This pattern is used to determine when a string # can be printed unquoted. Strings that match this pattern may be printed # unquoted. Strings that do not match must be quoted and may be further # transformed to be properly encoded. Note that this expression matches the # characters listed with "+", for 1 or more occurrences: if a string is empty, # it must not match this pattern, because it needs to be encoded as "". _unquoted = re.compile("^[A-Za-z0-9$./_]+$") # Strings that match this pattern are quoted regardless of what _unquoted says. # Oddly, Xcode will quote any string with a run of three or more underscores. _quoted = re.compile("___") # This pattern should match any character that needs to be escaped by # XCObject._EncodeString. See that function. _escaped = re.compile('[\\\\"]|[\x00-\x1f]') # Used by SourceTreeAndPathFromPath _path_leading_variable = re.compile(r"^\$\((.*?)\)(/(.*))?$") def SourceTreeAndPathFromPath(input_path): """Given input_path, returns a tuple with sourceTree and path values. Examples: input_path (source_tree, output_path) '$(VAR)/path' ('VAR', 'path') '$(VAR)' ('VAR', None) 'path' (None, 'path') """ source_group_match = _path_leading_variable.match(input_path) if source_group_match: source_tree = source_group_match.group(1) output_path = source_group_match.group(3) # This may be None. else: source_tree = None output_path = input_path return (source_tree, output_path) def ConvertVariablesToShellSyntax(input_string): return re.sub(r"\$\((.*?)\)", "${\\1}", input_string) class XCObject: """The abstract base of all class types used in Xcode project files. Class variables: _schema: A dictionary defining the properties of this class. The keys to _schema are string property keys as used in project files. Values are a list of four or five elements: [ is_list, property_type, is_strong, is_required, default ] is_list: True if the property described is a list, as opposed to a single element. property_type: The type to use as the value of the property, or if is_list is True, the type to use for each element of the value's list. property_type must be an XCObject subclass, or one of the built-in types str, int, or dict. is_strong: If property_type is an XCObject subclass, is_strong is True to assert that this class "owns," or serves as parent, to the property value (or, if is_list is True, values). is_strong must be False if property_type is not an XCObject subclass. is_required: True if the property is required for the class. Note that is_required being True does not preclude an empty string ("", in the case of property_type str) or list ([], in the case of is_list True) from being set for the property. default: Optional. If is_required is True, default may be set to provide a default value for objects that do not supply their own value. If is_required is True and default is not provided, users of the class must supply their own value for the property. Note that although the values of the array are expressed in boolean terms, subclasses provide values as integers to conserve horizontal space. _should_print_single_line: False in XCObject. Subclasses whose objects should be written to the project file in the alternate single-line format, such as PBXFileReference and PBXBuildFile, should set this to True. _encode_transforms: Used by _EncodeString to encode unprintable characters. The index into this list is the ordinal of the character to transform; each value is a string used to represent the character in the output. XCObject provides an _encode_transforms list suitable for most XCObject subclasses. _alternate_encode_transforms: Provided for subclasses that wish to use the alternate encoding rules. Xcode seems to use these rules when printing objects in single-line format. Subclasses that desire this behavior should set _encode_transforms to _alternate_encode_transforms. _hashables: A list of XCObject subclasses that can be hashed by ComputeIDs to construct this object's ID. Most classes that need custom hashing behavior should do it by overriding Hashables, but in some cases an object's parent may wish to push a hashable value into its child, and it can do so by appending to _hashables. Attributes: id: The object's identifier, a 24-character uppercase hexadecimal string. Usually, objects being created should not set id until the entire project file structure is built. At that point, UpdateIDs() should be called on the root object to assign deterministic values for id to each object in the tree. parent: The object's parent. This is set by a parent XCObject when a child object is added to it. _properties: The object's property dictionary. An object's properties are described by its class' _schema variable. """ _schema = {} _should_print_single_line = False # See _EncodeString. _encode_transforms = [] i = 0 while i < ord(" "): _encode_transforms.append("\\U%04x" % i) i = i + 1 _encode_transforms[7] = "\\a" _encode_transforms[8] = "\\b" _encode_transforms[9] = "\\t" _encode_transforms[10] = "\\n" _encode_transforms[11] = "\\v" _encode_transforms[12] = "\\f" _encode_transforms[13] = "\\n" _alternate_encode_transforms = list(_encode_transforms) _alternate_encode_transforms[9] = chr(9) _alternate_encode_transforms[10] = chr(10) _alternate_encode_transforms[11] = chr(11) def __init__(self, properties=None, id=None, parent=None): self.id = id self.parent = parent self._properties = {} self._hashables = [] self._SetDefaultsFromSchema() self.UpdateProperties(properties) def __repr__(self): try: name = self.Name() except NotImplementedError: return f"<{self.__class__.__name__} at 0x{id(self):x}>" return f"<{self.__class__.__name__} {name!r} at 0x{id(self):x}>" def Copy(self): """Make a copy of this object. The new object will have its own copy of lists and dicts. Any XCObject objects owned by this object (marked "strong") will be copied in the new object, even those found in lists. If this object has any weak references to other XCObjects, the same references are added to the new object without making a copy. """ that = self.__class__(id=self.id, parent=self.parent) for key, value in self._properties.items(): is_strong = self._schema[key][2] if isinstance(value, XCObject): if is_strong: new_value = value.Copy() new_value.parent = that that._properties[key] = new_value else: that._properties[key] = value elif isinstance(value, (str, int)): that._properties[key] = value elif isinstance(value, list): if is_strong: # If is_strong is True, each element is an XCObject, so it's safe to # call Copy. that._properties[key] = [] for item in value: new_item = item.Copy() new_item.parent = that that._properties[key].append(new_item) else: that._properties[key] = value[:] elif isinstance(value, dict): # dicts are never strong. if is_strong: raise TypeError( "Strong dict for key " + key + " in " + self.__class__.__name__ ) else: that._properties[key] = value.copy() else: raise TypeError( "Unexpected type " + value.__class__.__name__ + " for key " + key + " in " + self.__class__.__name__ ) return that def Name(self): """Return the name corresponding to an object. Not all objects necessarily need to be nameable, and not all that do have a "name" property. Override as needed. """ # If the schema indicates that "name" is required, try to access the # property even if it doesn't exist. This will result in a KeyError # being raised for the property that should be present, which seems more # appropriate than NotImplementedError in this case. if "name" in self._properties or ( "name" in self._schema and self._schema["name"][3] ): return self._properties["name"] raise NotImplementedError(self.__class__.__name__ + " must implement Name") def Comment(self): """Return a comment string for the object. Most objects just use their name as the comment, but PBXProject uses different values. The returned comment is not escaped and does not have any comment marker strings applied to it. """ return self.Name() def Hashables(self): hashables = [self.__class__.__name__] name = self.Name() if name is not None: hashables.append(name) hashables.extend(self._hashables) return hashables def HashablesForChild(self): return None def ComputeIDs(self, recursive=True, overwrite=True, seed_hash=None): """Set "id" properties deterministically. An object's "id" property is set based on a hash of its class type and name, as well as the class type and name of all ancestor objects. As such, it is only advisable to call ComputeIDs once an entire project file tree is built. If recursive is True, recurse into all descendant objects and update their hashes. If overwrite is True, any existing value set in the "id" property will be replaced. """ def _HashUpdate(hash, data): """Update hash with data's length and contents. If the hash were updated only with the value of data, it would be possible for clowns to induce collisions by manipulating the names of their objects. By adding the length, it's exceedingly less likely that ID collisions will be encountered, intentionally or not. """ hash.update(struct.pack(">i", len(data))) if isinstance(data, str): data = data.encode("utf-8") hash.update(data) if seed_hash is None: seed_hash = hashlib.sha1() hash = seed_hash.copy() hashables = self.Hashables() assert len(hashables) > 0 for hashable in hashables: _HashUpdate(hash, hashable) if recursive: hashables_for_child = self.HashablesForChild() if hashables_for_child is None: child_hash = hash else: assert len(hashables_for_child) > 0 child_hash = seed_hash.copy() for hashable in hashables_for_child: _HashUpdate(child_hash, hashable) for child in self.Children(): child.ComputeIDs(recursive, overwrite, child_hash) if overwrite or self.id is None: # Xcode IDs are only 96 bits (24 hex characters), but a SHA-1 digest is # is 160 bits. Instead of throwing out 64 bits of the digest, xor them # into the portion that gets used. assert hash.digest_size % 4 == 0 digest_int_count = hash.digest_size // 4 digest_ints = struct.unpack(">" + "I" * digest_int_count, hash.digest()) id_ints = [0, 0, 0] for index in range(0, digest_int_count): id_ints[index % 3] ^= digest_ints[index] self.id = "%08X%08X%08X" % tuple(id_ints) def EnsureNoIDCollisions(self): """Verifies that no two objects have the same ID. Checks all descendants. """ ids = {} descendants = self.Descendants() for descendant in descendants: if descendant.id in ids: other = ids[descendant.id] raise KeyError( 'Duplicate ID %s, objects "%s" and "%s" in "%s"' % ( descendant.id, str(descendant._properties), str(other._properties), self._properties["rootObject"].Name(), ) ) ids[descendant.id] = descendant def Children(self): """Returns a list of all of this object's owned (strong) children.""" children = [] for property, attributes in self._schema.items(): (is_list, property_type, is_strong) = attributes[0:3] if is_strong and property in self._properties: if not is_list: children.append(self._properties[property]) else: children.extend(self._properties[property]) return children def Descendants(self): """Returns a list of all of this object's descendants, including this object. """ children = self.Children() descendants = [self] for child in children: descendants.extend(child.Descendants()) return descendants def PBXProjectAncestor(self): # The base case for recursion is defined at PBXProject.PBXProjectAncestor. if self.parent: return self.parent.PBXProjectAncestor() return None def _EncodeComment(self, comment): """Encodes a comment to be placed in the project file output, mimicking Xcode behavior. """ # This mimics Xcode behavior by wrapping the comment in "/*" and "*/". If # the string already contains a "*/", it is turned into "(*)/". This keeps # the file writer from outputting something that would be treated as the # end of a comment in the middle of something intended to be entirely a # comment. return "/* " + comment.replace("*/", "(*)/") + " */" def _EncodeTransform(self, match): # This function works closely with _EncodeString. It will only be called # by re.sub with match.group(0) containing a character matched by the # the _escaped expression. char = match.group(0) # Backslashes (\) and quotation marks (") are always replaced with a # backslash-escaped version of the same. Everything else gets its # replacement from the class' _encode_transforms array. if char == "\\": return "\\\\" if char == '"': return '\\"' return self._encode_transforms[ord(char)] def _EncodeString(self, value): """Encodes a string to be placed in the project file output, mimicking Xcode behavior. """ # Use quotation marks when any character outside of the range A-Z, a-z, 0-9, # $ (dollar sign), . (period), and _ (underscore) is present. Also use # quotation marks to represent empty strings. # # Escape " (double-quote) and \ (backslash) by preceding them with a # backslash. # # Some characters below the printable ASCII range are encoded specially: # 7 ^G BEL is encoded as "\a" # 8 ^H BS is encoded as "\b" # 11 ^K VT is encoded as "\v" # 12 ^L NP is encoded as "\f" # 127 ^? DEL is passed through as-is without escaping # - In PBXFileReference and PBXBuildFile objects: # 9 ^I HT is passed through as-is without escaping # 10 ^J NL is passed through as-is without escaping # 13 ^M CR is passed through as-is without escaping # - In other objects: # 9 ^I HT is encoded as "\t" # 10 ^J NL is encoded as "\n" # 13 ^M CR is encoded as "\n" rendering it indistinguishable from # 10 ^J NL # All other characters within the ASCII control character range (0 through # 31 inclusive) are encoded as "\U001f" referring to the Unicode code point # in hexadecimal. For example, character 14 (^N SO) is encoded as "\U000e". # Characters above the ASCII range are passed through to the output encoded # as UTF-8 without any escaping. These mappings are contained in the # class' _encode_transforms list. if _unquoted.search(value) and not _quoted.search(value): return value return '"' + _escaped.sub(self._EncodeTransform, value) + '"' def _XCPrint(self, file, tabs, line): file.write("\t" * tabs + line) def _XCPrintableValue(self, tabs, value, flatten_list=False): """Returns a representation of value that may be printed in a project file, mimicking Xcode's behavior. _XCPrintableValue can handle str and int values, XCObjects (which are made printable by returning their id property), and list and dict objects composed of any of the above types. When printing a list or dict, and _should_print_single_line is False, the tabs parameter is used to determine how much to indent the lines corresponding to the items in the list or dict. If flatten_list is True, single-element lists will be transformed into strings. """ printable = "" comment = None if self._should_print_single_line: sep = " " element_tabs = "" end_tabs = "" else: sep = "\n" element_tabs = "\t" * (tabs + 1) end_tabs = "\t" * tabs if isinstance(value, XCObject): printable += value.id comment = value.Comment() elif isinstance(value, str): printable += self._EncodeString(value) elif isinstance(value, str): printable += self._EncodeString(value.encode("utf-8")) elif isinstance(value, int): printable += str(value) elif isinstance(value, list): if flatten_list and len(value) <= 1: if len(value) == 0: printable += self._EncodeString("") else: printable += self._EncodeString(value[0]) else: printable = "(" + sep for item in value: printable += ( element_tabs + self._XCPrintableValue(tabs + 1, item, flatten_list) + "," + sep ) printable += end_tabs + ")" elif isinstance(value, dict): printable = "{" + sep for item_key, item_value in sorted(value.items()): printable += ( element_tabs + self._XCPrintableValue(tabs + 1, item_key, flatten_list) + " = " + self._XCPrintableValue(tabs + 1, item_value, flatten_list) + ";" + sep ) printable += end_tabs + "}" else: raise TypeError("Can't make " + value.__class__.__name__ + " printable") if comment: printable += " " + self._EncodeComment(comment) return printable def _XCKVPrint(self, file, tabs, key, value): """Prints a key and value, members of an XCObject's _properties dictionary, to file. tabs is an int identifying the indentation level. If the class' _should_print_single_line variable is True, tabs is ignored and the key-value pair will be followed by a space insead of a newline. """ if self._should_print_single_line: printable = "" after_kv = " " else: printable = "\t" * tabs after_kv = "\n" # Xcode usually prints remoteGlobalIDString values in PBXContainerItemProxy # objects without comments. Sometimes it prints them with comments, but # the majority of the time, it doesn't. To avoid unnecessary changes to # the project file after Xcode opens it, don't write comments for # remoteGlobalIDString. This is a sucky hack and it would certainly be # cleaner to extend the schema to indicate whether or not a comment should # be printed, but since this is the only case where the problem occurs and # Xcode itself can't seem to make up its mind, the hack will suffice. # # Also see PBXContainerItemProxy._schema['remoteGlobalIDString']. if key == "remoteGlobalIDString" and isinstance(self, PBXContainerItemProxy): value_to_print = value.id else: value_to_print = value # PBXBuildFile's settings property is represented in the output as a dict, # but a hack here has it represented as a string. Arrange to strip off the # quotes so that it shows up in the output as expected. if key == "settings" and isinstance(self, PBXBuildFile): strip_value_quotes = True else: strip_value_quotes = False # In another one-off, let's set flatten_list on buildSettings properties # of XCBuildConfiguration objects, because that's how Xcode treats them. if key == "buildSettings" and isinstance(self, XCBuildConfiguration): flatten_list = True else: flatten_list = False try: printable_key = self._XCPrintableValue(tabs, key, flatten_list) printable_value = self._XCPrintableValue(tabs, value_to_print, flatten_list) if ( strip_value_quotes and len(printable_value) > 1 and printable_value[0] == '"' and printable_value[-1] == '"' ): printable_value = printable_value[1:-1] printable += printable_key + " = " + printable_value + ";" + after_kv except TypeError as e: gyp.common.ExceptionAppend(e, 'while printing key "%s"' % key) raise self._XCPrint(file, 0, printable) def Print(self, file=sys.stdout): """Prints a reprentation of this object to file, adhering to Xcode output formatting. """ self.VerifyHasRequiredProperties() if self._should_print_single_line: # When printing an object in a single line, Xcode doesn't put any space # between the beginning of a dictionary (or presumably a list) and the # first contained item, so you wind up with snippets like # ...CDEF = {isa = PBXFileReference; fileRef = 0123... # If it were me, I would have put a space in there after the opening # curly, but I guess this is just another one of those inconsistencies # between how Xcode prints PBXFileReference and PBXBuildFile objects as # compared to other objects. Mimic Xcode's behavior here by using an # empty string for sep. sep = "" end_tabs = 0 else: sep = "\n" end_tabs = 2 # Start the object. For example, '\t\tPBXProject = {\n'. self._XCPrint(file, 2, self._XCPrintableValue(2, self) + " = {" + sep) # "isa" isn't in the _properties dictionary, it's an intrinsic property # of the class which the object belongs to. Xcode always outputs "isa" # as the first element of an object dictionary. self._XCKVPrint(file, 3, "isa", self.__class__.__name__) # The remaining elements of an object dictionary are sorted alphabetically. for property, value in sorted(self._properties.items()): self._XCKVPrint(file, 3, property, value) # End the object. self._XCPrint(file, end_tabs, "};\n") def UpdateProperties(self, properties, do_copy=False): """Merge the supplied properties into the _properties dictionary. The input properties must adhere to the class schema or a KeyError or TypeError exception will be raised. If adding an object of an XCObject subclass and the schema indicates a strong relationship, the object's parent will be set to this object. If do_copy is True, then lists, dicts, strong-owned XCObjects, and strong-owned XCObjects in lists will be copied instead of having their references added. """ if properties is None: return for property, value in properties.items(): # Make sure the property is in the schema. if property not in self._schema: raise KeyError(property + " not in " + self.__class__.__name__) # Make sure the property conforms to the schema. (is_list, property_type, is_strong) = self._schema[property][0:3] if is_list: if value.__class__ != list: raise TypeError( property + " of " + self.__class__.__name__ + " must be list, not " + value.__class__.__name__ ) for item in value: if not isinstance(item, property_type) and not ( isinstance(item, str) and property_type == str ): # Accept unicode where str is specified. str is treated as # UTF-8-encoded. raise TypeError( "item of " + property + " of " + self.__class__.__name__ + " must be " + property_type.__name__ + ", not " + item.__class__.__name__ ) elif not isinstance(value, property_type) and not ( isinstance(value, str) and property_type == str ): # Accept unicode where str is specified. str is treated as # UTF-8-encoded. raise TypeError( property + " of " + self.__class__.__name__ + " must be " + property_type.__name__ + ", not " + value.__class__.__name__ ) # Checks passed, perform the assignment. if do_copy: if isinstance(value, XCObject): if is_strong: self._properties[property] = value.Copy() else: self._properties[property] = value elif isinstance(value, (str, int)): self._properties[property] = value elif isinstance(value, list): if is_strong: # If is_strong is True, each element is an XCObject, # so it's safe to call Copy. self._properties[property] = [] for item in value: self._properties[property].append(item.Copy()) else: self._properties[property] = value[:] elif isinstance(value, dict): self._properties[property] = value.copy() else: raise TypeError( "Don't know how to copy a " + value.__class__.__name__ + " object for " + property + " in " + self.__class__.__name__ ) else: self._properties[property] = value # Set up the child's back-reference to this object. Don't use |value| # any more because it may not be right if do_copy is true. if is_strong: if not is_list: self._properties[property].parent = self else: for item in self._properties[property]: item.parent = self def HasProperty(self, key): return key in self._properties def GetProperty(self, key): return self._properties[key] def SetProperty(self, key, value): self.UpdateProperties({key: value}) def DelProperty(self, key): if key in self._properties: del self._properties[key] def AppendProperty(self, key, value): # TODO(mark): Support ExtendProperty too (and make this call that)? # Schema validation. if key not in self._schema: raise KeyError(key + " not in " + self.__class__.__name__) (is_list, property_type, is_strong) = self._schema[key][0:3] if not is_list: raise TypeError(key + " of " + self.__class__.__name__ + " must be list") if not isinstance(value, property_type): raise TypeError( "item of " + key + " of " + self.__class__.__name__ + " must be " + property_type.__name__ + ", not " + value.__class__.__name__ ) # If the property doesn't exist yet, create a new empty list to receive the # item. self._properties[key] = self._properties.get(key, []) # Set up the ownership link. if is_strong: value.parent = self # Store the item. self._properties[key].append(value) def VerifyHasRequiredProperties(self): """Ensure that all properties identified as required by the schema are set. """ # TODO(mark): A stronger verification mechanism is needed. Some # subclasses need to perform validation beyond what the schema can enforce. for property, attributes in self._schema.items(): (is_list, property_type, is_strong, is_required) = attributes[0:4] if is_required and property not in self._properties: raise KeyError(self.__class__.__name__ + " requires " + property) def _SetDefaultsFromSchema(self): """Assign object default values according to the schema. This will not overwrite properties that have already been set.""" defaults = {} for property, attributes in self._schema.items(): (is_list, property_type, is_strong, is_required) = attributes[0:4] if ( is_required and len(attributes) >= 5 and property not in self._properties ): default = attributes[4] defaults[property] = default if len(defaults) > 0: # Use do_copy=True so that each new object gets its own copy of strong # objects, lists, and dicts. self.UpdateProperties(defaults, do_copy=True) class XCHierarchicalElement(XCObject): """Abstract base for PBXGroup and PBXFileReference. Not represented in a project file.""" # TODO(mark): Do name and path belong here? Probably so. # If path is set and name is not, name may have a default value. Name will # be set to the basename of path, if the basename of path is different from # the full value of path. If path is already just a leaf name, name will # not be set. _schema = XCObject._schema.copy() _schema.update( { "comments": [0, str, 0, 0], "fileEncoding": [0, str, 0, 0], "includeInIndex": [0, int, 0, 0], "indentWidth": [0, int, 0, 0], "lineEnding": [0, int, 0, 0], "sourceTree": [0, str, 0, 1, ""], "tabWidth": [0, int, 0, 0], "usesTabs": [0, int, 0, 0], "wrapsLines": [0, int, 0, 0], } ) def __init__(self, properties=None, id=None, parent=None): # super XCObject.__init__(self, properties, id, parent) if "path" in self._properties and "name" not in self._properties: path = self._properties["path"] name = posixpath.basename(path) if name not in ("", path): self.SetProperty("name", name) if "path" in self._properties and ( "sourceTree" not in self._properties or self._properties["sourceTree"] == "" ): # If the pathname begins with an Xcode variable like "$(SDKROOT)/", take # the variable out and make the path be relative to that variable by # assigning the variable name as the sourceTree. (source_tree, path) = SourceTreeAndPathFromPath(self._properties["path"]) if source_tree is not None: self._properties["sourceTree"] = source_tree if path is not None: self._properties["path"] = path if ( source_tree is not None and path is None and "name" not in self._properties ): # The path was of the form "$(SDKROOT)" with no path following it. # This object is now relative to that variable, so it has no path # attribute of its own. It does, however, keep a name. del self._properties["path"] self._properties["name"] = source_tree def Name(self): if "name" in self._properties: return self._properties["name"] elif "path" in self._properties: return self._properties["path"] else: # This happens in the case of the root PBXGroup. return None def Hashables(self): """Custom hashables for XCHierarchicalElements. XCHierarchicalElements are special. Generally, their hashes shouldn't change if the paths don't change. The normal XCObject implementation of Hashables adds a hashable for each object, which means that if the hierarchical structure changes (possibly due to changes caused when TakeOverOnlyChild runs and encounters slight changes in the hierarchy), the hashes will change. For example, if a project file initially contains a/b/f1 and a/b becomes collapsed into a/b, f1 will have a single parent a/b. If someone later adds a/f2 to the project file, a/b can no longer be collapsed, and f1 winds up with parent b and grandparent a. That would be sufficient to change f1's hash. To counteract this problem, hashables for all XCHierarchicalElements except for the main group (which has neither a name nor a path) are taken to be just the set of path components. Because hashables are inherited from parents, this provides assurance that a/b/f1 has the same set of hashables whether its parent is b or a/b. The main group is a special case. As it is permitted to have no name or path, it is permitted to use the standard XCObject hash mechanism. This is not considered a problem because there can be only one main group. """ if self == self.PBXProjectAncestor()._properties["mainGroup"]: # super return XCObject.Hashables(self) hashables = [] # Put the name in first, ensuring that if TakeOverOnlyChild collapses # children into a top-level group like "Source", the name always goes # into the list of hashables without interfering with path components. if "name" in self._properties: # Make it less likely for people to manipulate hashes by following the # pattern of always pushing an object type value onto the list first. hashables.append(self.__class__.__name__ + ".name") hashables.append(self._properties["name"]) # NOTE: This still has the problem that if an absolute path is encountered, # including paths with a sourceTree, they'll still inherit their parents' # hashables, even though the paths aren't relative to their parents. This # is not expected to be much of a problem in practice. path = self.PathFromSourceTreeAndPath() if path is not None: components = path.split(posixpath.sep) for component in components: hashables.append(self.__class__.__name__ + ".path") hashables.append(component) hashables.extend(self._hashables) return hashables def Compare(self, other): # Allow comparison of these types. PBXGroup has the highest sort rank; # PBXVariantGroup is treated as equal to PBXFileReference. valid_class_types = { PBXFileReference: "file", PBXGroup: "group", PBXVariantGroup: "file", } self_type = valid_class_types[self.__class__] other_type = valid_class_types[other.__class__] if self_type == other_type: # If the two objects are of the same sort rank, compare their names. return cmp(self.Name(), other.Name()) # Otherwise, sort groups before everything else. if self_type == "group": return -1 return 1 def CompareRootGroup(self, other): # This function should be used only to compare direct children of the # containing PBXProject's mainGroup. These groups should appear in the # listed order. # TODO(mark): "Build" is used by gyp.generator.xcode, perhaps the # generator should have a way of influencing this list rather than having # to hardcode for the generator here. order = [ "Source", "Intermediates", "Projects", "Frameworks", "Products", "Build", ] # If the groups aren't in the listed order, do a name comparison. # Otherwise, groups in the listed order should come before those that # aren't. self_name = self.Name() other_name = other.Name() self_in = isinstance(self, PBXGroup) and self_name in order other_in = isinstance(self, PBXGroup) and other_name in order if not self_in and not other_in: return self.Compare(other) if self_name in order and other_name not in order: return -1 if other_name in order and self_name not in order: return 1 # If both groups are in the listed order, go by the defined order. self_index = order.index(self_name) other_index = order.index(other_name) if self_index < other_index: return -1 if self_index > other_index: return 1 return 0 def PathFromSourceTreeAndPath(self): # Turn the object's sourceTree and path properties into a single flat # string of a form comparable to the path parameter. If there's a # sourceTree property other than "", wrap it in $(...) for the # comparison. components = [] if self._properties["sourceTree"] != "": components.append("$(" + self._properties["sourceTree"] + ")") if "path" in self._properties: components.append(self._properties["path"]) if len(components) > 0: return posixpath.join(*components) return None def FullPath(self): # Returns a full path to self relative to the project file, or relative # to some other source tree. Start with self, and walk up the chain of # parents prepending their paths, if any, until no more parents are # available (project-relative path) or until a path relative to some # source tree is found. xche = self path = None while isinstance(xche, XCHierarchicalElement) and ( path is None or (not path.startswith("/") and not path.startswith("$")) ): this_path = xche.PathFromSourceTreeAndPath() if this_path is not None and path is not None: path = posixpath.join(this_path, path) elif this_path is not None: path = this_path xche = xche.parent return path class PBXGroup(XCHierarchicalElement): """ Attributes: _children_by_path: Maps pathnames of children of this PBXGroup to the actual child XCHierarchicalElement objects. _variant_children_by_name_and_path: Maps (name, path) tuples of PBXVariantGroup children to the actual child PBXVariantGroup objects. """ _schema = XCHierarchicalElement._schema.copy() _schema.update( { "children": [1, XCHierarchicalElement, 1, 1, []], "name": [0, str, 0, 0], "path": [0, str, 0, 0], } ) def __init__(self, properties=None, id=None, parent=None): # super XCHierarchicalElement.__init__(self, properties, id, parent) self._children_by_path = {} self._variant_children_by_name_and_path = {} for child in self._properties.get("children", []): self._AddChildToDicts(child) def Hashables(self): # super hashables = XCHierarchicalElement.Hashables(self) # It is not sufficient to just rely on name and parent to build a unique # hashable : a node could have two child PBXGroup sharing a common name. # To add entropy the hashable is enhanced with the names of all its # children. for child in self._properties.get("children", []): child_name = child.Name() if child_name is not None: hashables.append(child_name) return hashables def HashablesForChild(self): # To avoid a circular reference the hashables used to compute a child id do # not include the child names. return XCHierarchicalElement.Hashables(self) def _AddChildToDicts(self, child): # Sets up this PBXGroup object's dicts to reference the child properly. child_path = child.PathFromSourceTreeAndPath() if child_path: if child_path in self._children_by_path: raise ValueError("Found multiple children with path " + child_path) self._children_by_path[child_path] = child if isinstance(child, PBXVariantGroup): child_name = child._properties.get("name", None) key = (child_name, child_path) if key in self._variant_children_by_name_and_path: raise ValueError( "Found multiple PBXVariantGroup children with " + "name " + str(child_name) + " and path " + str(child_path) ) self._variant_children_by_name_and_path[key] = child def AppendChild(self, child): # Callers should use this instead of calling # AppendProperty('children', child) directly because this function # maintains the group's dicts. self.AppendProperty("children", child) self._AddChildToDicts(child) def GetChildByName(self, name): # This is not currently optimized with a dict as GetChildByPath is because # it has few callers. Most callers probably want GetChildByPath. This # function is only useful to get children that have names but no paths, # which is rare. The children of the main group ("Source", "Products", # etc.) is pretty much the only case where this likely to come up. # # TODO(mark): Maybe this should raise an error if more than one child is # present with the same name. if "children" not in self._properties: return None for child in self._properties["children"]: if child.Name() == name: return child return None def GetChildByPath(self, path): if not path: return None if path in self._children_by_path: return self._children_by_path[path] return None def GetChildByRemoteObject(self, remote_object): # This method is a little bit esoteric. Given a remote_object, which # should be a PBXFileReference in another project file, this method will # return this group's PBXReferenceProxy object serving as a local proxy # for the remote PBXFileReference. # # This function might benefit from a dict optimization as GetChildByPath # for some workloads, but profiling shows that it's not currently a # problem. if "children" not in self._properties: return None for child in self._properties["children"]: if not isinstance(child, PBXReferenceProxy): continue container_proxy = child._properties["remoteRef"] if container_proxy._properties["remoteGlobalIDString"] == remote_object: return child return None def AddOrGetFileByPath(self, path, hierarchical): """Returns an existing or new file reference corresponding to path. If hierarchical is True, this method will create or use the necessary hierarchical group structure corresponding to path. Otherwise, it will look in and create an item in the current group only. If an existing matching reference is found, it is returned, otherwise, a new one will be created, added to the correct group, and returned. If path identifies a directory by virtue of carrying a trailing slash, this method returns a PBXFileReference of "folder" type. If path identifies a variant, by virtue of it identifying a file inside a directory with an ".lproj" extension, this method returns a PBXVariantGroup containing the variant named by path, and possibly other variants. For all other paths, a "normal" PBXFileReference will be returned. """ # Adding or getting a directory? Directories end with a trailing slash. is_dir = False if path.endswith("/"): is_dir = True path = posixpath.normpath(path) if is_dir: path = path + "/" # Adding or getting a variant? Variants are files inside directories # with an ".lproj" extension. Xcode uses variants for localization. For # a variant path/to/Language.lproj/MainMenu.nib, put a variant group named # MainMenu.nib inside path/to, and give it a variant named Language. In # this example, grandparent would be set to path/to and parent_root would # be set to Language. variant_name = None parent = posixpath.dirname(path) grandparent = posixpath.dirname(parent) parent_basename = posixpath.basename(parent) (parent_root, parent_ext) = posixpath.splitext(parent_basename) if parent_ext == ".lproj": variant_name = parent_root if grandparent == "": grandparent = None # Putting a directory inside a variant group is not currently supported. assert not is_dir or variant_name is None path_split = path.split(posixpath.sep) if ( len(path_split) == 1 or ((is_dir or variant_name is not None) and len(path_split) == 2) or not hierarchical ): # The PBXFileReference or PBXVariantGroup will be added to or gotten from # this PBXGroup, no recursion necessary. if variant_name is None: # Add or get a PBXFileReference. file_ref = self.GetChildByPath(path) if file_ref is not None: assert file_ref.__class__ == PBXFileReference else: file_ref = PBXFileReference({"path": path}) self.AppendChild(file_ref) else: # Add or get a PBXVariantGroup. The variant group name is the same # as the basename (MainMenu.nib in the example above). grandparent # specifies the path to the variant group itself, and path_split[-2:] # is the path of the specific variant relative to its group. variant_group_name = posixpath.basename(path) variant_group_ref = self.AddOrGetVariantGroupByNameAndPath( variant_group_name, grandparent ) variant_path = posixpath.sep.join(path_split[-2:]) variant_ref = variant_group_ref.GetChildByPath(variant_path) if variant_ref is not None: assert variant_ref.__class__ == PBXFileReference else: variant_ref = PBXFileReference( {"name": variant_name, "path": variant_path} ) variant_group_ref.AppendChild(variant_ref) # The caller is interested in the variant group, not the specific # variant file. file_ref = variant_group_ref return file_ref else: # Hierarchical recursion. Add or get a PBXGroup corresponding to the # outermost path component, and then recurse into it, chopping off that # path component. next_dir = path_split[0] group_ref = self.GetChildByPath(next_dir) if group_ref is not None: assert group_ref.__class__ == PBXGroup else: group_ref = PBXGroup({"path": next_dir}) self.AppendChild(group_ref) return group_ref.AddOrGetFileByPath( posixpath.sep.join(path_split[1:]), hierarchical ) def AddOrGetVariantGroupByNameAndPath(self, name, path): """Returns an existing or new PBXVariantGroup for name and path. If a PBXVariantGroup identified by the name and path arguments is already present as a child of this object, it is returned. Otherwise, a new PBXVariantGroup with the correct properties is created, added as a child, and returned. This method will generally be called by AddOrGetFileByPath, which knows when to create a variant group based on the structure of the pathnames passed to it. """ key = (name, path) if key in self._variant_children_by_name_and_path: variant_group_ref = self._variant_children_by_name_and_path[key] assert variant_group_ref.__class__ == PBXVariantGroup return variant_group_ref variant_group_properties = {"name": name} if path is not None: variant_group_properties["path"] = path variant_group_ref = PBXVariantGroup(variant_group_properties) self.AppendChild(variant_group_ref) return variant_group_ref def TakeOverOnlyChild(self, recurse=False): """If this PBXGroup has only one child and it's also a PBXGroup, take it over by making all of its children this object's children. This function will continue to take over only children when those children are groups. If there are three PBXGroups representing a, b, and c, with c inside b and b inside a, and a and b have no other children, this will result in a taking over both b and c, forming a PBXGroup for a/b/c. If recurse is True, this function will recurse into children and ask them to collapse themselves by taking over only children as well. Assuming an example hierarchy with files at a/b/c/d1, a/b/c/d2, and a/b/c/d3/e/f (d1, d2, and f are files, the rest are groups), recursion will result in a group for a/b/c containing a group for d3/e. """ # At this stage, check that child class types are PBXGroup exactly, # instead of using isinstance. The only subclass of PBXGroup, # PBXVariantGroup, should not participate in reparenting in the same way: # reparenting by merging different object types would be wrong. while ( len(self._properties["children"]) == 1 and self._properties["children"][0].__class__ == PBXGroup ): # Loop to take over the innermost only-child group possible. child = self._properties["children"][0] # Assume the child's properties, including its children. Save a copy # of this object's old properties, because they'll still be needed. # This object retains its existing id and parent attributes. old_properties = self._properties self._properties = child._properties self._children_by_path = child._children_by_path if ( "sourceTree" not in self._properties or self._properties["sourceTree"] == "" ): # The child was relative to its parent. Fix up the path. Note that # children with a sourceTree other than "" are not relative to # their parents, so no path fix-up is needed in that case. if "path" in old_properties: if "path" in self._properties: # Both the original parent and child have paths set. self._properties["path"] = posixpath.join( old_properties["path"], self._properties["path"] ) else: # Only the original parent has a path, use it. self._properties["path"] = old_properties["path"] if "sourceTree" in old_properties: # The original parent had a sourceTree set, use it. self._properties["sourceTree"] = old_properties["sourceTree"] # If the original parent had a name set, keep using it. If the original # parent didn't have a name but the child did, let the child's name # live on. If the name attribute seems unnecessary now, get rid of it. if "name" in old_properties and old_properties["name"] not in ( None, self.Name(), ): self._properties["name"] = old_properties["name"] if ( "name" in self._properties and "path" in self._properties and self._properties["name"] == self._properties["path"] ): del self._properties["name"] # Notify all children of their new parent. for child in self._properties["children"]: child.parent = self # If asked to recurse, recurse. if recurse: for child in self._properties["children"]: if child.__class__ == PBXGroup: child.TakeOverOnlyChild(recurse) def SortGroup(self): self._properties["children"] = sorted( self._properties["children"], key=cmp_to_key(lambda x, y: x.Compare(y)) ) # Recurse. for child in self._properties["children"]: if isinstance(child, PBXGroup): child.SortGroup() class XCFileLikeElement(XCHierarchicalElement): # Abstract base for objects that can be used as the fileRef property of # PBXBuildFile. def PathHashables(self): # A PBXBuildFile that refers to this object will call this method to # obtain additional hashables specific to this XCFileLikeElement. Don't # just use this object's hashables, they're not specific and unique enough # on their own (without access to the parent hashables.) Instead, provide # hashables that identify this object by path by getting its hashables as # well as the hashables of ancestor XCHierarchicalElement objects. hashables = [] xche = self while isinstance(xche, XCHierarchicalElement): xche_hashables = xche.Hashables() for index, xche_hashable in enumerate(xche_hashables): hashables.insert(index, xche_hashable) xche = xche.parent return hashables class XCContainerPortal(XCObject): # Abstract base for objects that can be used as the containerPortal property # of PBXContainerItemProxy. pass class XCRemoteObject(XCObject): # Abstract base for objects that can be used as the remoteGlobalIDString # property of PBXContainerItemProxy. pass class PBXFileReference(XCFileLikeElement, XCContainerPortal, XCRemoteObject): _schema = XCFileLikeElement._schema.copy() _schema.update( { "explicitFileType": [0, str, 0, 0], "lastKnownFileType": [0, str, 0, 0], "name": [0, str, 0, 0], "path": [0, str, 0, 1], } ) # Weird output rules for PBXFileReference. _should_print_single_line = True # super _encode_transforms = XCFileLikeElement._alternate_encode_transforms def __init__(self, properties=None, id=None, parent=None): # super XCFileLikeElement.__init__(self, properties, id, parent) if "path" in self._properties and self._properties["path"].endswith("/"): self._properties["path"] = self._properties["path"][:-1] is_dir = True else: is_dir = False if ( "path" in self._properties and "lastKnownFileType" not in self._properties and "explicitFileType" not in self._properties ): # TODO(mark): This is the replacement for a replacement for a quick hack. # It is no longer incredibly sucky, but this list needs to be extended. extension_map = { "a": "archive.ar", "app": "wrapper.application", "bdic": "file", "bundle": "wrapper.cfbundle", "c": "sourcecode.c.c", "cc": "sourcecode.cpp.cpp", "cpp": "sourcecode.cpp.cpp", "css": "text.css", "cxx": "sourcecode.cpp.cpp", "dart": "sourcecode", "dylib": "compiled.mach-o.dylib", "framework": "wrapper.framework", "gyp": "sourcecode", "gypi": "sourcecode", "h": "sourcecode.c.h", "hxx": "sourcecode.cpp.h", "icns": "image.icns", "java": "sourcecode.java", "js": "sourcecode.javascript", "kext": "wrapper.kext", "m": "sourcecode.c.objc", "mm": "sourcecode.cpp.objcpp", "nib": "wrapper.nib", "o": "compiled.mach-o.objfile", "pdf": "image.pdf", "pl": "text.script.perl", "plist": "text.plist.xml", "pm": "text.script.perl", "png": "image.png", "py": "text.script.python", "r": "sourcecode.rez", "rez": "sourcecode.rez", "s": "sourcecode.asm", "storyboard": "file.storyboard", "strings": "text.plist.strings", "swift": "sourcecode.swift", "ttf": "file", "xcassets": "folder.assetcatalog", "xcconfig": "text.xcconfig", "xcdatamodel": "wrapper.xcdatamodel", "xcdatamodeld": "wrapper.xcdatamodeld", "xib": "file.xib", "y": "sourcecode.yacc", } prop_map = { "dart": "explicitFileType", "gyp": "explicitFileType", "gypi": "explicitFileType", } if is_dir: file_type = "folder" prop_name = "lastKnownFileType" else: basename = posixpath.basename(self._properties["path"]) (root, ext) = posixpath.splitext(basename) # Check the map using a lowercase extension. # TODO(mark): Maybe it should try with the original case first and fall # back to lowercase, in case there are any instances where case # matters. There currently aren't. if ext != "": ext = ext[1:].lower() # TODO(mark): "text" is the default value, but "file" is appropriate # for unrecognized files not containing text. Xcode seems to choose # based on content. file_type = extension_map.get(ext, "text") prop_name = prop_map.get(ext, "lastKnownFileType") self._properties[prop_name] = file_type class PBXVariantGroup(PBXGroup, XCFileLikeElement): """PBXVariantGroup is used by Xcode to represent localizations.""" # No additions to the schema relative to PBXGroup. pass # PBXReferenceProxy is also an XCFileLikeElement subclass. It is defined below # because it uses PBXContainerItemProxy, defined below. class XCBuildConfiguration(XCObject): _schema = XCObject._schema.copy() _schema.update( { "baseConfigurationReference": [0, PBXFileReference, 0, 0], "buildSettings": [0, dict, 0, 1, {}], "name": [0, str, 0, 1], } ) def HasBuildSetting(self, key): return key in self._properties["buildSettings"] def GetBuildSetting(self, key): return self._properties["buildSettings"][key] def SetBuildSetting(self, key, value): # TODO(mark): If a list, copy? self._properties["buildSettings"][key] = value def AppendBuildSetting(self, key, value): if key not in self._properties["buildSettings"]: self._properties["buildSettings"][key] = [] self._properties["buildSettings"][key].append(value) def DelBuildSetting(self, key): if key in self._properties["buildSettings"]: del self._properties["buildSettings"][key] def SetBaseConfiguration(self, value): self._properties["baseConfigurationReference"] = value class XCConfigurationList(XCObject): # _configs is the default list of configurations. _configs = [ XCBuildConfiguration({"name": "Debug"}), XCBuildConfiguration({"name": "Release"}), ] _schema = XCObject._schema.copy() _schema.update( { "buildConfigurations": [1, XCBuildConfiguration, 1, 1, _configs], "defaultConfigurationIsVisible": [0, int, 0, 1, 1], "defaultConfigurationName": [0, str, 0, 1, "Release"], } ) def Name(self): return ( "Build configuration list for " + self.parent.__class__.__name__ + ' "' + self.parent.Name() + '"' ) def ConfigurationNamed(self, name): """Convenience accessor to obtain an XCBuildConfiguration by name.""" for configuration in self._properties["buildConfigurations"]: if configuration._properties["name"] == name: return configuration raise KeyError(name) def DefaultConfiguration(self): """Convenience accessor to obtain the default XCBuildConfiguration.""" return self.ConfigurationNamed(self._properties["defaultConfigurationName"]) def HasBuildSetting(self, key): """Determines the state of a build setting in all XCBuildConfiguration child objects. If all child objects have key in their build settings, and the value is the same in all child objects, returns 1. If no child objects have the key in their build settings, returns 0. If some, but not all, child objects have the key in their build settings, or if any children have different values for the key, returns -1. """ has = None value = None for configuration in self._properties["buildConfigurations"]: configuration_has = configuration.HasBuildSetting(key) if has is None: has = configuration_has elif has != configuration_has: return -1 if configuration_has: configuration_value = configuration.GetBuildSetting(key) if value is None: value = configuration_value elif value != configuration_value: return -1 if not has: return 0 return 1 def GetBuildSetting(self, key): """Gets the build setting for key. All child XCConfiguration objects must have the same value set for the setting, or a ValueError will be raised. """ # TODO(mark): This is wrong for build settings that are lists. The list # contents should be compared (and a list copy returned?) value = None for configuration in self._properties["buildConfigurations"]: configuration_value = configuration.GetBuildSetting(key) if value is None: value = configuration_value else: if value != configuration_value: raise ValueError("Variant values for " + key) return value def SetBuildSetting(self, key, value): """Sets the build setting for key to value in all child XCBuildConfiguration objects. """ for configuration in self._properties["buildConfigurations"]: configuration.SetBuildSetting(key, value) def AppendBuildSetting(self, key, value): """Appends value to the build setting for key, which is treated as a list, in all child XCBuildConfiguration objects. """ for configuration in self._properties["buildConfigurations"]: configuration.AppendBuildSetting(key, value) def DelBuildSetting(self, key): """Deletes the build setting key from all child XCBuildConfiguration objects. """ for configuration in self._properties["buildConfigurations"]: configuration.DelBuildSetting(key) def SetBaseConfiguration(self, value): """Sets the build configuration in all child XCBuildConfiguration objects. """ for configuration in self._properties["buildConfigurations"]: configuration.SetBaseConfiguration(value) class PBXBuildFile(XCObject): _schema = XCObject._schema.copy() _schema.update( { "fileRef": [0, XCFileLikeElement, 0, 1], "settings": [0, str, 0, 0], # hack, it's a dict } ) # Weird output rules for PBXBuildFile. _should_print_single_line = True _encode_transforms = XCObject._alternate_encode_transforms def Name(self): # Example: "main.cc in Sources" return self._properties["fileRef"].Name() + " in " + self.parent.Name() def Hashables(self): # super hashables = XCObject.Hashables(self) # It is not sufficient to just rely on Name() to get the # XCFileLikeElement's name, because that is not a complete pathname. # PathHashables returns hashables unique enough that no two # PBXBuildFiles should wind up with the same set of hashables, unless # someone adds the same file multiple times to the same target. That # would be considered invalid anyway. hashables.extend(self._properties["fileRef"].PathHashables()) return hashables class XCBuildPhase(XCObject): """Abstract base for build phase classes. Not represented in a project file. Attributes: _files_by_path: A dict mapping each path of a child in the files list by path (keys) to the corresponding PBXBuildFile children (values). _files_by_xcfilelikeelement: A dict mapping each XCFileLikeElement (keys) to the corresponding PBXBuildFile children (values). """ # TODO(mark): Some build phase types, like PBXShellScriptBuildPhase, don't # actually have a "files" list. XCBuildPhase should not have "files" but # another abstract subclass of it should provide this, and concrete build # phase types that do have "files" lists should be derived from that new # abstract subclass. XCBuildPhase should only provide buildActionMask and # runOnlyForDeploymentPostprocessing, and not files or the various # file-related methods and attributes. _schema = XCObject._schema.copy() _schema.update( { "buildActionMask": [0, int, 0, 1, 0x7FFFFFFF], "files": [1, PBXBuildFile, 1, 1, []], "runOnlyForDeploymentPostprocessing": [0, int, 0, 1, 0], } ) def __init__(self, properties=None, id=None, parent=None): # super XCObject.__init__(self, properties, id, parent) self._files_by_path = {} self._files_by_xcfilelikeelement = {} for pbxbuildfile in self._properties.get("files", []): self._AddBuildFileToDicts(pbxbuildfile) def FileGroup(self, path): # Subclasses must override this by returning a two-element tuple. The # first item in the tuple should be the PBXGroup to which "path" should be # added, either as a child or deeper descendant. The second item should # be a boolean indicating whether files should be added into hierarchical # groups or one single flat group. raise NotImplementedError(self.__class__.__name__ + " must implement FileGroup") def _AddPathToDict(self, pbxbuildfile, path): """Adds path to the dict tracking paths belonging to this build phase. If the path is already a member of this build phase, raises an exception. """ if path in self._files_by_path: raise ValueError("Found multiple build files with path " + path) self._files_by_path[path] = pbxbuildfile def _AddBuildFileToDicts(self, pbxbuildfile, path=None): """Maintains the _files_by_path and _files_by_xcfilelikeelement dicts. If path is specified, then it is the path that is being added to the phase, and pbxbuildfile must contain either a PBXFileReference directly referencing that path, or it must contain a PBXVariantGroup that itself contains a PBXFileReference referencing the path. If path is not specified, either the PBXFileReference's path or the paths of all children of the PBXVariantGroup are taken as being added to the phase. If the path is already present in the phase, raises an exception. If the PBXFileReference or PBXVariantGroup referenced by pbxbuildfile are already present in the phase, referenced by a different PBXBuildFile object, raises an exception. This does not raise an exception when a PBXFileReference or PBXVariantGroup reappear and are referenced by the same PBXBuildFile that has already introduced them, because in the case of PBXVariantGroup objects, they may correspond to multiple paths that are not all added simultaneously. When this situation occurs, the path needs to be added to _files_by_path, but nothing needs to change in _files_by_xcfilelikeelement, and the caller should have avoided adding the PBXBuildFile if it is already present in the list of children. """ xcfilelikeelement = pbxbuildfile._properties["fileRef"] paths = [] if path is not None: # It's best when the caller provides the path. if isinstance(xcfilelikeelement, PBXVariantGroup): paths.append(path) else: # If the caller didn't provide a path, there can be either multiple # paths (PBXVariantGroup) or one. if isinstance(xcfilelikeelement, PBXVariantGroup): for variant in xcfilelikeelement._properties["children"]: paths.append(variant.FullPath()) else: paths.append(xcfilelikeelement.FullPath()) # Add the paths first, because if something's going to raise, the # messages provided by _AddPathToDict are more useful owing to its # having access to a real pathname and not just an object's Name(). for a_path in paths: self._AddPathToDict(pbxbuildfile, a_path) # If another PBXBuildFile references this XCFileLikeElement, there's a # problem. if ( xcfilelikeelement in self._files_by_xcfilelikeelement and self._files_by_xcfilelikeelement[xcfilelikeelement] != pbxbuildfile ): raise ValueError( "Found multiple build files for " + xcfilelikeelement.Name() ) self._files_by_xcfilelikeelement[xcfilelikeelement] = pbxbuildfile def AppendBuildFile(self, pbxbuildfile, path=None): # Callers should use this instead of calling # AppendProperty('files', pbxbuildfile) directly because this function # maintains the object's dicts. Better yet, callers can just call AddFile # with a pathname and not worry about building their own PBXBuildFile # objects. self.AppendProperty("files", pbxbuildfile) self._AddBuildFileToDicts(pbxbuildfile, path) def AddFile(self, path, settings=None): (file_group, hierarchical) = self.FileGroup(path) file_ref = file_group.AddOrGetFileByPath(path, hierarchical) if file_ref in self._files_by_xcfilelikeelement and isinstance( file_ref, PBXVariantGroup ): # There's already a PBXBuildFile in this phase corresponding to the # PBXVariantGroup. path just provides a new variant that belongs to # the group. Add the path to the dict. pbxbuildfile = self._files_by_xcfilelikeelement[file_ref] self._AddBuildFileToDicts(pbxbuildfile, path) else: # Add a new PBXBuildFile to get file_ref into the phase. if settings is None: pbxbuildfile = PBXBuildFile({"fileRef": file_ref}) else: pbxbuildfile = PBXBuildFile({"fileRef": file_ref, "settings": settings}) self.AppendBuildFile(pbxbuildfile, path) class PBXHeadersBuildPhase(XCBuildPhase): # No additions to the schema relative to XCBuildPhase. def Name(self): return "Headers" def FileGroup(self, path): return self.PBXProjectAncestor().RootGroupForPath(path) class PBXResourcesBuildPhase(XCBuildPhase): # No additions to the schema relative to XCBuildPhase. def Name(self): return "Resources" def FileGroup(self, path): return self.PBXProjectAncestor().RootGroupForPath(path) class PBXSourcesBuildPhase(XCBuildPhase): # No additions to the schema relative to XCBuildPhase. def Name(self): return "Sources" def FileGroup(self, path): return self.PBXProjectAncestor().RootGroupForPath(path) class PBXFrameworksBuildPhase(XCBuildPhase): # No additions to the schema relative to XCBuildPhase. def Name(self): return "Frameworks" def FileGroup(self, path): (root, ext) = posixpath.splitext(path) if ext != "": ext = ext[1:].lower() if ext == "o": # .o files are added to Xcode Frameworks phases, but conceptually aren't # frameworks, they're more like sources or intermediates. Redirect them # to show up in one of those other groups. return self.PBXProjectAncestor().RootGroupForPath(path) else: return (self.PBXProjectAncestor().FrameworksGroup(), False) class PBXShellScriptBuildPhase(XCBuildPhase): _schema = XCBuildPhase._schema.copy() _schema.update( { "inputPaths": [1, str, 0, 1, []], "name": [0, str, 0, 0], "outputPaths": [1, str, 0, 1, []], "shellPath": [0, str, 0, 1, "/bin/sh"], "shellScript": [0, str, 0, 1], "showEnvVarsInLog": [0, int, 0, 0], } ) def Name(self): if "name" in self._properties: return self._properties["name"] return "ShellScript" class PBXCopyFilesBuildPhase(XCBuildPhase): _schema = XCBuildPhase._schema.copy() _schema.update( { "dstPath": [0, str, 0, 1], "dstSubfolderSpec": [0, int, 0, 1], "name": [0, str, 0, 0], } ) # path_tree_re matches "$(DIR)/path", "$(DIR)/$(DIR2)/path" or just "$(DIR)". # Match group 1 is "DIR", group 3 is "path" or "$(DIR2") or "$(DIR2)/path" # or None. If group 3 is "path", group 4 will be None otherwise group 4 is # "DIR2" and group 6 is "path". path_tree_re = re.compile(r"^\$\((.*?)\)(/(\$\((.*?)\)(/(.*)|)|(.*)|)|)$") # path_tree_{first,second}_to_subfolder map names of Xcode variables to the # associated dstSubfolderSpec property value used in a PBXCopyFilesBuildPhase # object. path_tree_first_to_subfolder = { # Types that can be chosen via the Xcode UI. "BUILT_PRODUCTS_DIR": 16, # Products Directory "BUILT_FRAMEWORKS_DIR": 10, # Not an official Xcode macro. # Existed before support for the # names below was added. Maps to # "Frameworks". } path_tree_second_to_subfolder = { "WRAPPER_NAME": 1, # Wrapper # Although Xcode's friendly name is "Executables", the destination # is demonstrably the value of the build setting # EXECUTABLE_FOLDER_PATH not EXECUTABLES_FOLDER_PATH. "EXECUTABLE_FOLDER_PATH": 6, # Executables. "UNLOCALIZED_RESOURCES_FOLDER_PATH": 7, # Resources "JAVA_FOLDER_PATH": 15, # Java Resources "FRAMEWORKS_FOLDER_PATH": 10, # Frameworks "SHARED_FRAMEWORKS_FOLDER_PATH": 11, # Shared Frameworks "SHARED_SUPPORT_FOLDER_PATH": 12, # Shared Support "PLUGINS_FOLDER_PATH": 13, # PlugIns # For XPC Services, Xcode sets both dstPath and dstSubfolderSpec. # Note that it re-uses the BUILT_PRODUCTS_DIR value for # dstSubfolderSpec. dstPath is set below. "XPCSERVICES_FOLDER_PATH": 16, # XPC Services. } def Name(self): if "name" in self._properties: return self._properties["name"] return "CopyFiles" def FileGroup(self, path): return self.PBXProjectAncestor().RootGroupForPath(path) def SetDestination(self, path): """Set the dstSubfolderSpec and dstPath properties from path. path may be specified in the same notation used for XCHierarchicalElements, specifically, "$(DIR)/path". """ path_tree_match = self.path_tree_re.search(path) if path_tree_match: path_tree = path_tree_match.group(1) if path_tree in self.path_tree_first_to_subfolder: subfolder = self.path_tree_first_to_subfolder[path_tree] relative_path = path_tree_match.group(3) if relative_path is None: relative_path = "" if subfolder == 16 and path_tree_match.group(4) is not None: # BUILT_PRODUCTS_DIR (16) is the first element in a path whose # second element is possibly one of the variable names in # path_tree_second_to_subfolder. Xcode sets the values of all these # variables to relative paths so .gyp files must prefix them with # BUILT_PRODUCTS_DIR, e.g. # $(BUILT_PRODUCTS_DIR)/$(PLUGINS_FOLDER_PATH). Then # xcode_emulation.py can export these variables with the same values # as Xcode yet make & ninja files can determine the absolute path # to the target. Xcode uses the dstSubfolderSpec value set here # to determine the full path. # # An alternative of xcode_emulation.py setting the values to # absolute paths when exporting these variables has been # ruled out because then the values would be different # depending on the build tool. # # Another alternative is to invent new names for the variables used # to match to the subfolder indices in the second table. .gyp files # then will not need to prepend $(BUILT_PRODUCTS_DIR) because # xcode_emulation.py can set the values of those variables to # the absolute paths when exporting. This is possibly the thinking # behind BUILT_FRAMEWORKS_DIR which is used in exactly this manner. # # Requiring prepending BUILT_PRODUCTS_DIR has been chosen because # this same way could be used to specify destinations in .gyp files # that pre-date this addition to GYP. However they would only work # with the Xcode generator. # The previous version of xcode_emulation.py # does not export these variables. Such files will get the benefit # of the Xcode UI showing the proper destination name simply by # regenerating the projects with this version of GYP. path_tree = path_tree_match.group(4) relative_path = path_tree_match.group(6) separator = "/" if path_tree in self.path_tree_second_to_subfolder: subfolder = self.path_tree_second_to_subfolder[path_tree] if relative_path is None: relative_path = "" separator = "" if path_tree == "XPCSERVICES_FOLDER_PATH": relative_path = ( "$(CONTENTS_FOLDER_PATH)/XPCServices" + separator + relative_path ) else: # subfolder = 16 from above # The second element of the path is an unrecognized variable. # Include it and any remaining elements in relative_path. relative_path = path_tree_match.group(3) else: # The path starts with an unrecognized Xcode variable # name like $(SRCROOT). Xcode will still handle this # as an "absolute path" that starts with the variable. subfolder = 0 relative_path = path elif path.startswith("/"): # Special case. Absolute paths are in dstSubfolderSpec 0. subfolder = 0 relative_path = path[1:] else: raise ValueError( f"Can't use path {path} in a {self.__class__.__name__}" ) self._properties["dstPath"] = relative_path self._properties["dstSubfolderSpec"] = subfolder class PBXBuildRule(XCObject): _schema = XCObject._schema.copy() _schema.update( { "compilerSpec": [0, str, 0, 1], "filePatterns": [0, str, 0, 0], "fileType": [0, str, 0, 1], "isEditable": [0, int, 0, 1, 1], "outputFiles": [1, str, 0, 1, []], "script": [0, str, 0, 0], } ) def Name(self): # Not very inspired, but it's what Xcode uses. return self.__class__.__name__ def Hashables(self): # super hashables = XCObject.Hashables(self) # Use the hashables of the weak objects that this object refers to. hashables.append(self._properties["fileType"]) if "filePatterns" in self._properties: hashables.append(self._properties["filePatterns"]) return hashables class PBXContainerItemProxy(XCObject): # When referencing an item in this project file, containerPortal is the # PBXProject root object of this project file. When referencing an item in # another project file, containerPortal is a PBXFileReference identifying # the other project file. # # When serving as a proxy to an XCTarget (in this project file or another), # proxyType is 1. When serving as a proxy to a PBXFileReference (in another # project file), proxyType is 2. Type 2 is used for references to the # producs of the other project file's targets. # # Xcode is weird about remoteGlobalIDString. Usually, it's printed without # a comment, indicating that it's tracked internally simply as a string, but # sometimes it's printed with a comment (usually when the object is initially # created), indicating that it's tracked as a project file object at least # sometimes. This module always tracks it as an object, but contains a hack # to prevent it from printing the comment in the project file output. See # _XCKVPrint. _schema = XCObject._schema.copy() _schema.update( { "containerPortal": [0, XCContainerPortal, 0, 1], "proxyType": [0, int, 0, 1], "remoteGlobalIDString": [0, XCRemoteObject, 0, 1], "remoteInfo": [0, str, 0, 1], } ) def __repr__(self): props = self._properties name = "{}.gyp:{}".format(props["containerPortal"].Name(), props["remoteInfo"]) return f"<{self.__class__.__name__} {name!r} at 0x{id(self):x}>" def Name(self): # Admittedly not the best name, but it's what Xcode uses. return self.__class__.__name__ def Hashables(self): # super hashables = XCObject.Hashables(self) # Use the hashables of the weak objects that this object refers to. hashables.extend(self._properties["containerPortal"].Hashables()) hashables.extend(self._properties["remoteGlobalIDString"].Hashables()) return hashables class PBXTargetDependency(XCObject): # The "target" property accepts an XCTarget object, and obviously not # NoneType. But XCTarget is defined below, so it can't be put into the # schema yet. The definition of PBXTargetDependency can't be moved below # XCTarget because XCTarget's own schema references PBXTargetDependency. # Python doesn't deal well with this circular relationship, and doesn't have # a real way to do forward declarations. To work around, the type of # the "target" property is reset below, after XCTarget is defined. # # At least one of "name" and "target" is required. _schema = XCObject._schema.copy() _schema.update( { "name": [0, str, 0, 0], "target": [0, None.__class__, 0, 0], "targetProxy": [0, PBXContainerItemProxy, 1, 1], } ) def __repr__(self): name = self._properties.get("name") or self._properties["target"].Name() return f"<{self.__class__.__name__} {name!r} at 0x{id(self):x}>" def Name(self): # Admittedly not the best name, but it's what Xcode uses. return self.__class__.__name__ def Hashables(self): # super hashables = XCObject.Hashables(self) # Use the hashables of the weak objects that this object refers to. hashables.extend(self._properties["targetProxy"].Hashables()) return hashables class PBXReferenceProxy(XCFileLikeElement): _schema = XCFileLikeElement._schema.copy() _schema.update( { "fileType": [0, str, 0, 1], "path": [0, str, 0, 1], "remoteRef": [0, PBXContainerItemProxy, 1, 1], } ) class XCTarget(XCRemoteObject): # An XCTarget is really just an XCObject, the XCRemoteObject thing is just # to allow PBXProject to be used in the remoteGlobalIDString property of # PBXContainerItemProxy. # # Setting a "name" property at instantiation may also affect "productName", # which may in turn affect the "PRODUCT_NAME" build setting in children of # "buildConfigurationList". See __init__ below. _schema = XCRemoteObject._schema.copy() _schema.update( { "buildConfigurationList": [ 0, XCConfigurationList, 1, 1, XCConfigurationList(), ], "buildPhases": [1, XCBuildPhase, 1, 1, []], "dependencies": [1, PBXTargetDependency, 1, 1, []], "name": [0, str, 0, 1], "productName": [0, str, 0, 1], } ) def __init__( self, properties=None, id=None, parent=None, force_outdir=None, force_prefix=None, force_extension=None, ): # super XCRemoteObject.__init__(self, properties, id, parent) # Set up additional defaults not expressed in the schema. If a "name" # property was supplied, set "productName" if it is not present. Also set # the "PRODUCT_NAME" build setting in each configuration, but only if # the setting is not present in any build configuration. if "name" in self._properties and "productName" not in self._properties: self.SetProperty("productName", self._properties["name"]) if "productName" in self._properties: if "buildConfigurationList" in self._properties: configs = self._properties["buildConfigurationList"] if configs.HasBuildSetting("PRODUCT_NAME") == 0: configs.SetBuildSetting( "PRODUCT_NAME", self._properties["productName"] ) def AddDependency(self, other): pbxproject = self.PBXProjectAncestor() other_pbxproject = other.PBXProjectAncestor() if pbxproject == other_pbxproject: # Add a dependency to another target in the same project file. container = PBXContainerItemProxy( { "containerPortal": pbxproject, "proxyType": 1, "remoteGlobalIDString": other, "remoteInfo": other.Name(), } ) dependency = PBXTargetDependency( {"target": other, "targetProxy": container} ) self.AppendProperty("dependencies", dependency) else: # Add a dependency to a target in a different project file. other_project_ref = pbxproject.AddOrGetProjectReference(other_pbxproject)[1] container = PBXContainerItemProxy( { "containerPortal": other_project_ref, "proxyType": 1, "remoteGlobalIDString": other, "remoteInfo": other.Name(), } ) dependency = PBXTargetDependency( {"name": other.Name(), "targetProxy": container} ) self.AppendProperty("dependencies", dependency) # Proxy all of these through to the build configuration list. def ConfigurationNamed(self, name): return self._properties["buildConfigurationList"].ConfigurationNamed(name) def DefaultConfiguration(self): return self._properties["buildConfigurationList"].DefaultConfiguration() def HasBuildSetting(self, key): return self._properties["buildConfigurationList"].HasBuildSetting(key) def GetBuildSetting(self, key): return self._properties["buildConfigurationList"].GetBuildSetting(key) def SetBuildSetting(self, key, value): return self._properties["buildConfigurationList"].SetBuildSetting(key, value) def AppendBuildSetting(self, key, value): return self._properties["buildConfigurationList"].AppendBuildSetting(key, value) def DelBuildSetting(self, key): return self._properties["buildConfigurationList"].DelBuildSetting(key) # Redefine the type of the "target" property. See PBXTargetDependency._schema # above. PBXTargetDependency._schema["target"][1] = XCTarget class PBXNativeTarget(XCTarget): # buildPhases is overridden in the schema to be able to set defaults. # # NOTE: Contrary to most objects, it is advisable to set parent when # constructing PBXNativeTarget. A parent of an XCTarget must be a PBXProject # object. A parent reference is required for a PBXNativeTarget during # construction to be able to set up the target defaults for productReference, # because a PBXBuildFile object must be created for the target and it must # be added to the PBXProject's mainGroup hierarchy. _schema = XCTarget._schema.copy() _schema.update( { "buildPhases": [ 1, XCBuildPhase, 1, 1, [PBXSourcesBuildPhase(), PBXFrameworksBuildPhase()], ], "buildRules": [1, PBXBuildRule, 1, 1, []], "productReference": [0, PBXFileReference, 0, 1], "productType": [0, str, 0, 1], } ) # Mapping from Xcode product-types to settings. The settings are: # filetype : used for explicitFileType in the project file # prefix : the prefix for the file name # suffix : the suffix for the file name _product_filetypes = { "com.apple.product-type.application": ["wrapper.application", "", ".app"], "com.apple.product-type.application.watchapp": [ "wrapper.application", "", ".app", ], "com.apple.product-type.watchkit-extension": [ "wrapper.app-extension", "", ".appex", ], "com.apple.product-type.app-extension": ["wrapper.app-extension", "", ".appex"], "com.apple.product-type.bundle": ["wrapper.cfbundle", "", ".bundle"], "com.apple.product-type.framework": ["wrapper.framework", "", ".framework"], "com.apple.product-type.library.dynamic": [ "compiled.mach-o.dylib", "lib", ".dylib", ], "com.apple.product-type.library.static": ["archive.ar", "lib", ".a"], "com.apple.product-type.tool": ["compiled.mach-o.executable", "", ""], "com.apple.product-type.bundle.unit-test": ["wrapper.cfbundle", "", ".xctest"], "com.apple.product-type.bundle.ui-testing": ["wrapper.cfbundle", "", ".xctest"], "com.googlecode.gyp.xcode.bundle": ["compiled.mach-o.dylib", "", ".so"], "com.apple.product-type.kernel-extension": ["wrapper.kext", "", ".kext"], } def __init__( self, properties=None, id=None, parent=None, force_outdir=None, force_prefix=None, force_extension=None, ): # super XCTarget.__init__(self, properties, id, parent) if ( "productName" in self._properties and "productType" in self._properties and "productReference" not in self._properties and self._properties["productType"] in self._product_filetypes ): products_group = None pbxproject = self.PBXProjectAncestor() if pbxproject is not None: products_group = pbxproject.ProductsGroup() if products_group is not None: (filetype, prefix, suffix) = self._product_filetypes[ self._properties["productType"] ] # Xcode does not have a distinct type for loadable modules that are # pure BSD targets (not in a bundle wrapper). GYP allows such modules # to be specified by setting a target type to loadable_module without # having mac_bundle set. These are mapped to the pseudo-product type # com.googlecode.gyp.xcode.bundle. # # By picking up this special type and converting it to a dynamic # library (com.apple.product-type.library.dynamic) with fix-ups, # single-file loadable modules can be produced. # # MACH_O_TYPE is changed to mh_bundle to produce the proper file type # (as opposed to mh_dylib). In order for linking to succeed, # DYLIB_CURRENT_VERSION and DYLIB_COMPATIBILITY_VERSION must be # cleared. They are meaningless for type mh_bundle. # # Finally, the .so extension is forcibly applied over the default # (.dylib), unless another forced extension is already selected. # .dylib is plainly wrong, and .bundle is used by loadable_modules in # bundle wrappers (com.apple.product-type.bundle). .so seems an odd # choice because it's used as the extension on many other systems that # don't distinguish between linkable shared libraries and non-linkable # loadable modules, but there's precedent: Python loadable modules on # Mac OS X use an .so extension. if self._properties["productType"] == "com.googlecode.gyp.xcode.bundle": self._properties[ "productType" ] = "com.apple.product-type.library.dynamic" self.SetBuildSetting("MACH_O_TYPE", "mh_bundle") self.SetBuildSetting("DYLIB_CURRENT_VERSION", "") self.SetBuildSetting("DYLIB_COMPATIBILITY_VERSION", "") if force_extension is None: force_extension = suffix[1:] if ( self._properties["productType"] in { "com.apple.product-type-bundle.unit.test", "com.apple.product-type-bundle.ui-testing" } ) and force_extension is None: force_extension = suffix[1:] if force_extension is not None: # If it's a wrapper (bundle), set WRAPPER_EXTENSION. # Extension override. suffix = "." + force_extension if filetype.startswith("wrapper."): self.SetBuildSetting("WRAPPER_EXTENSION", force_extension) else: self.SetBuildSetting("EXECUTABLE_EXTENSION", force_extension) if filetype.startswith("compiled.mach-o.executable"): product_name = self._properties["productName"] product_name += suffix suffix = "" self.SetProperty("productName", product_name) self.SetBuildSetting("PRODUCT_NAME", product_name) # Xcode handles most prefixes based on the target type, however there # are exceptions. If a "BSD Dynamic Library" target is added in the # Xcode UI, Xcode sets EXECUTABLE_PREFIX. This check duplicates that # behavior. if force_prefix is not None: prefix = force_prefix if filetype.startswith("wrapper."): self.SetBuildSetting("WRAPPER_PREFIX", prefix) else: self.SetBuildSetting("EXECUTABLE_PREFIX", prefix) if force_outdir is not None: self.SetBuildSetting("TARGET_BUILD_DIR", force_outdir) # TODO(tvl): Remove the below hack. # http://code.google.com/p/gyp/issues/detail?id=122 # Some targets include the prefix in the target_name. These targets # really should just add a product_name setting that doesn't include # the prefix. For example: # target_name = 'libevent', product_name = 'event' # This check cleans up for them. product_name = self._properties["productName"] prefix_len = len(prefix) if prefix_len and (product_name[:prefix_len] == prefix): product_name = product_name[prefix_len:] self.SetProperty("productName", product_name) self.SetBuildSetting("PRODUCT_NAME", product_name) ref_props = { "explicitFileType": filetype, "includeInIndex": 0, "path": prefix + product_name + suffix, "sourceTree": "BUILT_PRODUCTS_DIR", } file_ref = PBXFileReference(ref_props) products_group.AppendChild(file_ref) self.SetProperty("productReference", file_ref) def GetBuildPhaseByType(self, type): if "buildPhases" not in self._properties: return None the_phase = None for phase in self._properties["buildPhases"]: if isinstance(phase, type): # Some phases may be present in multiples in a well-formed project file, # but phases like PBXSourcesBuildPhase may only be present singly, and # this function is intended as an aid to GetBuildPhaseByType. Loop # over the entire list of phases and assert if more than one of the # desired type is found. assert the_phase is None the_phase = phase return the_phase def HeadersPhase(self): headers_phase = self.GetBuildPhaseByType(PBXHeadersBuildPhase) if headers_phase is None: headers_phase = PBXHeadersBuildPhase() # The headers phase should come before the resources, sources, and # frameworks phases, if any. insert_at = len(self._properties["buildPhases"]) for index, phase in enumerate(self._properties["buildPhases"]): if isinstance( phase, ( PBXResourcesBuildPhase, PBXSourcesBuildPhase, PBXFrameworksBuildPhase, ), ): insert_at = index break self._properties["buildPhases"].insert(insert_at, headers_phase) headers_phase.parent = self return headers_phase def ResourcesPhase(self): resources_phase = self.GetBuildPhaseByType(PBXResourcesBuildPhase) if resources_phase is None: resources_phase = PBXResourcesBuildPhase() # The resources phase should come before the sources and frameworks # phases, if any. insert_at = len(self._properties["buildPhases"]) for index, phase in enumerate(self._properties["buildPhases"]): if isinstance(phase, (PBXSourcesBuildPhase, PBXFrameworksBuildPhase)): insert_at = index break self._properties["buildPhases"].insert(insert_at, resources_phase) resources_phase.parent = self return resources_phase def SourcesPhase(self): sources_phase = self.GetBuildPhaseByType(PBXSourcesBuildPhase) if sources_phase is None: sources_phase = PBXSourcesBuildPhase() self.AppendProperty("buildPhases", sources_phase) return sources_phase def FrameworksPhase(self): frameworks_phase = self.GetBuildPhaseByType(PBXFrameworksBuildPhase) if frameworks_phase is None: frameworks_phase = PBXFrameworksBuildPhase() self.AppendProperty("buildPhases", frameworks_phase) return frameworks_phase def AddDependency(self, other): # super XCTarget.AddDependency(self, other) static_library_type = "com.apple.product-type.library.static" shared_library_type = "com.apple.product-type.library.dynamic" framework_type = "com.apple.product-type.framework" if ( isinstance(other, PBXNativeTarget) and "productType" in self._properties and self._properties["productType"] != static_library_type and "productType" in other._properties and ( other._properties["productType"] == static_library_type or ( ( other._properties["productType"] in { shared_library_type, framework_type } ) and ( (not other.HasBuildSetting("MACH_O_TYPE")) or other.GetBuildSetting("MACH_O_TYPE") != "mh_bundle" ) ) ) ): file_ref = other.GetProperty("productReference") pbxproject = self.PBXProjectAncestor() other_pbxproject = other.PBXProjectAncestor() if pbxproject != other_pbxproject: other_project_product_group = pbxproject.AddOrGetProjectReference( other_pbxproject )[0] file_ref = other_project_product_group.GetChildByRemoteObject(file_ref) self.FrameworksPhase().AppendProperty( "files", PBXBuildFile({"fileRef": file_ref}) ) class PBXAggregateTarget(XCTarget): pass class PBXProject(XCContainerPortal): # A PBXProject is really just an XCObject, the XCContainerPortal thing is # just to allow PBXProject to be used in the containerPortal property of # PBXContainerItemProxy. """ Attributes: path: "sample.xcodeproj". TODO(mark) Document me! _other_pbxprojects: A dictionary, keyed by other PBXProject objects. Each value is a reference to the dict in the projectReferences list associated with the keyed PBXProject. """ _schema = XCContainerPortal._schema.copy() _schema.update( { "attributes": [0, dict, 0, 0], "buildConfigurationList": [ 0, XCConfigurationList, 1, 1, XCConfigurationList(), ], "compatibilityVersion": [0, str, 0, 1, "Xcode 3.2"], "hasScannedForEncodings": [0, int, 0, 1, 1], "mainGroup": [0, PBXGroup, 1, 1, PBXGroup()], "projectDirPath": [0, str, 0, 1, ""], "projectReferences": [1, dict, 0, 0], "projectRoot": [0, str, 0, 1, ""], "targets": [1, XCTarget, 1, 1, []], } ) def __init__(self, properties=None, id=None, parent=None, path=None): self.path = path self._other_pbxprojects = {} # super XCContainerPortal.__init__(self, properties, id, parent) def Name(self): name = self.path if name[-10:] == ".xcodeproj": name = name[:-10] return posixpath.basename(name) def Path(self): return self.path def Comment(self): return "Project object" def Children(self): # super children = XCContainerPortal.Children(self) # Add children that the schema doesn't know about. Maybe there's a more # elegant way around this, but this is the only case where we need to own # objects in a dictionary (that is itself in a list), and three lines for # a one-off isn't that big a deal. if "projectReferences" in self._properties: for reference in self._properties["projectReferences"]: children.append(reference["ProductGroup"]) return children def PBXProjectAncestor(self): return self def _GroupByName(self, name): if "mainGroup" not in self._properties: self.SetProperty("mainGroup", PBXGroup()) main_group = self._properties["mainGroup"] group = main_group.GetChildByName(name) if group is None: group = PBXGroup({"name": name}) main_group.AppendChild(group) return group # SourceGroup and ProductsGroup are created by default in Xcode's own # templates. def SourceGroup(self): return self._GroupByName("Source") def ProductsGroup(self): return self._GroupByName("Products") # IntermediatesGroup is used to collect source-like files that are generated # by rules or script phases and are placed in intermediate directories such # as DerivedSources. def IntermediatesGroup(self): return self._GroupByName("Intermediates") # FrameworksGroup and ProjectsGroup are top-level groups used to collect # frameworks and projects. def FrameworksGroup(self): return self._GroupByName("Frameworks") def ProjectsGroup(self): return self._GroupByName("Projects") def RootGroupForPath(self, path): """Returns a PBXGroup child of this object to which path should be added. This method is intended to choose between SourceGroup and IntermediatesGroup on the basis of whether path is present in a source directory or an intermediates directory. For the purposes of this determination, any path located within a derived file directory such as PROJECT_DERIVED_FILE_DIR is treated as being in an intermediates directory. The returned value is a two-element tuple. The first element is the PBXGroup, and the second element specifies whether that group should be organized hierarchically (True) or as a single flat list (False). """ # TODO(mark): make this a class variable and bind to self on call? # Also, this list is nowhere near exhaustive. # INTERMEDIATE_DIR and SHARED_INTERMEDIATE_DIR are used by # gyp.generator.xcode. There should probably be some way for that module # to push the names in, rather than having to hard-code them here. source_tree_groups = { "DERIVED_FILE_DIR": (self.IntermediatesGroup, True), "INTERMEDIATE_DIR": (self.IntermediatesGroup, True), "PROJECT_DERIVED_FILE_DIR": (self.IntermediatesGroup, True), "SHARED_INTERMEDIATE_DIR": (self.IntermediatesGroup, True), } (source_tree, path) = SourceTreeAndPathFromPath(path) if source_tree is not None and source_tree in source_tree_groups: (group_func, hierarchical) = source_tree_groups[source_tree] group = group_func() return (group, hierarchical) # TODO(mark): make additional choices based on file extension. return (self.SourceGroup(), True) def AddOrGetFileInRootGroup(self, path): """Returns a PBXFileReference corresponding to path in the correct group according to RootGroupForPath's heuristics. If an existing PBXFileReference for path exists, it will be returned. Otherwise, one will be created and returned. """ (group, hierarchical) = self.RootGroupForPath(path) return group.AddOrGetFileByPath(path, hierarchical) def RootGroupsTakeOverOnlyChildren(self, recurse=False): """Calls TakeOverOnlyChild for all groups in the main group.""" for group in self._properties["mainGroup"]._properties["children"]: if isinstance(group, PBXGroup): group.TakeOverOnlyChild(recurse) def SortGroups(self): # Sort the children of the mainGroup (like "Source" and "Products") # according to their defined order. self._properties["mainGroup"]._properties["children"] = sorted( self._properties["mainGroup"]._properties["children"], key=cmp_to_key(lambda x, y: x.CompareRootGroup(y)), ) # Sort everything else by putting group before files, and going # alphabetically by name within sections of groups and files. SortGroup # is recursive. for group in self._properties["mainGroup"]._properties["children"]: if not isinstance(group, PBXGroup): continue if group.Name() == "Products": # The Products group is a special case. Instead of sorting # alphabetically, sort things in the order of the targets that # produce the products. To do this, just build up a new list of # products based on the targets. products = [] for target in self._properties["targets"]: if not isinstance(target, PBXNativeTarget): continue product = target._properties["productReference"] # Make sure that the product is already in the products group. assert product in group._properties["children"] products.append(product) # Make sure that this process doesn't miss anything that was already # in the products group. assert len(products) == len(group._properties["children"]) group._properties["children"] = products else: group.SortGroup() def AddOrGetProjectReference(self, other_pbxproject): """Add a reference to another project file (via PBXProject object) to this one. Returns [ProductGroup, ProjectRef]. ProductGroup is a PBXGroup object in this project file that contains a PBXReferenceProxy object for each product of each PBXNativeTarget in the other project file. ProjectRef is a PBXFileReference to the other project file. If this project file already references the other project file, the existing ProductGroup and ProjectRef are returned. The ProductGroup will still be updated if necessary. """ if "projectReferences" not in self._properties: self._properties["projectReferences"] = [] product_group = None project_ref = None if other_pbxproject not in self._other_pbxprojects: # This project file isn't yet linked to the other one. Establish the # link. product_group = PBXGroup({"name": "Products"}) # ProductGroup is strong. product_group.parent = self # There's nothing unique about this PBXGroup, and if left alone, it will # wind up with the same set of hashables as all other PBXGroup objects # owned by the projectReferences list. Add the hashables of the # remote PBXProject that it's related to. product_group._hashables.extend(other_pbxproject.Hashables()) # The other project reports its path as relative to the same directory # that this project's path is relative to. The other project's path # is not necessarily already relative to this project. Figure out the # pathname that this project needs to use to refer to the other one. this_path = posixpath.dirname(self.Path()) projectDirPath = self.GetProperty("projectDirPath") if projectDirPath: if posixpath.isabs(projectDirPath[0]): this_path = projectDirPath else: this_path = posixpath.join(this_path, projectDirPath) other_path = gyp.common.RelativePath(other_pbxproject.Path(), this_path) # ProjectRef is weak (it's owned by the mainGroup hierarchy). project_ref = PBXFileReference( { "lastKnownFileType": "wrapper.pb-project", "path": other_path, "sourceTree": "SOURCE_ROOT", } ) self.ProjectsGroup().AppendChild(project_ref) ref_dict = {"ProductGroup": product_group, "ProjectRef": project_ref} self._other_pbxprojects[other_pbxproject] = ref_dict self.AppendProperty("projectReferences", ref_dict) # Xcode seems to sort this list case-insensitively self._properties["projectReferences"] = sorted( self._properties["projectReferences"], key=lambda x: x["ProjectRef"].Name().lower() ) else: # The link already exists. Pull out the relevnt data. project_ref_dict = self._other_pbxprojects[other_pbxproject] product_group = project_ref_dict["ProductGroup"] project_ref = project_ref_dict["ProjectRef"] self._SetUpProductReferences(other_pbxproject, product_group, project_ref) inherit_unique_symroot = self._AllSymrootsUnique(other_pbxproject, False) targets = other_pbxproject.GetProperty("targets") if all(self._AllSymrootsUnique(t, inherit_unique_symroot) for t in targets): dir_path = project_ref._properties["path"] product_group._hashables.extend(dir_path) return [product_group, project_ref] def _AllSymrootsUnique(self, target, inherit_unique_symroot): # Returns True if all configurations have a unique 'SYMROOT' attribute. # The value of inherit_unique_symroot decides, if a configuration is assumed # to inherit a unique 'SYMROOT' attribute from its parent, if it doesn't # define an explicit value for 'SYMROOT'. symroots = self._DefinedSymroots(target) for s in self._DefinedSymroots(target): if ( s is not None and not self._IsUniqueSymrootForTarget(s) or s is None and not inherit_unique_symroot ): return False return True if symroots else inherit_unique_symroot def _DefinedSymroots(self, target): # Returns all values for the 'SYMROOT' attribute defined in all # configurations for this target. If any configuration doesn't define the # 'SYMROOT' attribute, None is added to the returned set. If all # configurations don't define the 'SYMROOT' attribute, an empty set is # returned. config_list = target.GetProperty("buildConfigurationList") symroots = set() for config in config_list.GetProperty("buildConfigurations"): setting = config.GetProperty("buildSettings") if "SYMROOT" in setting: symroots.add(setting["SYMROOT"]) else: symroots.add(None) if len(symroots) == 1 and None in symroots: return set() return symroots def _IsUniqueSymrootForTarget(self, symroot): # This method returns True if all configurations in target contain a # 'SYMROOT' attribute that is unique for the given target. A value is # unique, if the Xcode macro '$SRCROOT' appears in it in any form. uniquifier = ["$SRCROOT", "$(SRCROOT)"] if any(x in symroot for x in uniquifier): return True return False def _SetUpProductReferences(self, other_pbxproject, product_group, project_ref): # TODO(mark): This only adds references to products in other_pbxproject # when they don't exist in this pbxproject. Perhaps it should also # remove references from this pbxproject that are no longer present in # other_pbxproject. Perhaps it should update various properties if they # change. for target in other_pbxproject._properties["targets"]: if not isinstance(target, PBXNativeTarget): continue other_fileref = target._properties["productReference"] if product_group.GetChildByRemoteObject(other_fileref) is None: # Xcode sets remoteInfo to the name of the target and not the name # of its product, despite this proxy being a reference to the product. container_item = PBXContainerItemProxy( { "containerPortal": project_ref, "proxyType": 2, "remoteGlobalIDString": other_fileref, "remoteInfo": target.Name(), } ) # TODO(mark): Does sourceTree get copied straight over from the other # project? Can the other project ever have lastKnownFileType here # instead of explicitFileType? (Use it if so?) Can path ever be # unset? (I don't think so.) Can other_fileref have name set, and # does it impact the PBXReferenceProxy if so? These are the questions # that perhaps will be answered one day. reference_proxy = PBXReferenceProxy( { "fileType": other_fileref._properties["explicitFileType"], "path": other_fileref._properties["path"], "sourceTree": other_fileref._properties["sourceTree"], "remoteRef": container_item, } ) product_group.AppendChild(reference_proxy) def SortRemoteProductReferences(self): # For each remote project file, sort the associated ProductGroup in the # same order that the targets are sorted in the remote project file. This # is the sort order used by Xcode. def CompareProducts(x, y, remote_products): # x and y are PBXReferenceProxy objects. Go through their associated # PBXContainerItem to get the remote PBXFileReference, which will be # present in the remote_products list. x_remote = x._properties["remoteRef"]._properties["remoteGlobalIDString"] y_remote = y._properties["remoteRef"]._properties["remoteGlobalIDString"] x_index = remote_products.index(x_remote) y_index = remote_products.index(y_remote) # Use the order of each remote PBXFileReference in remote_products to # determine the sort order. return cmp(x_index, y_index) for other_pbxproject, ref_dict in self._other_pbxprojects.items(): # Build up a list of products in the remote project file, ordered the # same as the targets that produce them. remote_products = [] for target in other_pbxproject._properties["targets"]: if not isinstance(target, PBXNativeTarget): continue remote_products.append(target._properties["productReference"]) # Sort the PBXReferenceProxy children according to the list of remote # products. product_group = ref_dict["ProductGroup"] product_group._properties["children"] = sorted( product_group._properties["children"], key=cmp_to_key( lambda x, y, rp=remote_products: CompareProducts(x, y, rp)), ) class XCProjectFile(XCObject): _schema = XCObject._schema.copy() _schema.update( { "archiveVersion": [0, int, 0, 1, 1], "classes": [0, dict, 0, 1, {}], "objectVersion": [0, int, 0, 1, 46], "rootObject": [0, PBXProject, 1, 1], } ) def ComputeIDs(self, recursive=True, overwrite=True, hash=None): # Although XCProjectFile is implemented here as an XCObject, it's not a # proper object in the Xcode sense, and it certainly doesn't have its own # ID. Pass through an attempt to update IDs to the real root object. if recursive: self._properties["rootObject"].ComputeIDs(recursive, overwrite, hash) def Print(self, file=sys.stdout): self.VerifyHasRequiredProperties() # Add the special "objects" property, which will be caught and handled # separately during printing. This structure allows a fairly standard # loop do the normal printing. self._properties["objects"] = {} self._XCPrint(file, 0, "// !$*UTF8*$!\n") if self._should_print_single_line: self._XCPrint(file, 0, "{ ") else: self._XCPrint(file, 0, "{\n") for property, value in sorted( self._properties.items() ): if property == "objects": self._PrintObjects(file) else: self._XCKVPrint(file, 1, property, value) self._XCPrint(file, 0, "}\n") del self._properties["objects"] def _PrintObjects(self, file): if self._should_print_single_line: self._XCPrint(file, 0, "objects = {") else: self._XCPrint(file, 1, "objects = {\n") objects_by_class = {} for object in self.Descendants(): if object == self: continue class_name = object.__class__.__name__ if class_name not in objects_by_class: objects_by_class[class_name] = [] objects_by_class[class_name].append(object) for class_name in sorted(objects_by_class): self._XCPrint(file, 0, "\n") self._XCPrint(file, 0, "/* Begin " + class_name + " section */\n") for object in sorted( objects_by_class[class_name], key=attrgetter("id") ): object.Print(file) self._XCPrint(file, 0, "/* End " + class_name + " section */\n") if self._should_print_single_line: self._XCPrint(file, 0, "}; ") else: self._XCPrint(file, 1, "};\n") PK ~\0+node-gyp/gyp/pylib/packaging/_structures.pynu[# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. class InfinityType: def __repr__(self) -> str: return "Infinity" def __hash__(self) -> int: return hash(repr(self)) def __lt__(self, other: object) -> bool: return False def __le__(self, other: object) -> bool: return False def __eq__(self, other: object) -> bool: return isinstance(other, self.__class__) def __gt__(self, other: object) -> bool: return True def __ge__(self, other: object) -> bool: return True def __neg__(self: object) -> "NegativeInfinityType": return NegativeInfinity Infinity = InfinityType() class NegativeInfinityType: def __repr__(self) -> str: return "-Infinity" def __hash__(self) -> int: return hash(repr(self)) def __lt__(self, other: object) -> bool: return True def __le__(self, other: object) -> bool: return True def __eq__(self, other: object) -> bool: return isinstance(other, self.__class__) def __gt__(self, other: object) -> bool: return False def __ge__(self, other: object) -> bool: return False def __neg__(self: object) -> InfinityType: return Infinity NegativeInfinity = NegativeInfinityType() PK ~\P G@@(node-gyp/gyp/pylib/packaging/LICENSE.BSDnu[Copyright (c) Donald Stufft and individual contributors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. PK ~\OGG$node-gyp/gyp/pylib/packaging/tags.pynu[# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. import logging import platform import struct import subprocess import sys import sysconfig from importlib.machinery import EXTENSION_SUFFIXES from typing import ( Dict, FrozenSet, Iterable, Iterator, List, Optional, Sequence, Tuple, Union, cast, ) from . import _manylinux, _musllinux logger = logging.getLogger(__name__) PythonVersion = Sequence[int] MacVersion = Tuple[int, int] INTERPRETER_SHORT_NAMES: Dict[str, str] = { "python": "py", # Generic. "cpython": "cp", "pypy": "pp", "ironpython": "ip", "jython": "jy", } _32_BIT_INTERPRETER = struct.calcsize("P") == 4 class Tag: """ A representation of the tag triple for a wheel. Instances are considered immutable and thus are hashable. Equality checking is also supported. """ __slots__ = ["_interpreter", "_abi", "_platform", "_hash"] def __init__(self, interpreter: str, abi: str, platform: str) -> None: self._interpreter = interpreter.lower() self._abi = abi.lower() self._platform = platform.lower() # The __hash__ of every single element in a Set[Tag] will be evaluated each time # that a set calls its `.disjoint()` method, which may be called hundreds of # times when scanning a page of links for packages with tags matching that # Set[Tag]. Pre-computing the value here produces significant speedups for # downstream consumers. self._hash = hash((self._interpreter, self._abi, self._platform)) @property def interpreter(self) -> str: return self._interpreter @property def abi(self) -> str: return self._abi @property def platform(self) -> str: return self._platform def __eq__(self, other: object) -> bool: if not isinstance(other, Tag): return NotImplemented return ( (self._hash == other._hash) # Short-circuit ASAP for perf reasons. and (self._platform == other._platform) and (self._abi == other._abi) and (self._interpreter == other._interpreter) ) def __hash__(self) -> int: return self._hash def __str__(self) -> str: return f"{self._interpreter}-{self._abi}-{self._platform}" def __repr__(self) -> str: return f"<{self} @ {id(self)}>" def parse_tag(tag: str) -> FrozenSet[Tag]: """ Parses the provided tag (e.g. `py3-none-any`) into a frozenset of Tag instances. Returning a set is required due to the possibility that the tag is a compressed tag set. """ tags = set() interpreters, abis, platforms = tag.split("-") for interpreter in interpreters.split("."): for abi in abis.split("."): for platform_ in platforms.split("."): tags.add(Tag(interpreter, abi, platform_)) return frozenset(tags) def _get_config_var(name: str, warn: bool = False) -> Union[int, str, None]: value: Union[int, str, None] = sysconfig.get_config_var(name) if value is None and warn: logger.debug( "Config variable '%s' is unset, Python ABI tag may be incorrect", name ) return value def _normalize_string(string: str) -> str: return string.replace(".", "_").replace("-", "_").replace(" ", "_") def _abi3_applies(python_version: PythonVersion) -> bool: """ Determine if the Python version supports abi3. PEP 384 was first implemented in Python 3.2. """ return len(python_version) > 1 and tuple(python_version) >= (3, 2) def _cpython_abis(py_version: PythonVersion, warn: bool = False) -> List[str]: py_version = tuple(py_version) # To allow for version comparison. abis = [] version = _version_nodot(py_version[:2]) debug = pymalloc = ucs4 = "" with_debug = _get_config_var("Py_DEBUG", warn) has_refcount = hasattr(sys, "gettotalrefcount") # Windows doesn't set Py_DEBUG, so checking for support of debug-compiled # extension modules is the best option. # https://github.com/pypa/pip/issues/3383#issuecomment-173267692 has_ext = "_d.pyd" in EXTENSION_SUFFIXES if with_debug or (with_debug is None and (has_refcount or has_ext)): debug = "d" if py_version < (3, 8): with_pymalloc = _get_config_var("WITH_PYMALLOC", warn) if with_pymalloc or with_pymalloc is None: pymalloc = "m" if py_version < (3, 3): unicode_size = _get_config_var("Py_UNICODE_SIZE", warn) if unicode_size == 4 or ( unicode_size is None and sys.maxunicode == 0x10FFFF ): ucs4 = "u" elif debug: # Debug builds can also load "normal" extension modules. # We can also assume no UCS-4 or pymalloc requirement. abis.append(f"cp{version}") abis.insert( 0, "cp{version}{debug}{pymalloc}{ucs4}".format( version=version, debug=debug, pymalloc=pymalloc, ucs4=ucs4 ), ) return abis def cpython_tags( python_version: Optional[PythonVersion] = None, abis: Optional[Iterable[str]] = None, platforms: Optional[Iterable[str]] = None, *, warn: bool = False, ) -> Iterator[Tag]: """ Yields the tags for a CPython interpreter. The tags consist of: - cp-- - cp-abi3- - cp-none- - cp-abi3- # Older Python versions down to 3.2. If python_version only specifies a major version then user-provided ABIs and the 'none' ABItag will be used. If 'abi3' or 'none' are specified in 'abis' then they will be yielded at their normal position and not at the beginning. """ if not python_version: python_version = sys.version_info[:2] interpreter = f"cp{_version_nodot(python_version[:2])}" if abis is None: if len(python_version) > 1: abis = _cpython_abis(python_version, warn) else: abis = [] abis = list(abis) # 'abi3' and 'none' are explicitly handled later. for explicit_abi in ("abi3", "none"): try: abis.remove(explicit_abi) except ValueError: pass platforms = list(platforms or platform_tags()) for abi in abis: for platform_ in platforms: yield Tag(interpreter, abi, platform_) if _abi3_applies(python_version): yield from (Tag(interpreter, "abi3", platform_) for platform_ in platforms) yield from (Tag(interpreter, "none", platform_) for platform_ in platforms) if _abi3_applies(python_version): for minor_version in range(python_version[1] - 1, 1, -1): for platform_ in platforms: interpreter = "cp{version}".format( version=_version_nodot((python_version[0], minor_version)) ) yield Tag(interpreter, "abi3", platform_) def _generic_abi() -> List[str]: """ Return the ABI tag based on EXT_SUFFIX. """ # The following are examples of `EXT_SUFFIX`. # We want to keep the parts which are related to the ABI and remove the # parts which are related to the platform: # - linux: '.cpython-310-x86_64-linux-gnu.so' => cp310 # - mac: '.cpython-310-darwin.so' => cp310 # - win: '.cp310-win_amd64.pyd' => cp310 # - win: '.pyd' => cp37 (uses _cpython_abis()) # - pypy: '.pypy38-pp73-x86_64-linux-gnu.so' => pypy38_pp73 # - graalpy: '.graalpy-38-native-x86_64-darwin.dylib' # => graalpy_38_native ext_suffix = _get_config_var("EXT_SUFFIX", warn=True) if not isinstance(ext_suffix, str) or ext_suffix[0] != ".": raise SystemError("invalid sysconfig.get_config_var('EXT_SUFFIX')") parts = ext_suffix.split(".") if len(parts) < 3: # CPython3.7 and earlier uses ".pyd" on Windows. return _cpython_abis(sys.version_info[:2]) soabi = parts[1] if soabi.startswith("cpython"): # non-windows abi = "cp" + soabi.split("-")[1] elif soabi.startswith("cp"): # windows abi = soabi.split("-")[0] elif soabi.startswith("pypy"): abi = "-".join(soabi.split("-")[:2]) elif soabi.startswith("graalpy"): abi = "-".join(soabi.split("-")[:3]) elif soabi: # pyston, ironpython, others? abi = soabi else: return [] return [_normalize_string(abi)] def generic_tags( interpreter: Optional[str] = None, abis: Optional[Iterable[str]] = None, platforms: Optional[Iterable[str]] = None, *, warn: bool = False, ) -> Iterator[Tag]: """ Yields the tags for a generic interpreter. The tags consist of: - -- The "none" ABI will be added if it was not explicitly provided. """ if not interpreter: interp_name = interpreter_name() interp_version = interpreter_version(warn=warn) interpreter = "".join([interp_name, interp_version]) if abis is None: abis = _generic_abi() else: abis = list(abis) platforms = list(platforms or platform_tags()) if "none" not in abis: abis.append("none") for abi in abis: for platform_ in platforms: yield Tag(interpreter, abi, platform_) def _py_interpreter_range(py_version: PythonVersion) -> Iterator[str]: """ Yields Python versions in descending order. After the latest version, the major-only version will be yielded, and then all previous versions of that major version. """ if len(py_version) > 1: yield f"py{_version_nodot(py_version[:2])}" yield f"py{py_version[0]}" if len(py_version) > 1: for minor in range(py_version[1] - 1, -1, -1): yield f"py{_version_nodot((py_version[0], minor))}" def compatible_tags( python_version: Optional[PythonVersion] = None, interpreter: Optional[str] = None, platforms: Optional[Iterable[str]] = None, ) -> Iterator[Tag]: """ Yields the sequence of tags that are compatible with a specific version of Python. The tags consist of: - py*-none- - -none-any # ... if `interpreter` is provided. - py*-none-any """ if not python_version: python_version = sys.version_info[:2] platforms = list(platforms or platform_tags()) for version in _py_interpreter_range(python_version): for platform_ in platforms: yield Tag(version, "none", platform_) if interpreter: yield Tag(interpreter, "none", "any") for version in _py_interpreter_range(python_version): yield Tag(version, "none", "any") def _mac_arch(arch: str, is_32bit: bool = _32_BIT_INTERPRETER) -> str: if not is_32bit: return arch if arch.startswith("ppc"): return "ppc" return "i386" def _mac_binary_formats(version: MacVersion, cpu_arch: str) -> List[str]: formats = [cpu_arch] if cpu_arch == "x86_64": if version < (10, 4): return [] formats.extend(["intel", "fat64", "fat32"]) elif cpu_arch == "i386": if version < (10, 4): return [] formats.extend(["intel", "fat32", "fat"]) elif cpu_arch == "ppc64": # TODO: Need to care about 32-bit PPC for ppc64 through 10.2? if version > (10, 5) or version < (10, 4): return [] formats.append("fat64") elif cpu_arch == "ppc": if version > (10, 6): return [] formats.extend(["fat32", "fat"]) if cpu_arch in {"arm64", "x86_64"}: formats.append("universal2") if cpu_arch in {"x86_64", "i386", "ppc64", "ppc", "intel"}: formats.append("universal") return formats def mac_platforms( version: Optional[MacVersion] = None, arch: Optional[str] = None ) -> Iterator[str]: """ Yields the platform tags for a macOS system. The `version` parameter is a two-item tuple specifying the macOS version to generate platform tags for. The `arch` parameter is the CPU architecture to generate platform tags for. Both parameters default to the appropriate value for the current system. """ version_str, _, cpu_arch = platform.mac_ver() if version is None: version = cast("MacVersion", tuple(map(int, version_str.split(".")[:2]))) if version == (10, 16): # When built against an older macOS SDK, Python will report macOS 10.16 # instead of the real version. version_str = subprocess.run( [ sys.executable, "-sS", "-c", "import platform; print(platform.mac_ver()[0])", ], check=True, env={"SYSTEM_VERSION_COMPAT": "0"}, stdout=subprocess.PIPE, text=True, ).stdout version = cast("MacVersion", tuple(map(int, version_str.split(".")[:2]))) else: version = version if arch is None: arch = _mac_arch(cpu_arch) else: arch = arch if (10, 0) <= version and version < (11, 0): # Prior to Mac OS 11, each yearly release of Mac OS bumped the # "minor" version number. The major version was always 10. for minor_version in range(version[1], -1, -1): compat_version = 10, minor_version binary_formats = _mac_binary_formats(compat_version, arch) for binary_format in binary_formats: yield "macosx_{major}_{minor}_{binary_format}".format( major=10, minor=minor_version, binary_format=binary_format ) if version >= (11, 0): # Starting with Mac OS 11, each yearly release bumps the major version # number. The minor versions are now the midyear updates. for major_version in range(version[0], 10, -1): compat_version = major_version, 0 binary_formats = _mac_binary_formats(compat_version, arch) for binary_format in binary_formats: yield "macosx_{major}_{minor}_{binary_format}".format( major=major_version, minor=0, binary_format=binary_format ) if version >= (11, 0): # Mac OS 11 on x86_64 is compatible with binaries from previous releases. # Arm64 support was introduced in 11.0, so no Arm binaries from previous # releases exist. # # However, the "universal2" binary format can have a # macOS version earlier than 11.0 when the x86_64 part of the binary supports # that version of macOS. if arch == "x86_64": for minor_version in range(16, 3, -1): compat_version = 10, minor_version binary_formats = _mac_binary_formats(compat_version, arch) for binary_format in binary_formats: yield "macosx_{major}_{minor}_{binary_format}".format( major=compat_version[0], minor=compat_version[1], binary_format=binary_format, ) else: for minor_version in range(16, 3, -1): compat_version = 10, minor_version binary_format = "universal2" yield "macosx_{major}_{minor}_{binary_format}".format( major=compat_version[0], minor=compat_version[1], binary_format=binary_format, ) def _linux_platforms(is_32bit: bool = _32_BIT_INTERPRETER) -> Iterator[str]: linux = _normalize_string(sysconfig.get_platform()) if not linux.startswith("linux_"): # we should never be here, just yield the sysconfig one and return yield linux return if is_32bit: if linux == "linux_x86_64": linux = "linux_i686" elif linux == "linux_aarch64": linux = "linux_armv8l" _, arch = linux.split("_", 1) archs = {"armv8l": ["armv8l", "armv7l"]}.get(arch, [arch]) yield from _manylinux.platform_tags(archs) yield from _musllinux.platform_tags(archs) for arch in archs: yield f"linux_{arch}" def _generic_platforms() -> Iterator[str]: yield _normalize_string(sysconfig.get_platform()) def platform_tags() -> Iterator[str]: """ Provides the platform tags for this installation. """ if platform.system() == "Darwin": return mac_platforms() elif platform.system() == "Linux": return _linux_platforms() else: return _generic_platforms() def interpreter_name() -> str: """ Returns the name of the running interpreter. Some implementations have a reserved, two-letter abbreviation which will be returned when appropriate. """ name = sys.implementation.name return INTERPRETER_SHORT_NAMES.get(name) or name def interpreter_version(*, warn: bool = False) -> str: """ Returns the version of the running interpreter. """ version = _get_config_var("py_version_nodot", warn=warn) if version: version = str(version) else: version = _version_nodot(sys.version_info[:2]) return version def _version_nodot(version: PythonVersion) -> str: return "".join(map(str, version)) def sys_tags(*, warn: bool = False) -> Iterator[Tag]: """ Returns the sequence of tag triples for the running interpreter. The order of the sequence corresponds to priority order for the interpreter, from most to least important. """ interp_name = interpreter_name() if interp_name == "cp": yield from cpython_tags(warn=warn) else: yield from generic_tags() if interp_name == "pp": interp = "pp3" elif interp_name == "cp": interp = "cp" + interpreter_version(warn=warn) else: interp = None yield from compatible_tags(interpreter=interp) PK ~\M  'node-gyp/gyp/pylib/packaging/markers.pynu[# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. import operator import os import platform import sys from typing import Any, Callable, Dict, List, Optional, Tuple, Union from ._parser import ( MarkerAtom, MarkerList, Op, Value, Variable, parse_marker as _parse_marker, ) from ._tokenizer import ParserSyntaxError from .specifiers import InvalidSpecifier, Specifier from .utils import canonicalize_name __all__ = [ "InvalidMarker", "UndefinedComparison", "UndefinedEnvironmentName", "Marker", "default_environment", ] Operator = Callable[[str, str], bool] class InvalidMarker(ValueError): """ An invalid marker was found, users should refer to PEP 508. """ class UndefinedComparison(ValueError): """ An invalid operation was attempted on a value that doesn't support it. """ class UndefinedEnvironmentName(ValueError): """ A name was attempted to be used that does not exist inside of the environment. """ def _normalize_extra_values(results: Any) -> Any: """ Normalize extra values. """ if isinstance(results[0], tuple): lhs, op, rhs = results[0] if isinstance(lhs, Variable) and lhs.value == "extra": normalized_extra = canonicalize_name(rhs.value) rhs = Value(normalized_extra) elif isinstance(rhs, Variable) and rhs.value == "extra": normalized_extra = canonicalize_name(lhs.value) lhs = Value(normalized_extra) results[0] = lhs, op, rhs return results def _format_marker( marker: Union[List[str], MarkerAtom, str], first: Optional[bool] = True ) -> str: assert isinstance(marker, (list, tuple, str)) # Sometimes we have a structure like [[...]] which is a single item list # where the single item is itself it's own list. In that case we want skip # the rest of this function so that we don't get extraneous () on the # outside. if ( isinstance(marker, list) and len(marker) == 1 and isinstance(marker[0], (list, tuple)) ): return _format_marker(marker[0]) if isinstance(marker, list): inner = (_format_marker(m, first=False) for m in marker) if first: return " ".join(inner) else: return "(" + " ".join(inner) + ")" elif isinstance(marker, tuple): return " ".join([m.serialize() for m in marker]) else: return marker _operators: Dict[str, Operator] = { "in": lambda lhs, rhs: lhs in rhs, "not in": lambda lhs, rhs: lhs not in rhs, "<": operator.lt, "<=": operator.le, "==": operator.eq, "!=": operator.ne, ">=": operator.ge, ">": operator.gt, } def _eval_op(lhs: str, op: Op, rhs: str) -> bool: try: spec = Specifier("".join([op.serialize(), rhs])) except InvalidSpecifier: pass else: return spec.contains(lhs, prereleases=True) oper: Optional[Operator] = _operators.get(op.serialize()) if oper is None: raise UndefinedComparison(f"Undefined {op!r} on {lhs!r} and {rhs!r}.") return oper(lhs, rhs) def _normalize(*values: str, key: str) -> Tuple[str, ...]: # PEP 685 – Comparison of extra names for optional distribution dependencies # https://peps.python.org/pep-0685/ # > When comparing extra names, tools MUST normalize the names being # > compared using the semantics outlined in PEP 503 for names if key == "extra": return tuple(canonicalize_name(v) for v in values) # other environment markers don't have such standards return values def _evaluate_markers(markers: MarkerList, environment: Dict[str, str]) -> bool: groups: List[List[bool]] = [[]] for marker in markers: assert isinstance(marker, (list, tuple, str)) if isinstance(marker, list): groups[-1].append(_evaluate_markers(marker, environment)) elif isinstance(marker, tuple): lhs, op, rhs = marker if isinstance(lhs, Variable): environment_key = lhs.value lhs_value = environment[environment_key] rhs_value = rhs.value else: lhs_value = lhs.value environment_key = rhs.value rhs_value = environment[environment_key] lhs_value, rhs_value = _normalize(lhs_value, rhs_value, key=environment_key) groups[-1].append(_eval_op(lhs_value, op, rhs_value)) else: assert marker in ["and", "or"] if marker == "or": groups.append([]) return any(all(item) for item in groups) def format_full_version(info: "sys._version_info") -> str: version = "{0.major}.{0.minor}.{0.micro}".format(info) kind = info.releaselevel if kind != "final": version += kind[0] + str(info.serial) return version def default_environment() -> Dict[str, str]: iver = format_full_version(sys.implementation.version) implementation_name = sys.implementation.name return { "implementation_name": implementation_name, "implementation_version": iver, "os_name": os.name, "platform_machine": platform.machine(), "platform_release": platform.release(), "platform_system": platform.system(), "platform_version": platform.version(), "python_full_version": platform.python_version(), "platform_python_implementation": platform.python_implementation(), "python_version": ".".join(platform.python_version_tuple()[:2]), "sys_platform": sys.platform, } class Marker: def __init__(self, marker: str) -> None: # Note: We create a Marker object without calling this constructor in # packaging.requirements.Requirement. If any additional logic is # added here, make sure to mirror/adapt Requirement. try: self._markers = _normalize_extra_values(_parse_marker(marker)) # The attribute `_markers` can be described in terms of a recursive type: # MarkerList = List[Union[Tuple[Node, ...], str, MarkerList]] # # For example, the following expression: # python_version > "3.6" or (python_version == "3.6" and os_name == "unix") # # is parsed into: # [ # (, ')>, ), # 'and', # [ # (, , ), # 'or', # (, , ) # ] # ] except ParserSyntaxError as e: raise InvalidMarker(str(e)) from e def __str__(self) -> str: return _format_marker(self._markers) def __repr__(self) -> str: return f"" def __hash__(self) -> int: return hash((self.__class__.__name__, str(self))) def __eq__(self, other: Any) -> bool: if not isinstance(other, Marker): return NotImplemented return str(self) == str(other) def evaluate(self, environment: Optional[Dict[str, str]] = None) -> bool: """Evaluate a marker. Return the boolean from evaluating the given marker against the environment. environment is an optional argument to override all or part of the determined environment. The environment is determined from the current Python process. """ current_environment = default_environment() current_environment["extra"] = "" if environment is not None: current_environment.update(environment) # The API used to allow setting extra to None. We need to handle this # case for backwards compatibility. if current_environment["extra"] is None: current_environment["extra"] = "" return _evaluate_markers(self._markers, current_environment) PK ~\Ҽ$node-gyp/gyp/pylib/packaging/LICENSEnu[This software is made available under the terms of *either* of the licenses found in LICENSE.APACHE or LICENSE.BSD. Contributions to this software is made under the terms of *both* these licenses. PK ~\ (node-gyp/gyp/pylib/packaging/metadata.pynu[import email.feedparser import email.header import email.message import email.parser import email.policy import sys import typing from typing import ( Any, Callable, Dict, Generic, List, Optional, Tuple, Type, Union, cast, ) from . import requirements, specifiers, utils, version as version_module T = typing.TypeVar("T") if sys.version_info[:2] >= (3, 8): # pragma: no cover from typing import Literal, TypedDict else: # pragma: no cover if typing.TYPE_CHECKING: from typing_extensions import Literal, TypedDict else: try: from typing_extensions import Literal, TypedDict except ImportError: class Literal: def __init_subclass__(*_args, **_kwargs): pass class TypedDict: def __init_subclass__(*_args, **_kwargs): pass try: ExceptionGroup except NameError: # pragma: no cover class ExceptionGroup(Exception): # noqa: N818 """A minimal implementation of :external:exc:`ExceptionGroup` from Python 3.11. If :external:exc:`ExceptionGroup` is already defined by Python itself, that version is used instead. """ message: str exceptions: List[Exception] def __init__(self, message: str, exceptions: List[Exception]) -> None: self.message = message self.exceptions = exceptions def __repr__(self) -> str: return f"{self.__class__.__name__}({self.message!r}, {self.exceptions!r})" else: # pragma: no cover ExceptionGroup = ExceptionGroup class InvalidMetadata(ValueError): """A metadata field contains invalid data.""" field: str """The name of the field that contains invalid data.""" def __init__(self, field: str, message: str) -> None: self.field = field super().__init__(message) # The RawMetadata class attempts to make as few assumptions about the underlying # serialization formats as possible. The idea is that as long as a serialization # formats offer some very basic primitives in *some* way then we can support # serializing to and from that format. class RawMetadata(TypedDict, total=False): """A dictionary of raw core metadata. Each field in core metadata maps to a key of this dictionary (when data is provided). The key is lower-case and underscores are used instead of dashes compared to the equivalent core metadata field. Any core metadata field that can be specified multiple times or can hold multiple values in a single field have a key with a plural name. See :class:`Metadata` whose attributes match the keys of this dictionary. Core metadata fields that can be specified multiple times are stored as a list or dict depending on which is appropriate for the field. Any fields which hold multiple values in a single field are stored as a list. """ # Metadata 1.0 - PEP 241 metadata_version: str name: str version: str platforms: List[str] summary: str description: str keywords: List[str] home_page: str author: str author_email: str license: str # Metadata 1.1 - PEP 314 supported_platforms: List[str] download_url: str classifiers: List[str] requires: List[str] provides: List[str] obsoletes: List[str] # Metadata 1.2 - PEP 345 maintainer: str maintainer_email: str requires_dist: List[str] provides_dist: List[str] obsoletes_dist: List[str] requires_python: str requires_external: List[str] project_urls: Dict[str, str] # Metadata 2.0 # PEP 426 attempted to completely revamp the metadata format # but got stuck without ever being able to build consensus on # it and ultimately ended up withdrawn. # # However, a number of tools had started emitting METADATA with # `2.0` Metadata-Version, so for historical reasons, this version # was skipped. # Metadata 2.1 - PEP 566 description_content_type: str provides_extra: List[str] # Metadata 2.2 - PEP 643 dynamic: List[str] # Metadata 2.3 - PEP 685 # No new fields were added in PEP 685, just some edge case were # tightened up to provide better interoptability. _STRING_FIELDS = { "author", "author_email", "description", "description_content_type", "download_url", "home_page", "license", "maintainer", "maintainer_email", "metadata_version", "name", "requires_python", "summary", "version", } _LIST_FIELDS = { "classifiers", "dynamic", "obsoletes", "obsoletes_dist", "platforms", "provides", "provides_dist", "provides_extra", "requires", "requires_dist", "requires_external", "supported_platforms", } _DICT_FIELDS = { "project_urls", } def _parse_keywords(data: str) -> List[str]: """Split a string of comma-separate keyboards into a list of keywords.""" return [k.strip() for k in data.split(",")] def _parse_project_urls(data: List[str]) -> Dict[str, str]: """Parse a list of label/URL string pairings separated by a comma.""" urls = {} for pair in data: # Our logic is slightly tricky here as we want to try and do # *something* reasonable with malformed data. # # The main thing that we have to worry about, is data that does # not have a ',' at all to split the label from the Value. There # isn't a singular right answer here, and we will fail validation # later on (if the caller is validating) so it doesn't *really* # matter, but since the missing value has to be an empty str # and our return value is dict[str, str], if we let the key # be the missing value, then they'd have multiple '' values that # overwrite each other in a accumulating dict. # # The other potentional issue is that it's possible to have the # same label multiple times in the metadata, with no solid "right" # answer with what to do in that case. As such, we'll do the only # thing we can, which is treat the field as unparseable and add it # to our list of unparsed fields. parts = [p.strip() for p in pair.split(",", 1)] parts.extend([""] * (max(0, 2 - len(parts)))) # Ensure 2 items # TODO: The spec doesn't say anything about if the keys should be # considered case sensitive or not... logically they should # be case-preserving and case-insensitive, but doing that # would open up more cases where we might have duplicate # entries. label, url = parts if label in urls: # The label already exists in our set of urls, so this field # is unparseable, and we can just add the whole thing to our # unparseable data and stop processing it. raise KeyError("duplicate labels in project urls") urls[label] = url return urls def _get_payload(msg: email.message.Message, source: Union[bytes, str]) -> str: """Get the body of the message.""" # If our source is a str, then our caller has managed encodings for us, # and we don't need to deal with it. if isinstance(source, str): payload: str = msg.get_payload() return payload # If our source is a bytes, then we're managing the encoding and we need # to deal with it. else: bpayload: bytes = msg.get_payload(decode=True) try: return bpayload.decode("utf8", "strict") except UnicodeDecodeError: raise ValueError("payload in an invalid encoding") # The various parse_FORMAT functions here are intended to be as lenient as # possible in their parsing, while still returning a correctly typed # RawMetadata. # # To aid in this, we also generally want to do as little touching of the # data as possible, except where there are possibly some historic holdovers # that make valid data awkward to work with. # # While this is a lower level, intermediate format than our ``Metadata`` # class, some light touch ups can make a massive difference in usability. # Map METADATA fields to RawMetadata. _EMAIL_TO_RAW_MAPPING = { "author": "author", "author-email": "author_email", "classifier": "classifiers", "description": "description", "description-content-type": "description_content_type", "download-url": "download_url", "dynamic": "dynamic", "home-page": "home_page", "keywords": "keywords", "license": "license", "maintainer": "maintainer", "maintainer-email": "maintainer_email", "metadata-version": "metadata_version", "name": "name", "obsoletes": "obsoletes", "obsoletes-dist": "obsoletes_dist", "platform": "platforms", "project-url": "project_urls", "provides": "provides", "provides-dist": "provides_dist", "provides-extra": "provides_extra", "requires": "requires", "requires-dist": "requires_dist", "requires-external": "requires_external", "requires-python": "requires_python", "summary": "summary", "supported-platform": "supported_platforms", "version": "version", } _RAW_TO_EMAIL_MAPPING = {raw: email for email, raw in _EMAIL_TO_RAW_MAPPING.items()} def parse_email(data: Union[bytes, str]) -> Tuple[RawMetadata, Dict[str, List[str]]]: """Parse a distribution's metadata stored as email headers (e.g. from ``METADATA``). This function returns a two-item tuple of dicts. The first dict is of recognized fields from the core metadata specification. Fields that can be parsed and translated into Python's built-in types are converted appropriately. All other fields are left as-is. Fields that are allowed to appear multiple times are stored as lists. The second dict contains all other fields from the metadata. This includes any unrecognized fields. It also includes any fields which are expected to be parsed into a built-in type but were not formatted appropriately. Finally, any fields that are expected to appear only once but are repeated are included in this dict. """ raw: Dict[str, Union[str, List[str], Dict[str, str]]] = {} unparsed: Dict[str, List[str]] = {} if isinstance(data, str): parsed = email.parser.Parser(policy=email.policy.compat32).parsestr(data) else: parsed = email.parser.BytesParser(policy=email.policy.compat32).parsebytes(data) # We have to wrap parsed.keys() in a set, because in the case of multiple # values for a key (a list), the key will appear multiple times in the # list of keys, but we're avoiding that by using get_all(). for name in frozenset(parsed.keys()): # Header names in RFC are case insensitive, so we'll normalize to all # lower case to make comparisons easier. name = name.lower() # We use get_all() here, even for fields that aren't multiple use, # because otherwise someone could have e.g. two Name fields, and we # would just silently ignore it rather than doing something about it. headers = parsed.get_all(name) or [] # The way the email module works when parsing bytes is that it # unconditionally decodes the bytes as ascii using the surrogateescape # handler. When you pull that data back out (such as with get_all() ), # it looks to see if the str has any surrogate escapes, and if it does # it wraps it in a Header object instead of returning the string. # # As such, we'll look for those Header objects, and fix up the encoding. value = [] # Flag if we have run into any issues processing the headers, thus # signalling that the data belongs in 'unparsed'. valid_encoding = True for h in headers: # It's unclear if this can return more types than just a Header or # a str, so we'll just assert here to make sure. assert isinstance(h, (email.header.Header, str)) # If it's a header object, we need to do our little dance to get # the real data out of it. In cases where there is invalid data # we're going to end up with mojibake, but there's no obvious, good # way around that without reimplementing parts of the Header object # ourselves. # # That should be fine since, if mojibacked happens, this key is # going into the unparsed dict anyways. if isinstance(h, email.header.Header): # The Header object stores it's data as chunks, and each chunk # can be independently encoded, so we'll need to check each # of them. chunks: List[Tuple[bytes, Optional[str]]] = [] for bin, encoding in email.header.decode_header(h): try: bin.decode("utf8", "strict") except UnicodeDecodeError: # Enable mojibake. encoding = "latin1" valid_encoding = False else: encoding = "utf8" chunks.append((bin, encoding)) # Turn our chunks back into a Header object, then let that # Header object do the right thing to turn them into a # string for us. value.append(str(email.header.make_header(chunks))) # This is already a string, so just add it. else: value.append(h) # We've processed all of our values to get them into a list of str, # but we may have mojibake data, in which case this is an unparsed # field. if not valid_encoding: unparsed[name] = value continue raw_name = _EMAIL_TO_RAW_MAPPING.get(name) if raw_name is None: # This is a bit of a weird situation, we've encountered a key that # we don't know what it means, so we don't know whether it's meant # to be a list or not. # # Since we can't really tell one way or another, we'll just leave it # as a list, even though it may be a single item list, because that's # what makes the most sense for email headers. unparsed[name] = value continue # If this is one of our string fields, then we'll check to see if our # value is a list of a single item. If it is then we'll assume that # it was emitted as a single string, and unwrap the str from inside # the list. # # If it's any other kind of data, then we haven't the faintest clue # what we should parse it as, and we have to just add it to our list # of unparsed stuff. if raw_name in _STRING_FIELDS and len(value) == 1: raw[raw_name] = value[0] # If this is one of our list of string fields, then we can just assign # the value, since email *only* has strings, and our get_all() call # above ensures that this is a list. elif raw_name in _LIST_FIELDS: raw[raw_name] = value # Special Case: Keywords # The keywords field is implemented in the metadata spec as a str, # but it conceptually is a list of strings, and is serialized using # ", ".join(keywords), so we'll do some light data massaging to turn # this into what it logically is. elif raw_name == "keywords" and len(value) == 1: raw[raw_name] = _parse_keywords(value[0]) # Special Case: Project-URL # The project urls is implemented in the metadata spec as a list of # specially-formatted strings that represent a key and a value, which # is fundamentally a mapping, however the email format doesn't support # mappings in a sane way, so it was crammed into a list of strings # instead. # # We will do a little light data massaging to turn this into a map as # it logically should be. elif raw_name == "project_urls": try: raw[raw_name] = _parse_project_urls(value) except KeyError: unparsed[name] = value # Nothing that we've done has managed to parse this, so it'll just # throw it in our unparseable data and move on. else: unparsed[name] = value # We need to support getting the Description from the message payload in # addition to getting it from the the headers. This does mean, though, there # is the possibility of it being set both ways, in which case we put both # in 'unparsed' since we don't know which is right. try: payload = _get_payload(parsed, data) except ValueError: unparsed.setdefault("description", []).append( parsed.get_payload(decode=isinstance(data, bytes)) ) else: if payload: # Check to see if we've already got a description, if so then both # it, and this body move to unparseable. if "description" in raw: description_header = cast(str, raw.pop("description")) unparsed.setdefault("description", []).extend( [description_header, payload] ) elif "description" in unparsed: unparsed["description"].append(payload) else: raw["description"] = payload # We need to cast our `raw` to a metadata, because a TypedDict only support # literal key names, but we're computing our key names on purpose, but the # way this function is implemented, our `TypedDict` can only have valid key # names. return cast(RawMetadata, raw), unparsed _NOT_FOUND = object() # Keep the two values in sync. _VALID_METADATA_VERSIONS = ["1.0", "1.1", "1.2", "2.1", "2.2", "2.3"] _MetadataVersion = Literal["1.0", "1.1", "1.2", "2.1", "2.2", "2.3"] _REQUIRED_ATTRS = frozenset(["metadata_version", "name", "version"]) class _Validator(Generic[T]): """Validate a metadata field. All _process_*() methods correspond to a core metadata field. The method is called with the field's raw value. If the raw value is valid it is returned in its "enriched" form (e.g. ``version.Version`` for the ``Version`` field). If the raw value is invalid, :exc:`InvalidMetadata` is raised (with a cause as appropriate). """ name: str raw_name: str added: _MetadataVersion def __init__( self, *, added: _MetadataVersion = "1.0", ) -> None: self.added = added def __set_name__(self, _owner: "Metadata", name: str) -> None: self.name = name self.raw_name = _RAW_TO_EMAIL_MAPPING[name] def __get__(self, instance: "Metadata", _owner: Type["Metadata"]) -> T: # With Python 3.8, the caching can be replaced with functools.cached_property(). # No need to check the cache as attribute lookup will resolve into the # instance's __dict__ before __get__ is called. cache = instance.__dict__ value = instance._raw.get(self.name) # To make the _process_* methods easier, we'll check if the value is None # and if this field is NOT a required attribute, and if both of those # things are true, we'll skip the the converter. This will mean that the # converters never have to deal with the None union. if self.name in _REQUIRED_ATTRS or value is not None: try: converter: Callable[[Any], T] = getattr(self, f"_process_{self.name}") except AttributeError: pass else: value = converter(value) cache[self.name] = value try: del instance._raw[self.name] # type: ignore[misc] except KeyError: pass return cast(T, value) def _invalid_metadata( self, msg: str, cause: Optional[Exception] = None ) -> InvalidMetadata: exc = InvalidMetadata( self.raw_name, msg.format_map({"field": repr(self.raw_name)}) ) exc.__cause__ = cause return exc def _process_metadata_version(self, value: str) -> _MetadataVersion: # Implicitly makes Metadata-Version required. if value not in _VALID_METADATA_VERSIONS: raise self._invalid_metadata(f"{value!r} is not a valid metadata version") return cast(_MetadataVersion, value) def _process_name(self, value: str) -> str: if not value: raise self._invalid_metadata("{field} is a required field") # Validate the name as a side-effect. try: utils.canonicalize_name(value, validate=True) except utils.InvalidName as exc: raise self._invalid_metadata( f"{value!r} is invalid for {{field}}", cause=exc ) else: return value def _process_version(self, value: str) -> version_module.Version: if not value: raise self._invalid_metadata("{field} is a required field") try: return version_module.parse(value) except version_module.InvalidVersion as exc: raise self._invalid_metadata( f"{value!r} is invalid for {{field}}", cause=exc ) def _process_summary(self, value: str) -> str: """Check the field contains no newlines.""" if "\n" in value: raise self._invalid_metadata("{field} must be a single line") return value def _process_description_content_type(self, value: str) -> str: content_types = {"text/plain", "text/x-rst", "text/markdown"} message = email.message.EmailMessage() message["content-type"] = value content_type, parameters = ( # Defaults to `text/plain` if parsing failed. message.get_content_type().lower(), message["content-type"].params, ) # Check if content-type is valid or defaulted to `text/plain` and thus was # not parseable. if content_type not in content_types or content_type not in value.lower(): raise self._invalid_metadata( f"{{field}} must be one of {list(content_types)}, not {value!r}" ) charset = parameters.get("charset", "UTF-8") if charset != "UTF-8": raise self._invalid_metadata( f"{{field}} can only specify the UTF-8 charset, not {list(charset)}" ) markdown_variants = {"GFM", "CommonMark"} variant = parameters.get("variant", "GFM") # Use an acceptable default. if content_type == "text/markdown" and variant not in markdown_variants: raise self._invalid_metadata( f"valid Markdown variants for {{field}} are {list(markdown_variants)}, " f"not {variant!r}", ) return value def _process_dynamic(self, value: List[str]) -> List[str]: for dynamic_field in map(str.lower, value): if dynamic_field in {"name", "version", "metadata-version"}: raise self._invalid_metadata( f"{value!r} is not allowed as a dynamic field" ) elif dynamic_field not in _EMAIL_TO_RAW_MAPPING: raise self._invalid_metadata(f"{value!r} is not a valid dynamic field") return list(map(str.lower, value)) def _process_provides_extra( self, value: List[str], ) -> List[utils.NormalizedName]: normalized_names = [] try: for name in value: normalized_names.append(utils.canonicalize_name(name, validate=True)) except utils.InvalidName as exc: raise self._invalid_metadata( f"{name!r} is invalid for {{field}}", cause=exc ) else: return normalized_names def _process_requires_python(self, value: str) -> specifiers.SpecifierSet: try: return specifiers.SpecifierSet(value) except specifiers.InvalidSpecifier as exc: raise self._invalid_metadata( f"{value!r} is invalid for {{field}}", cause=exc ) def _process_requires_dist( self, value: List[str], ) -> List[requirements.Requirement]: reqs = [] try: for req in value: reqs.append(requirements.Requirement(req)) except requirements.InvalidRequirement as exc: raise self._invalid_metadata(f"{req!r} is invalid for {{field}}", cause=exc) else: return reqs class Metadata: """Representation of distribution metadata. Compared to :class:`RawMetadata`, this class provides objects representing metadata fields instead of only using built-in types. Any invalid metadata will cause :exc:`InvalidMetadata` to be raised (with a :py:attr:`~BaseException.__cause__` attribute as appropriate). """ _raw: RawMetadata @classmethod def from_raw(cls, data: RawMetadata, *, validate: bool = True) -> "Metadata": """Create an instance from :class:`RawMetadata`. If *validate* is true, all metadata will be validated. All exceptions related to validation will be gathered and raised as an :class:`ExceptionGroup`. """ ins = cls() ins._raw = data.copy() # Mutations occur due to caching enriched values. if validate: exceptions: List[Exception] = [] try: metadata_version = ins.metadata_version metadata_age = _VALID_METADATA_VERSIONS.index(metadata_version) except InvalidMetadata as metadata_version_exc: exceptions.append(metadata_version_exc) metadata_version = None # Make sure to check for the fields that are present, the required # fields (so their absence can be reported). fields_to_check = frozenset(ins._raw) | _REQUIRED_ATTRS # Remove fields that have already been checked. fields_to_check -= {"metadata_version"} for key in fields_to_check: try: if metadata_version: # Can't use getattr() as that triggers descriptor protocol which # will fail due to no value for the instance argument. try: field_metadata_version = cls.__dict__[key].added except KeyError: exc = InvalidMetadata(key, f"unrecognized field: {key!r}") exceptions.append(exc) continue field_age = _VALID_METADATA_VERSIONS.index( field_metadata_version ) if field_age > metadata_age: field = _RAW_TO_EMAIL_MAPPING[key] exc = InvalidMetadata( field, "{field} introduced in metadata version " "{field_metadata_version}, not {metadata_version}", ) exceptions.append(exc) continue getattr(ins, key) except InvalidMetadata as exc: exceptions.append(exc) if exceptions: raise ExceptionGroup("invalid metadata", exceptions) return ins @classmethod def from_email( cls, data: Union[bytes, str], *, validate: bool = True ) -> "Metadata": """Parse metadata from email headers. If *validate* is true, the metadata will be validated. All exceptions related to validation will be gathered and raised as an :class:`ExceptionGroup`. """ raw, unparsed = parse_email(data) if validate: exceptions: list[Exception] = [] for unparsed_key in unparsed: if unparsed_key in _EMAIL_TO_RAW_MAPPING: message = f"{unparsed_key!r} has invalid data" else: message = f"unrecognized field: {unparsed_key!r}" exceptions.append(InvalidMetadata(unparsed_key, message)) if exceptions: raise ExceptionGroup("unparsed", exceptions) try: return cls.from_raw(raw, validate=validate) except ExceptionGroup as exc_group: raise ExceptionGroup( "invalid or unparsed metadata", exc_group.exceptions ) from None metadata_version: _Validator[_MetadataVersion] = _Validator() """:external:ref:`core-metadata-metadata-version` (required; validated to be a valid metadata version)""" name: _Validator[str] = _Validator() """:external:ref:`core-metadata-name` (required; validated using :func:`~packaging.utils.canonicalize_name` and its *validate* parameter)""" version: _Validator[version_module.Version] = _Validator() """:external:ref:`core-metadata-version` (required)""" dynamic: _Validator[Optional[List[str]]] = _Validator( added="2.2", ) """:external:ref:`core-metadata-dynamic` (validated against core metadata field names and lowercased)""" platforms: _Validator[Optional[List[str]]] = _Validator() """:external:ref:`core-metadata-platform`""" supported_platforms: _Validator[Optional[List[str]]] = _Validator(added="1.1") """:external:ref:`core-metadata-supported-platform`""" summary: _Validator[Optional[str]] = _Validator() """:external:ref:`core-metadata-summary` (validated to contain no newlines)""" description: _Validator[Optional[str]] = _Validator() # TODO 2.1: can be in body """:external:ref:`core-metadata-description`""" description_content_type: _Validator[Optional[str]] = _Validator(added="2.1") """:external:ref:`core-metadata-description-content-type` (validated)""" keywords: _Validator[Optional[List[str]]] = _Validator() """:external:ref:`core-metadata-keywords`""" home_page: _Validator[Optional[str]] = _Validator() """:external:ref:`core-metadata-home-page`""" download_url: _Validator[Optional[str]] = _Validator(added="1.1") """:external:ref:`core-metadata-download-url`""" author: _Validator[Optional[str]] = _Validator() """:external:ref:`core-metadata-author`""" author_email: _Validator[Optional[str]] = _Validator() """:external:ref:`core-metadata-author-email`""" maintainer: _Validator[Optional[str]] = _Validator(added="1.2") """:external:ref:`core-metadata-maintainer`""" maintainer_email: _Validator[Optional[str]] = _Validator(added="1.2") """:external:ref:`core-metadata-maintainer-email`""" license: _Validator[Optional[str]] = _Validator() """:external:ref:`core-metadata-license`""" classifiers: _Validator[Optional[List[str]]] = _Validator(added="1.1") """:external:ref:`core-metadata-classifier`""" requires_dist: _Validator[Optional[List[requirements.Requirement]]] = _Validator( added="1.2" ) """:external:ref:`core-metadata-requires-dist`""" requires_python: _Validator[Optional[specifiers.SpecifierSet]] = _Validator( added="1.2" ) """:external:ref:`core-metadata-requires-python`""" # Because `Requires-External` allows for non-PEP 440 version specifiers, we # don't do any processing on the values. requires_external: _Validator[Optional[List[str]]] = _Validator(added="1.2") """:external:ref:`core-metadata-requires-external`""" project_urls: _Validator[Optional[Dict[str, str]]] = _Validator(added="1.2") """:external:ref:`core-metadata-project-url`""" # PEP 685 lets us raise an error if an extra doesn't pass `Name` validation # regardless of metadata version. provides_extra: _Validator[Optional[List[utils.NormalizedName]]] = _Validator( added="2.1", ) """:external:ref:`core-metadata-provides-extra`""" provides_dist: _Validator[Optional[List[str]]] = _Validator(added="1.2") """:external:ref:`core-metadata-provides-dist`""" obsoletes_dist: _Validator[Optional[List[str]]] = _Validator(added="1.2") """:external:ref:`core-metadata-obsoletes-dist`""" requires: _Validator[Optional[List[str]]] = _Validator(added="1.1") """``Requires`` (deprecated)""" provides: _Validator[Optional[List[str]]] = _Validator(added="1.1") """``Provides`` (deprecated)""" obsoletes: _Validator[Optional[List[str]]] = _Validator(added="1.1") """``Obsoletes`` (deprecated)""" PK ~\(('node-gyp/gyp/pylib/packaging/_parser.pynu["""Handwritten parser of dependency specifiers. The docstring for each __parse_* function contains ENBF-inspired grammar representing the implementation. """ import ast from typing import Any, List, NamedTuple, Optional, Tuple, Union from ._tokenizer import DEFAULT_RULES, Tokenizer class Node: def __init__(self, value: str) -> None: self.value = value def __str__(self) -> str: return self.value def __repr__(self) -> str: return f"<{self.__class__.__name__}('{self}')>" def serialize(self) -> str: raise NotImplementedError class Variable(Node): def serialize(self) -> str: return str(self) class Value(Node): def serialize(self) -> str: return f'"{self}"' class Op(Node): def serialize(self) -> str: return str(self) MarkerVar = Union[Variable, Value] MarkerItem = Tuple[MarkerVar, Op, MarkerVar] # MarkerAtom = Union[MarkerItem, List["MarkerAtom"]] # MarkerList = List[Union["MarkerList", MarkerAtom, str]] # mypy does not support recursive type definition # https://github.com/python/mypy/issues/731 MarkerAtom = Any MarkerList = List[Any] class ParsedRequirement(NamedTuple): name: str url: str extras: List[str] specifier: str marker: Optional[MarkerList] # -------------------------------------------------------------------------------------- # Recursive descent parser for dependency specifier # -------------------------------------------------------------------------------------- def parse_requirement(source: str) -> ParsedRequirement: return _parse_requirement(Tokenizer(source, rules=DEFAULT_RULES)) def _parse_requirement(tokenizer: Tokenizer) -> ParsedRequirement: """ requirement = WS? IDENTIFIER WS? extras WS? requirement_details """ tokenizer.consume("WS") name_token = tokenizer.expect( "IDENTIFIER", expected="package name at the start of dependency specifier" ) name = name_token.text tokenizer.consume("WS") extras = _parse_extras(tokenizer) tokenizer.consume("WS") url, specifier, marker = _parse_requirement_details(tokenizer) tokenizer.expect("END", expected="end of dependency specifier") return ParsedRequirement(name, url, extras, specifier, marker) def _parse_requirement_details( tokenizer: Tokenizer, ) -> Tuple[str, str, Optional[MarkerList]]: """ requirement_details = AT URL (WS requirement_marker?)? | specifier WS? (requirement_marker)? """ specifier = "" url = "" marker = None if tokenizer.check("AT"): tokenizer.read() tokenizer.consume("WS") url_start = tokenizer.position url = tokenizer.expect("URL", expected="URL after @").text if tokenizer.check("END", peek=True): return (url, specifier, marker) tokenizer.expect("WS", expected="whitespace after URL") # The input might end after whitespace. if tokenizer.check("END", peek=True): return (url, specifier, marker) marker = _parse_requirement_marker( tokenizer, span_start=url_start, after="URL and whitespace" ) else: specifier_start = tokenizer.position specifier = _parse_specifier(tokenizer) tokenizer.consume("WS") if tokenizer.check("END", peek=True): return (url, specifier, marker) marker = _parse_requirement_marker( tokenizer, span_start=specifier_start, after=( "version specifier" if specifier else "name and no valid version specifier" ), ) return (url, specifier, marker) def _parse_requirement_marker( tokenizer: Tokenizer, *, span_start: int, after: str ) -> MarkerList: """ requirement_marker = SEMICOLON marker WS? """ if not tokenizer.check("SEMICOLON"): tokenizer.raise_syntax_error( f"Expected end or semicolon (after {after})", span_start=span_start, ) tokenizer.read() marker = _parse_marker(tokenizer) tokenizer.consume("WS") return marker def _parse_extras(tokenizer: Tokenizer) -> List[str]: """ extras = (LEFT_BRACKET wsp* extras_list? wsp* RIGHT_BRACKET)? """ if not tokenizer.check("LEFT_BRACKET", peek=True): return [] with tokenizer.enclosing_tokens( "LEFT_BRACKET", "RIGHT_BRACKET", around="extras", ): tokenizer.consume("WS") extras = _parse_extras_list(tokenizer) tokenizer.consume("WS") return extras def _parse_extras_list(tokenizer: Tokenizer) -> List[str]: """ extras_list = identifier (wsp* ',' wsp* identifier)* """ extras: List[str] = [] if not tokenizer.check("IDENTIFIER"): return extras extras.append(tokenizer.read().text) while True: tokenizer.consume("WS") if tokenizer.check("IDENTIFIER", peek=True): tokenizer.raise_syntax_error("Expected comma between extra names") elif not tokenizer.check("COMMA"): break tokenizer.read() tokenizer.consume("WS") extra_token = tokenizer.expect("IDENTIFIER", expected="extra name after comma") extras.append(extra_token.text) return extras def _parse_specifier(tokenizer: Tokenizer) -> str: """ specifier = LEFT_PARENTHESIS WS? version_many WS? RIGHT_PARENTHESIS | WS? version_many WS? """ with tokenizer.enclosing_tokens( "LEFT_PARENTHESIS", "RIGHT_PARENTHESIS", around="version specifier", ): tokenizer.consume("WS") parsed_specifiers = _parse_version_many(tokenizer) tokenizer.consume("WS") return parsed_specifiers def _parse_version_many(tokenizer: Tokenizer) -> str: """ version_many = (SPECIFIER (WS? COMMA WS? SPECIFIER)*)? """ parsed_specifiers = "" while tokenizer.check("SPECIFIER"): span_start = tokenizer.position parsed_specifiers += tokenizer.read().text if tokenizer.check("VERSION_PREFIX_TRAIL", peek=True): tokenizer.raise_syntax_error( ".* suffix can only be used with `==` or `!=` operators", span_start=span_start, span_end=tokenizer.position + 1, ) if tokenizer.check("VERSION_LOCAL_LABEL_TRAIL", peek=True): tokenizer.raise_syntax_error( "Local version label can only be used with `==` or `!=` operators", span_start=span_start, span_end=tokenizer.position, ) tokenizer.consume("WS") if not tokenizer.check("COMMA"): break parsed_specifiers += tokenizer.read().text tokenizer.consume("WS") return parsed_specifiers # -------------------------------------------------------------------------------------- # Recursive descent parser for marker expression # -------------------------------------------------------------------------------------- def parse_marker(source: str) -> MarkerList: return _parse_full_marker(Tokenizer(source, rules=DEFAULT_RULES)) def _parse_full_marker(tokenizer: Tokenizer) -> MarkerList: retval = _parse_marker(tokenizer) tokenizer.expect("END", expected="end of marker expression") return retval def _parse_marker(tokenizer: Tokenizer) -> MarkerList: """ marker = marker_atom (BOOLOP marker_atom)+ """ expression = [_parse_marker_atom(tokenizer)] while tokenizer.check("BOOLOP"): token = tokenizer.read() expr_right = _parse_marker_atom(tokenizer) expression.extend((token.text, expr_right)) return expression def _parse_marker_atom(tokenizer: Tokenizer) -> MarkerAtom: """ marker_atom = WS? LEFT_PARENTHESIS WS? marker WS? RIGHT_PARENTHESIS WS? | WS? marker_item WS? """ tokenizer.consume("WS") if tokenizer.check("LEFT_PARENTHESIS", peek=True): with tokenizer.enclosing_tokens( "LEFT_PARENTHESIS", "RIGHT_PARENTHESIS", around="marker expression", ): tokenizer.consume("WS") marker: MarkerAtom = _parse_marker(tokenizer) tokenizer.consume("WS") else: marker = _parse_marker_item(tokenizer) tokenizer.consume("WS") return marker def _parse_marker_item(tokenizer: Tokenizer) -> MarkerItem: """ marker_item = WS? marker_var WS? marker_op WS? marker_var WS? """ tokenizer.consume("WS") marker_var_left = _parse_marker_var(tokenizer) tokenizer.consume("WS") marker_op = _parse_marker_op(tokenizer) tokenizer.consume("WS") marker_var_right = _parse_marker_var(tokenizer) tokenizer.consume("WS") return (marker_var_left, marker_op, marker_var_right) def _parse_marker_var(tokenizer: Tokenizer) -> MarkerVar: """ marker_var = VARIABLE | QUOTED_STRING """ if tokenizer.check("VARIABLE"): return process_env_var(tokenizer.read().text.replace(".", "_")) elif tokenizer.check("QUOTED_STRING"): return process_python_str(tokenizer.read().text) else: tokenizer.raise_syntax_error( message="Expected a marker variable or quoted string" ) def process_env_var(env_var: str) -> Variable: if ( env_var == "platform_python_implementation" or env_var == "python_implementation" ): return Variable("platform_python_implementation") else: return Variable(env_var) def process_python_str(python_str: str) -> Value: value = ast.literal_eval(python_str) return Value(str(value)) def _parse_marker_op(tokenizer: Tokenizer) -> Op: """ marker_op = IN | NOT IN | OP """ if tokenizer.check("IN"): tokenizer.read() return Op("in") elif tokenizer.check("NOT"): tokenizer.read() tokenizer.expect("WS", expected="whitespace after 'not'") tokenizer.expect("IN", expected="'in' after 'not'") return Op("not in") elif tokenizer.check("OP"): return Op(tokenizer.read().text) else: return tokenizer.raise_syntax_error( "Expected marker operator, one of " "<=, <, !=, ==, >=, >, ~=, ===, in, not in" ) PK ~\&t t *node-gyp/gyp/pylib/packaging/_musllinux.pynu["""PEP 656 support. This module implements logic to detect if the currently running Python is linked against musl, and what musl version is used. """ import functools import re import subprocess import sys from typing import Iterator, NamedTuple, Optional, Sequence from ._elffile import ELFFile class _MuslVersion(NamedTuple): major: int minor: int def _parse_musl_version(output: str) -> Optional[_MuslVersion]: lines = [n for n in (n.strip() for n in output.splitlines()) if n] if len(lines) < 2 or lines[0][:4] != "musl": return None m = re.match(r"Version (\d+)\.(\d+)", lines[1]) if not m: return None return _MuslVersion(major=int(m.group(1)), minor=int(m.group(2))) @functools.lru_cache() def _get_musl_version(executable: str) -> Optional[_MuslVersion]: """Detect currently-running musl runtime version. This is done by checking the specified executable's dynamic linking information, and invoking the loader to parse its output for a version string. If the loader is musl, the output would be something like:: musl libc (x86_64) Version 1.2.2 Dynamic Program Loader """ try: with open(executable, "rb") as f: ld = ELFFile(f).interpreter except (OSError, TypeError, ValueError): return None if ld is None or "musl" not in ld: return None proc = subprocess.run([ld], stderr=subprocess.PIPE, text=True) return _parse_musl_version(proc.stderr) def platform_tags(archs: Sequence[str]) -> Iterator[str]: """Generate musllinux tags compatible to the current platform. :param archs: Sequence of compatible architectures. The first one shall be the closest to the actual architecture and be the part of platform tag after the ``linux_`` prefix, e.g. ``x86_64``. The ``linux_`` prefix is assumed as a prerequisite for the current platform to be musllinux-compatible. :returns: An iterator of compatible musllinux tags. """ sys_musl = _get_musl_version(sys.executable) if sys_musl is None: # Python not dynamically linked against musl. return for arch in archs: for minor in range(sys_musl.minor, -1, -1): yield f"musllinux_{sys_musl.major}_{minor}_{arch}" if __name__ == "__main__": # pragma: no cover import sysconfig plat = sysconfig.get_platform() assert plat.startswith("linux-"), "not linux" print("plat:", plat) print("musl:", _get_musl_version(sys.executable)) print("tags:", end=" ") for t in platform_tags(re.sub(r"[.-]", "_", plat.split("-", 1)[-1])): print(t, end="\n ") PK ~\$ܫ(node-gyp/gyp/pylib/packaging/__init__.pynu[# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. __title__ = "packaging" __summary__ = "Core utilities for Python packages" __uri__ = "https://github.com/pypa/packaging" __version__ = "23.3.dev0" __author__ = "Donald Stufft and individual contributors" __email__ = "donald@stufft.io" __license__ = "BSD-2-Clause or Apache-2.0" __copyright__ = "2014 %s" % __author__ PK ~\%node-gyp/gyp/pylib/packaging/py.typednu[PK ~\dԈ ,node-gyp/gyp/pylib/packaging/requirements.pynu[# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. from typing import Any, Iterator, Optional, Set from ._parser import parse_requirement as _parse_requirement from ._tokenizer import ParserSyntaxError from .markers import Marker, _normalize_extra_values from .specifiers import SpecifierSet from .utils import canonicalize_name class InvalidRequirement(ValueError): """ An invalid requirement was found, users should refer to PEP 508. """ class Requirement: """Parse a requirement. Parse a given requirement string into its parts, such as name, specifier, URL, and extras. Raises InvalidRequirement on a badly-formed requirement string. """ # TODO: Can we test whether something is contained within a requirement? # If so how do we do that? Do we need to test against the _name_ of # the thing as well as the version? What about the markers? # TODO: Can we normalize the name and extra name? def __init__(self, requirement_string: str) -> None: try: parsed = _parse_requirement(requirement_string) except ParserSyntaxError as e: raise InvalidRequirement(str(e)) from e self.name: str = parsed.name self.url: Optional[str] = parsed.url or None self.extras: Set[str] = set(parsed.extras if parsed.extras else []) self.specifier: SpecifierSet = SpecifierSet(parsed.specifier) self.marker: Optional[Marker] = None if parsed.marker is not None: self.marker = Marker.__new__(Marker) self.marker._markers = _normalize_extra_values(parsed.marker) def _iter_parts(self, name: str) -> Iterator[str]: yield name if self.extras: formatted_extras = ",".join(sorted(self.extras)) yield f"[{formatted_extras}]" if self.specifier: yield str(self.specifier) if self.url: yield f"@ {self.url}" if self.marker: yield " " if self.marker: yield f"; {self.marker}" def __str__(self) -> str: return "".join(self._iter_parts(self.name)) def __repr__(self) -> str: return f"" def __hash__(self) -> int: return hash( ( self.__class__.__name__, *self._iter_parts(canonicalize_name(self.name)), ) ) def __eq__(self, other: Any) -> bool: if not isinstance(other, Requirement): return NotImplemented return ( canonicalize_name(self.name) == canonicalize_name(other.name) and self.extras == other.extras and self.specifier == other.specifier and self.url == other.url and self.marker == other.marker ) PK ~\''+node-gyp/gyp/pylib/packaging/LICENSE.APACHEnu[ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS PK ~\I`y|l?l?'node-gyp/gyp/pylib/packaging/version.pynu[# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. """ .. testsetup:: from packaging.version import parse, Version """ import itertools import re from typing import Any, Callable, NamedTuple, Optional, SupportsInt, Tuple, Union from ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType __all__ = ["VERSION_PATTERN", "parse", "Version", "InvalidVersion"] LocalType = Tuple[Union[int, str], ...] CmpPrePostDevType = Union[InfinityType, NegativeInfinityType, Tuple[str, int]] CmpLocalType = Union[ NegativeInfinityType, Tuple[Union[Tuple[int, str], Tuple[NegativeInfinityType, Union[int, str]]], ...], ] CmpKey = Tuple[ int, Tuple[int, ...], CmpPrePostDevType, CmpPrePostDevType, CmpPrePostDevType, CmpLocalType, ] VersionComparisonMethod = Callable[[CmpKey, CmpKey], bool] class _Version(NamedTuple): epoch: int release: Tuple[int, ...] dev: Optional[Tuple[str, int]] pre: Optional[Tuple[str, int]] post: Optional[Tuple[str, int]] local: Optional[LocalType] def parse(version: str) -> "Version": """Parse the given version string. >>> parse('1.0.dev1') :param version: The version string to parse. :raises InvalidVersion: When the version string is not a valid version. """ return Version(version) class InvalidVersion(ValueError): """Raised when a version string is not a valid version. >>> Version("invalid") Traceback (most recent call last): ... packaging.version.InvalidVersion: Invalid version: 'invalid' """ class _BaseVersion: _key: Tuple[Any, ...] def __hash__(self) -> int: return hash(self._key) # Please keep the duplicated `isinstance` check # in the six comparisons hereunder # unless you find a way to avoid adding overhead function calls. def __lt__(self, other: "_BaseVersion") -> bool: if not isinstance(other, _BaseVersion): return NotImplemented return self._key < other._key def __le__(self, other: "_BaseVersion") -> bool: if not isinstance(other, _BaseVersion): return NotImplemented return self._key <= other._key def __eq__(self, other: object) -> bool: if not isinstance(other, _BaseVersion): return NotImplemented return self._key == other._key def __ge__(self, other: "_BaseVersion") -> bool: if not isinstance(other, _BaseVersion): return NotImplemented return self._key >= other._key def __gt__(self, other: "_BaseVersion") -> bool: if not isinstance(other, _BaseVersion): return NotImplemented return self._key > other._key def __ne__(self, other: object) -> bool: if not isinstance(other, _BaseVersion): return NotImplemented return self._key != other._key # Deliberately not anchored to the start and end of the string, to make it # easier for 3rd party code to reuse _VERSION_PATTERN = r""" v? (?: (?:(?P[0-9]+)!)? # epoch (?P[0-9]+(?:\.[0-9]+)*) # release segment (?P
                                          # pre-release
            [-_\.]?
            (?Palpha|a|beta|b|preview|pre|c|rc)
            [-_\.]?
            (?P[0-9]+)?
        )?
        (?P                                         # post release
            (?:-(?P[0-9]+))
            |
            (?:
                [-_\.]?
                (?Ppost|rev|r)
                [-_\.]?
                (?P[0-9]+)?
            )
        )?
        (?P                                          # dev release
            [-_\.]?
            (?Pdev)
            [-_\.]?
            (?P[0-9]+)?
        )?
    )
    (?:\+(?P[a-z0-9]+(?:[-_\.][a-z0-9]+)*))?       # local version
"""

VERSION_PATTERN = _VERSION_PATTERN
"""
A string containing the regular expression used to match a valid version.

The pattern is not anchored at either end, and is intended for embedding in larger
expressions (for example, matching a version number as part of a file name). The
regular expression should be compiled with the ``re.VERBOSE`` and ``re.IGNORECASE``
flags set.

:meta hide-value:
"""


class Version(_BaseVersion):
    """This class abstracts handling of a project's versions.

    A :class:`Version` instance is comparison aware and can be compared and
    sorted using the standard Python interfaces.

    >>> v1 = Version("1.0a5")
    >>> v2 = Version("1.0")
    >>> v1
    
    >>> v2
    
    >>> v1 < v2
    True
    >>> v1 == v2
    False
    >>> v1 > v2
    False
    >>> v1 >= v2
    False
    >>> v1 <= v2
    True
    """

    _regex = re.compile(r"^\s*" + VERSION_PATTERN + r"\s*$", re.VERBOSE | re.IGNORECASE)
    _key: CmpKey

    def __init__(self, version: str) -> None:
        """Initialize a Version object.

        :param version:
            The string representation of a version which will be parsed and normalized
            before use.
        :raises InvalidVersion:
            If the ``version`` does not conform to PEP 440 in any way then this
            exception will be raised.
        """

        # Validate the version and parse it into pieces
        match = self._regex.search(version)
        if not match:
            raise InvalidVersion(f"Invalid version: '{version}'")

        # Store the parsed out pieces of the version
        self._version = _Version(
            epoch=int(match.group("epoch")) if match.group("epoch") else 0,
            release=tuple(int(i) for i in match.group("release").split(".")),
            pre=_parse_letter_version(match.group("pre_l"), match.group("pre_n")),
            post=_parse_letter_version(
                match.group("post_l"), match.group("post_n1") or match.group("post_n2")
            ),
            dev=_parse_letter_version(match.group("dev_l"), match.group("dev_n")),
            local=_parse_local_version(match.group("local")),
        )

        # Generate a key which will be used for sorting
        self._key = _cmpkey(
            self._version.epoch,
            self._version.release,
            self._version.pre,
            self._version.post,
            self._version.dev,
            self._version.local,
        )

    def __repr__(self) -> str:
        """A representation of the Version that shows all internal state.

        >>> Version('1.0.0')
        
        """
        return f""

    def __str__(self) -> str:
        """A string representation of the version that can be rounded-tripped.

        >>> str(Version("1.0a5"))
        '1.0a5'
        """
        parts = []

        # Epoch
        if self.epoch != 0:
            parts.append(f"{self.epoch}!")

        # Release segment
        parts.append(".".join(str(x) for x in self.release))

        # Pre-release
        if self.pre is not None:
            parts.append("".join(str(x) for x in self.pre))

        # Post-release
        if self.post is not None:
            parts.append(f".post{self.post}")

        # Development release
        if self.dev is not None:
            parts.append(f".dev{self.dev}")

        # Local version segment
        if self.local is not None:
            parts.append(f"+{self.local}")

        return "".join(parts)

    @property
    def epoch(self) -> int:
        """The epoch of the version.

        >>> Version("2.0.0").epoch
        0
        >>> Version("1!2.0.0").epoch
        1
        """
        return self._version.epoch

    @property
    def release(self) -> Tuple[int, ...]:
        """The components of the "release" segment of the version.

        >>> Version("1.2.3").release
        (1, 2, 3)
        >>> Version("2.0.0").release
        (2, 0, 0)
        >>> Version("1!2.0.0.post0").release
        (2, 0, 0)

        Includes trailing zeroes but not the epoch or any pre-release / development /
        post-release suffixes.
        """
        return self._version.release

    @property
    def pre(self) -> Optional[Tuple[str, int]]:
        """The pre-release segment of the version.

        >>> print(Version("1.2.3").pre)
        None
        >>> Version("1.2.3a1").pre
        ('a', 1)
        >>> Version("1.2.3b1").pre
        ('b', 1)
        >>> Version("1.2.3rc1").pre
        ('rc', 1)
        """
        return self._version.pre

    @property
    def post(self) -> Optional[int]:
        """The post-release number of the version.

        >>> print(Version("1.2.3").post)
        None
        >>> Version("1.2.3.post1").post
        1
        """
        return self._version.post[1] if self._version.post else None

    @property
    def dev(self) -> Optional[int]:
        """The development number of the version.

        >>> print(Version("1.2.3").dev)
        None
        >>> Version("1.2.3.dev1").dev
        1
        """
        return self._version.dev[1] if self._version.dev else None

    @property
    def local(self) -> Optional[str]:
        """The local version segment of the version.

        >>> print(Version("1.2.3").local)
        None
        >>> Version("1.2.3+abc").local
        'abc'
        """
        if self._version.local:
            return ".".join(str(x) for x in self._version.local)
        else:
            return None

    @property
    def public(self) -> str:
        """The public portion of the version.

        >>> Version("1.2.3").public
        '1.2.3'
        >>> Version("1.2.3+abc").public
        '1.2.3'
        >>> Version("1.2.3+abc.dev1").public
        '1.2.3'
        """
        return str(self).split("+", 1)[0]

    @property
    def base_version(self) -> str:
        """The "base version" of the version.

        >>> Version("1.2.3").base_version
        '1.2.3'
        >>> Version("1.2.3+abc").base_version
        '1.2.3'
        >>> Version("1!1.2.3+abc.dev1").base_version
        '1!1.2.3'

        The "base version" is the public version of the project without any pre or post
        release markers.
        """
        parts = []

        # Epoch
        if self.epoch != 0:
            parts.append(f"{self.epoch}!")

        # Release segment
        parts.append(".".join(str(x) for x in self.release))

        return "".join(parts)

    @property
    def is_prerelease(self) -> bool:
        """Whether this version is a pre-release.

        >>> Version("1.2.3").is_prerelease
        False
        >>> Version("1.2.3a1").is_prerelease
        True
        >>> Version("1.2.3b1").is_prerelease
        True
        >>> Version("1.2.3rc1").is_prerelease
        True
        >>> Version("1.2.3dev1").is_prerelease
        True
        """
        return self.dev is not None or self.pre is not None

    @property
    def is_postrelease(self) -> bool:
        """Whether this version is a post-release.

        >>> Version("1.2.3").is_postrelease
        False
        >>> Version("1.2.3.post1").is_postrelease
        True
        """
        return self.post is not None

    @property
    def is_devrelease(self) -> bool:
        """Whether this version is a development release.

        >>> Version("1.2.3").is_devrelease
        False
        >>> Version("1.2.3.dev1").is_devrelease
        True
        """
        return self.dev is not None

    @property
    def major(self) -> int:
        """The first item of :attr:`release` or ``0`` if unavailable.

        >>> Version("1.2.3").major
        1
        """
        return self.release[0] if len(self.release) >= 1 else 0

    @property
    def minor(self) -> int:
        """The second item of :attr:`release` or ``0`` if unavailable.

        >>> Version("1.2.3").minor
        2
        >>> Version("1").minor
        0
        """
        return self.release[1] if len(self.release) >= 2 else 0

    @property
    def micro(self) -> int:
        """The third item of :attr:`release` or ``0`` if unavailable.

        >>> Version("1.2.3").micro
        3
        >>> Version("1").micro
        0
        """
        return self.release[2] if len(self.release) >= 3 else 0


def _parse_letter_version(
    letter: Optional[str], number: Union[str, bytes, SupportsInt, None]
) -> Optional[Tuple[str, int]]:

    if letter:
        # We consider there to be an implicit 0 in a pre-release if there is
        # not a numeral associated with it.
        if number is None:
            number = 0

        # We normalize any letters to their lower case form
        letter = letter.lower()

        # We consider some words to be alternate spellings of other words and
        # in those cases we want to normalize the spellings to our preferred
        # spelling.
        if letter == "alpha":
            letter = "a"
        elif letter == "beta":
            letter = "b"
        elif letter in ["c", "pre", "preview"]:
            letter = "rc"
        elif letter in ["rev", "r"]:
            letter = "post"

        return letter, int(number)
    if not letter and number:
        # We assume if we are given a number, but we are not given a letter
        # then this is using the implicit post release syntax (e.g. 1.0-1)
        letter = "post"

        return letter, int(number)

    return None


_local_version_separators = re.compile(r"[\._-]")


def _parse_local_version(local: Optional[str]) -> Optional[LocalType]:
    """
    Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
    """
    if local is not None:
        return tuple(
            part.lower() if not part.isdigit() else int(part)
            for part in _local_version_separators.split(local)
        )
    return None


def _cmpkey(
    epoch: int,
    release: Tuple[int, ...],
    pre: Optional[Tuple[str, int]],
    post: Optional[Tuple[str, int]],
    dev: Optional[Tuple[str, int]],
    local: Optional[LocalType],
) -> CmpKey:

    # When we compare a release version, we want to compare it with all of the
    # trailing zeros removed. So we'll use a reverse the list, drop all the now
    # leading zeros until we come to something non zero, then take the rest
    # re-reverse it back into the correct order and make it a tuple and use
    # that for our sorting key.
    _release = tuple(
        reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release))))
    )

    # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
    # We'll do this by abusing the pre segment, but we _only_ want to do this
    # if there is not a pre or a post segment. If we have one of those then
    # the normal sorting rules will handle this case correctly.
    if pre is None and post is None and dev is not None:
        _pre: CmpPrePostDevType = NegativeInfinity
    # Versions without a pre-release (except as noted above) should sort after
    # those with one.
    elif pre is None:
        _pre = Infinity
    else:
        _pre = pre

    # Versions without a post segment should sort before those with one.
    if post is None:
        _post: CmpPrePostDevType = NegativeInfinity

    else:
        _post = post

    # Versions without a development segment should sort after those with one.
    if dev is None:
        _dev: CmpPrePostDevType = Infinity

    else:
        _dev = dev

    if local is None:
        # Versions without a local segment should sort before those with one.
        _local: CmpLocalType = NegativeInfinity
    else:
        # Versions with a local segment need that segment parsed to implement
        # the sorting rules in PEP440.
        # - Alpha numeric segments sort before numeric segments
        # - Alpha numeric segments sort lexicographically
        # - Numeric segments sort numerically
        # - Shorter versions sort before longer versions when the prefixes
        #   match exactly
        _local = tuple(
            (i, "") if isinstance(i, int) else (NegativeInfinity, i) for i in local
        )

    return epoch, _release, _pre, _post, _dev, _local
PK~\sw*node-gyp/gyp/pylib/packaging/_tokenizer.pynu[import contextlib
import re
from dataclasses import dataclass
from typing import Dict, Iterator, NoReturn, Optional, Tuple, Union

from .specifiers import Specifier


@dataclass
class Token:
    name: str
    text: str
    position: int


class ParserSyntaxError(Exception):
    """The provided source text could not be parsed correctly."""

    def __init__(
        self,
        message: str,
        *,
        source: str,
        span: Tuple[int, int],
    ) -> None:
        self.span = span
        self.message = message
        self.source = source

        super().__init__()

    def __str__(self) -> str:
        marker = " " * self.span[0] + "~" * (self.span[1] - self.span[0]) + "^"
        return "\n    ".join([self.message, self.source, marker])


DEFAULT_RULES: "Dict[str, Union[str, re.Pattern[str]]]" = {
    "LEFT_PARENTHESIS": r"\(",
    "RIGHT_PARENTHESIS": r"\)",
    "LEFT_BRACKET": r"\[",
    "RIGHT_BRACKET": r"\]",
    "SEMICOLON": r";",
    "COMMA": r",",
    "QUOTED_STRING": re.compile(
        r"""
            (
                ('[^']*')
                |
                ("[^"]*")
            )
        """,
        re.VERBOSE,
    ),
    "OP": r"(===|==|~=|!=|<=|>=|<|>)",
    "BOOLOP": r"\b(or|and)\b",
    "IN": r"\bin\b",
    "NOT": r"\bnot\b",
    "VARIABLE": re.compile(
        r"""
            \b(
                python_version
                |python_full_version
                |os[._]name
                |sys[._]platform
                |platform_(release|system)
                |platform[._](version|machine|python_implementation)
                |python_implementation
                |implementation_(name|version)
                |extra
            )\b
        """,
        re.VERBOSE,
    ),
    "SPECIFIER": re.compile(
        Specifier._operator_regex_str + Specifier._version_regex_str,
        re.VERBOSE | re.IGNORECASE,
    ),
    "AT": r"\@",
    "URL": r"[^ \t]+",
    "IDENTIFIER": r"\b[a-zA-Z0-9][a-zA-Z0-9._-]*\b",
    "VERSION_PREFIX_TRAIL": r"\.\*",
    "VERSION_LOCAL_LABEL_TRAIL": r"\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*",
    "WS": r"[ \t]+",
    "END": r"$",
}


class Tokenizer:
    """Context-sensitive token parsing.

    Provides methods to examine the input stream to check whether the next token
    matches.
    """

    def __init__(
        self,
        source: str,
        *,
        rules: "Dict[str, Union[str, re.Pattern[str]]]",
    ) -> None:
        self.source = source
        self.rules: Dict[str, re.Pattern[str]] = {
            name: re.compile(pattern) for name, pattern in rules.items()
        }
        self.next_token: Optional[Token] = None
        self.position = 0

    def consume(self, name: str) -> None:
        """Move beyond provided token name, if at current position."""
        if self.check(name):
            self.read()

    def check(self, name: str, *, peek: bool = False) -> bool:
        """Check whether the next token has the provided name.

        By default, if the check succeeds, the token *must* be read before
        another check. If `peek` is set to `True`, the token is not loaded and
        would need to be checked again.
        """
        assert (
            self.next_token is None
        ), f"Cannot check for {name!r}, already have {self.next_token!r}"
        assert name in self.rules, f"Unknown token name: {name!r}"

        expression = self.rules[name]

        match = expression.match(self.source, self.position)
        if match is None:
            return False
        if not peek:
            self.next_token = Token(name, match[0], self.position)
        return True

    def expect(self, name: str, *, expected: str) -> Token:
        """Expect a certain token name next, failing with a syntax error otherwise.

        The token is *not* read.
        """
        if not self.check(name):
            raise self.raise_syntax_error(f"Expected {expected}")
        return self.read()

    def read(self) -> Token:
        """Consume the next token and return it."""
        token = self.next_token
        assert token is not None

        self.position += len(token.text)
        self.next_token = None

        return token

    def raise_syntax_error(
        self,
        message: str,
        *,
        span_start: Optional[int] = None,
        span_end: Optional[int] = None,
    ) -> NoReturn:
        """Raise ParserSyntaxError at the given position."""
        span = (
            self.position if span_start is None else span_start,
            self.position if span_end is None else span_end,
        )
        raise ParserSyntaxError(
            message,
            source=self.source,
            span=span,
        )

    @contextlib.contextmanager
    def enclosing_tokens(
        self, open_token: str, close_token: str, *, around: str
    ) -> Iterator[None]:
        if self.check(open_token):
            open_position = self.position
            self.read()
        else:
            open_position = None

        yield

        if open_position is None:
            return

        if not self.check(close_token):
            self.raise_syntax_error(
                f"Expected matching {close_token} for {open_token}, after {around}",
                span_start=open_position,
            )

        self.read()
PK~\3e~!!*node-gyp/gyp/pylib/packaging/specifiers.pynu[# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
"""
.. testsetup::

    from packaging.specifiers import Specifier, SpecifierSet, InvalidSpecifier
    from packaging.version import Version
"""

import abc
import itertools
import re
from typing import (
    Callable,
    Iterable,
    Iterator,
    List,
    Optional,
    Set,
    Tuple,
    TypeVar,
    Union,
)

from .utils import canonicalize_version
from .version import Version

UnparsedVersion = Union[Version, str]
UnparsedVersionVar = TypeVar("UnparsedVersionVar", bound=UnparsedVersion)
CallableOperator = Callable[[Version, str], bool]


def _coerce_version(version: UnparsedVersion) -> Version:
    if not isinstance(version, Version):
        version = Version(version)
    return version


class InvalidSpecifier(ValueError):
    """
    Raised when attempting to create a :class:`Specifier` with a specifier
    string that is invalid.

    >>> Specifier("lolwat")
    Traceback (most recent call last):
        ...
    packaging.specifiers.InvalidSpecifier: Invalid specifier: 'lolwat'
    """


class BaseSpecifier(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def __str__(self) -> str:
        """
        Returns the str representation of this Specifier-like object. This
        should be representative of the Specifier itself.
        """

    @abc.abstractmethod
    def __hash__(self) -> int:
        """
        Returns a hash value for this Specifier-like object.
        """

    @abc.abstractmethod
    def __eq__(self, other: object) -> bool:
        """
        Returns a boolean representing whether or not the two Specifier-like
        objects are equal.

        :param other: The other object to check against.
        """

    @property
    @abc.abstractmethod
    def prereleases(self) -> Optional[bool]:
        """Whether or not pre-releases as a whole are allowed.

        This can be set to either ``True`` or ``False`` to explicitly enable or disable
        prereleases or it can be set to ``None`` (the default) to use default semantics.
        """

    @prereleases.setter
    def prereleases(self, value: bool) -> None:
        """Setter for :attr:`prereleases`.

        :param value: The value to set.
        """

    @abc.abstractmethod
    def contains(self, item: str, prereleases: Optional[bool] = None) -> bool:
        """
        Determines if the given item is contained within this specifier.
        """

    @abc.abstractmethod
    def filter(
        self, iterable: Iterable[UnparsedVersionVar], prereleases: Optional[bool] = None
    ) -> Iterator[UnparsedVersionVar]:
        """
        Takes an iterable of items and filters them so that only items which
        are contained within this specifier are allowed in it.
        """


class Specifier(BaseSpecifier):
    """This class abstracts handling of version specifiers.

    .. tip::

        It is generally not required to instantiate this manually. You should instead
        prefer to work with :class:`SpecifierSet` instead, which can parse
        comma-separated version specifiers (which is what package metadata contains).
    """

    _operator_regex_str = r"""
        (?P(~=|==|!=|<=|>=|<|>|===))
        """
    _version_regex_str = r"""
        (?P
            (?:
                # The identity operators allow for an escape hatch that will
                # do an exact string match of the version you wish to install.
                # This will not be parsed by PEP 440 and we cannot determine
                # any semantic meaning from it. This operator is discouraged
                # but included entirely as an escape hatch.
                (?<====)  # Only match for the identity operator
                \s*
                [^\s;)]*  # The arbitrary version can be just about anything,
                          # we match everything except for whitespace, a
                          # semi-colon for marker support, and a closing paren
                          # since versions can be enclosed in them.
            )
            |
            (?:
                # The (non)equality operators allow for wild card and local
                # versions to be specified so we have to define these two
                # operators separately to enable that.
                (?<===|!=)            # Only match for equals and not equals

                \s*
                v?
                (?:[0-9]+!)?          # epoch
                [0-9]+(?:\.[0-9]+)*   # release

                # You cannot use a wild card and a pre-release, post-release, a dev or
                # local version together so group them with a | and make them optional.
                (?:
                    \.\*  # Wild card syntax of .*
                    |
                    (?:                                  # pre release
                        [-_\.]?
                        (alpha|beta|preview|pre|a|b|c|rc)
                        [-_\.]?
                        [0-9]*
                    )?
                    (?:                                  # post release
                        (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
                    )?
                    (?:[-_\.]?dev[-_\.]?[0-9]*)?         # dev release
                    (?:\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*)? # local
                )?
            )
            |
            (?:
                # The compatible operator requires at least two digits in the
                # release segment.
                (?<=~=)               # Only match for the compatible operator

                \s*
                v?
                (?:[0-9]+!)?          # epoch
                [0-9]+(?:\.[0-9]+)+   # release  (We have a + instead of a *)
                (?:                   # pre release
                    [-_\.]?
                    (alpha|beta|preview|pre|a|b|c|rc)
                    [-_\.]?
                    [0-9]*
                )?
                (?:                                   # post release
                    (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
                )?
                (?:[-_\.]?dev[-_\.]?[0-9]*)?          # dev release
            )
            |
            (?:
                # All other operators only allow a sub set of what the
                # (non)equality operators do. Specifically they do not allow
                # local versions to be specified nor do they allow the prefix
                # matching wild cards.
                (?=": "greater_than_equal",
        "<": "less_than",
        ">": "greater_than",
        "===": "arbitrary",
    }

    def __init__(self, spec: str = "", prereleases: Optional[bool] = None) -> None:
        """Initialize a Specifier instance.

        :param spec:
            The string representation of a specifier which will be parsed and
            normalized before use.
        :param prereleases:
            This tells the specifier if it should accept prerelease versions if
            applicable or not. The default of ``None`` will autodetect it from the
            given specifiers.
        :raises InvalidSpecifier:
            If the given specifier is invalid (i.e. bad syntax).
        """
        match = self._regex.search(spec)
        if not match:
            raise InvalidSpecifier(f"Invalid specifier: '{spec}'")

        self._spec: Tuple[str, str] = (
            match.group("operator").strip(),
            match.group("version").strip(),
        )

        # Store whether or not this Specifier should accept prereleases
        self._prereleases = prereleases

    # https://github.com/python/mypy/pull/13475#pullrequestreview-1079784515
    @property  # type: ignore[override]
    def prereleases(self) -> bool:
        # If there is an explicit prereleases set for this, then we'll just
        # blindly use that.
        if self._prereleases is not None:
            return self._prereleases

        # Look at all of our specifiers and determine if they are inclusive
        # operators, and if they are if they are including an explicit
        # prerelease.
        operator, version = self._spec
        if operator in ["==", ">=", "<=", "~=", "==="]:
            # The == specifier can include a trailing .*, if it does we
            # want to remove before parsing.
            if operator == "==" and version.endswith(".*"):
                version = version[:-2]

            # Parse the version, and if it is a pre-release than this
            # specifier allows pre-releases.
            if Version(version).is_prerelease:
                return True

        return False

    @prereleases.setter
    def prereleases(self, value: bool) -> None:
        self._prereleases = value

    @property
    def operator(self) -> str:
        """The operator of this specifier.

        >>> Specifier("==1.2.3").operator
        '=='
        """
        return self._spec[0]

    @property
    def version(self) -> str:
        """The version of this specifier.

        >>> Specifier("==1.2.3").version
        '1.2.3'
        """
        return self._spec[1]

    def __repr__(self) -> str:
        """A representation of the Specifier that shows all internal state.

        >>> Specifier('>=1.0.0')
        =1.0.0')>
        >>> Specifier('>=1.0.0', prereleases=False)
        =1.0.0', prereleases=False)>
        >>> Specifier('>=1.0.0', prereleases=True)
        =1.0.0', prereleases=True)>
        """
        pre = (
            f", prereleases={self.prereleases!r}"
            if self._prereleases is not None
            else ""
        )

        return f"<{self.__class__.__name__}({str(self)!r}{pre})>"

    def __str__(self) -> str:
        """A string representation of the Specifier that can be round-tripped.

        >>> str(Specifier('>=1.0.0'))
        '>=1.0.0'
        >>> str(Specifier('>=1.0.0', prereleases=False))
        '>=1.0.0'
        """
        return "{}{}".format(*self._spec)

    @property
    def _canonical_spec(self) -> Tuple[str, str]:
        canonical_version = canonicalize_version(
            self._spec[1],
            strip_trailing_zero=(self._spec[0] != "~="),
        )
        return self._spec[0], canonical_version

    def __hash__(self) -> int:
        return hash(self._canonical_spec)

    def __eq__(self, other: object) -> bool:
        """Whether or not the two Specifier-like objects are equal.

        :param other: The other object to check against.

        The value of :attr:`prereleases` is ignored.

        >>> Specifier("==1.2.3") == Specifier("== 1.2.3.0")
        True
        >>> (Specifier("==1.2.3", prereleases=False) ==
        ...  Specifier("==1.2.3", prereleases=True))
        True
        >>> Specifier("==1.2.3") == "==1.2.3"
        True
        >>> Specifier("==1.2.3") == Specifier("==1.2.4")
        False
        >>> Specifier("==1.2.3") == Specifier("~=1.2.3")
        False
        """
        if isinstance(other, str):
            try:
                other = self.__class__(str(other))
            except InvalidSpecifier:
                return NotImplemented
        elif not isinstance(other, self.__class__):
            return NotImplemented

        return self._canonical_spec == other._canonical_spec

    def _get_operator(self, op: str) -> CallableOperator:
        operator_callable: CallableOperator = getattr(
            self, f"_compare_{self._operators[op]}"
        )
        return operator_callable

    def _compare_compatible(self, prospective: Version, spec: str) -> bool:

        # Compatible releases have an equivalent combination of >= and ==. That
        # is that ~=2.2 is equivalent to >=2.2,==2.*. This allows us to
        # implement this in terms of the other specifiers instead of
        # implementing it ourselves. The only thing we need to do is construct
        # the other specifiers.

        # We want everything but the last item in the version, but we want to
        # ignore suffix segments.
        prefix = _version_join(
            list(itertools.takewhile(_is_not_suffix, _version_split(spec)))[:-1]
        )

        # Add the prefix notation to the end of our string
        prefix += ".*"

        return self._get_operator(">=")(prospective, spec) and self._get_operator("==")(
            prospective, prefix
        )

    def _compare_equal(self, prospective: Version, spec: str) -> bool:

        # We need special logic to handle prefix matching
        if spec.endswith(".*"):
            # In the case of prefix matching we want to ignore local segment.
            normalized_prospective = canonicalize_version(
                prospective.public, strip_trailing_zero=False
            )
            # Get the normalized version string ignoring the trailing .*
            normalized_spec = canonicalize_version(spec[:-2], strip_trailing_zero=False)
            # Split the spec out by bangs and dots, and pretend that there is
            # an implicit dot in between a release segment and a pre-release segment.
            split_spec = _version_split(normalized_spec)

            # Split the prospective version out by bangs and dots, and pretend
            # that there is an implicit dot in between a release segment and
            # a pre-release segment.
            split_prospective = _version_split(normalized_prospective)

            # 0-pad the prospective version before shortening it to get the correct
            # shortened version.
            padded_prospective, _ = _pad_version(split_prospective, split_spec)

            # Shorten the prospective version to be the same length as the spec
            # so that we can determine if the specifier is a prefix of the
            # prospective version or not.
            shortened_prospective = padded_prospective[: len(split_spec)]

            return shortened_prospective == split_spec
        else:
            # Convert our spec string into a Version
            spec_version = Version(spec)

            # If the specifier does not have a local segment, then we want to
            # act as if the prospective version also does not have a local
            # segment.
            if not spec_version.local:
                prospective = Version(prospective.public)

            return prospective == spec_version

    def _compare_not_equal(self, prospective: Version, spec: str) -> bool:
        return not self._compare_equal(prospective, spec)

    def _compare_less_than_equal(self, prospective: Version, spec: str) -> bool:

        # NB: Local version identifiers are NOT permitted in the version
        # specifier, so local version labels can be universally removed from
        # the prospective version.
        return Version(prospective.public) <= Version(spec)

    def _compare_greater_than_equal(self, prospective: Version, spec: str) -> bool:

        # NB: Local version identifiers are NOT permitted in the version
        # specifier, so local version labels can be universally removed from
        # the prospective version.
        return Version(prospective.public) >= Version(spec)

    def _compare_less_than(self, prospective: Version, spec_str: str) -> bool:

        # Convert our spec to a Version instance, since we'll want to work with
        # it as a version.
        spec = Version(spec_str)

        # Check to see if the prospective version is less than the spec
        # version. If it's not we can short circuit and just return False now
        # instead of doing extra unneeded work.
        if not prospective < spec:
            return False

        # This special case is here so that, unless the specifier itself
        # includes is a pre-release version, that we do not accept pre-release
        # versions for the version mentioned in the specifier (e.g. <3.1 should
        # not match 3.1.dev0, but should match 3.0.dev0).
        if not spec.is_prerelease and prospective.is_prerelease:
            if Version(prospective.base_version) == Version(spec.base_version):
                return False

        # If we've gotten to here, it means that prospective version is both
        # less than the spec version *and* it's not a pre-release of the same
        # version in the spec.
        return True

    def _compare_greater_than(self, prospective: Version, spec_str: str) -> bool:

        # Convert our spec to a Version instance, since we'll want to work with
        # it as a version.
        spec = Version(spec_str)

        # Check to see if the prospective version is greater than the spec
        # version. If it's not we can short circuit and just return False now
        # instead of doing extra unneeded work.
        if not prospective > spec:
            return False

        # This special case is here so that, unless the specifier itself
        # includes is a post-release version, that we do not accept
        # post-release versions for the version mentioned in the specifier
        # (e.g. >3.1 should not match 3.0.post0, but should match 3.2.post0).
        if not spec.is_postrelease and prospective.is_postrelease:
            if Version(prospective.base_version) == Version(spec.base_version):
                return False

        # Ensure that we do not allow a local version of the version mentioned
        # in the specifier, which is technically greater than, to match.
        if prospective.local is not None:
            if Version(prospective.base_version) == Version(spec.base_version):
                return False

        # If we've gotten to here, it means that prospective version is both
        # greater than the spec version *and* it's not a pre-release of the
        # same version in the spec.
        return True

    def _compare_arbitrary(self, prospective: Version, spec: str) -> bool:
        return str(prospective).lower() == str(spec).lower()

    def __contains__(self, item: Union[str, Version]) -> bool:
        """Return whether or not the item is contained in this specifier.

        :param item: The item to check for.

        This is used for the ``in`` operator and behaves the same as
        :meth:`contains` with no ``prereleases`` argument passed.

        >>> "1.2.3" in Specifier(">=1.2.3")
        True
        >>> Version("1.2.3") in Specifier(">=1.2.3")
        True
        >>> "1.0.0" in Specifier(">=1.2.3")
        False
        >>> "1.3.0a1" in Specifier(">=1.2.3")
        False
        >>> "1.3.0a1" in Specifier(">=1.2.3", prereleases=True)
        True
        """
        return self.contains(item)

    def contains(
        self, item: UnparsedVersion, prereleases: Optional[bool] = None
    ) -> bool:
        """Return whether or not the item is contained in this specifier.

        :param item:
            The item to check for, which can be a version string or a
            :class:`Version` instance.
        :param prereleases:
            Whether or not to match prereleases with this Specifier. If set to
            ``None`` (the default), it uses :attr:`prereleases` to determine
            whether or not prereleases are allowed.

        >>> Specifier(">=1.2.3").contains("1.2.3")
        True
        >>> Specifier(">=1.2.3").contains(Version("1.2.3"))
        True
        >>> Specifier(">=1.2.3").contains("1.0.0")
        False
        >>> Specifier(">=1.2.3").contains("1.3.0a1")
        False
        >>> Specifier(">=1.2.3", prereleases=True).contains("1.3.0a1")
        True
        >>> Specifier(">=1.2.3").contains("1.3.0a1", prereleases=True)
        True
        """

        # Determine if prereleases are to be allowed or not.
        if prereleases is None:
            prereleases = self.prereleases

        # Normalize item to a Version, this allows us to have a shortcut for
        # "2.0" in Specifier(">=2")
        normalized_item = _coerce_version(item)

        # Determine if we should be supporting prereleases in this specifier
        # or not, if we do not support prereleases than we can short circuit
        # logic if this version is a prereleases.
        if normalized_item.is_prerelease and not prereleases:
            return False

        # Actually do the comparison to determine if this item is contained
        # within this Specifier or not.
        operator_callable: CallableOperator = self._get_operator(self.operator)
        return operator_callable(normalized_item, self.version)

    def filter(
        self, iterable: Iterable[UnparsedVersionVar], prereleases: Optional[bool] = None
    ) -> Iterator[UnparsedVersionVar]:
        """Filter items in the given iterable, that match the specifier.

        :param iterable:
            An iterable that can contain version strings and :class:`Version` instances.
            The items in the iterable will be filtered according to the specifier.
        :param prereleases:
            Whether or not to allow prereleases in the returned iterator. If set to
            ``None`` (the default), it will be intelligently decide whether to allow
            prereleases or not (based on the :attr:`prereleases` attribute, and
            whether the only versions matching are prereleases).

        This method is smarter than just ``filter(Specifier().contains, [...])``
        because it implements the rule from :pep:`440` that a prerelease item
        SHOULD be accepted if no other versions match the given specifier.

        >>> list(Specifier(">=1.2.3").filter(["1.2", "1.3", "1.5a1"]))
        ['1.3']
        >>> list(Specifier(">=1.2.3").filter(["1.2", "1.2.3", "1.3", Version("1.4")]))
        ['1.2.3', '1.3', ]
        >>> list(Specifier(">=1.2.3").filter(["1.2", "1.5a1"]))
        ['1.5a1']
        >>> list(Specifier(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True))
        ['1.3', '1.5a1']
        >>> list(Specifier(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"]))
        ['1.3', '1.5a1']
        """

        yielded = False
        found_prereleases = []

        kw = {"prereleases": prereleases if prereleases is not None else True}

        # Attempt to iterate over all the values in the iterable and if any of
        # them match, yield them.
        for version in iterable:
            parsed_version = _coerce_version(version)

            if self.contains(parsed_version, **kw):
                # If our version is a prerelease, and we were not set to allow
                # prereleases, then we'll store it for later in case nothing
                # else matches this specifier.
                if parsed_version.is_prerelease and not (
                    prereleases or self.prereleases
                ):
                    found_prereleases.append(version)
                # Either this is not a prerelease, or we should have been
                # accepting prereleases from the beginning.
                else:
                    yielded = True
                    yield version

        # Now that we've iterated over everything, determine if we've yielded
        # any values, and if we have not and we have any prereleases stored up
        # then we will go ahead and yield the prereleases.
        if not yielded and found_prereleases:
            for version in found_prereleases:
                yield version


_prefix_regex = re.compile(r"^([0-9]+)((?:a|b|c|rc)[0-9]+)$")


def _version_split(version: str) -> List[str]:
    """Split version into components.

    The split components are intended for version comparison. The logic does
    not attempt to retain the original version string, so joining the
    components back with :func:`_version_join` may not produce the original
    version string.
    """
    result: List[str] = []

    epoch, _, rest = version.rpartition("!")
    result.append(epoch or "0")

    for item in rest.split("."):
        match = _prefix_regex.search(item)
        if match:
            result.extend(match.groups())
        else:
            result.append(item)
    return result


def _version_join(components: List[str]) -> str:
    """Join split version components into a version string.

    This function assumes the input came from :func:`_version_split`, where the
    first component must be the epoch (either empty or numeric), and all other
    components numeric.
    """
    epoch, *rest = components
    return f"{epoch}!{'.'.join(rest)}"


def _is_not_suffix(segment: str) -> bool:
    return not any(
        segment.startswith(prefix) for prefix in ("dev", "a", "b", "rc", "post")
    )


def _pad_version(left: List[str], right: List[str]) -> Tuple[List[str], List[str]]:
    left_split, right_split = [], []

    # Get the release segment of our versions
    left_split.append(list(itertools.takewhile(lambda x: x.isdigit(), left)))
    right_split.append(list(itertools.takewhile(lambda x: x.isdigit(), right)))

    # Get the rest of our versions
    left_split.append(left[len(left_split[0]) :])
    right_split.append(right[len(right_split[0]) :])

    # Insert our padding
    left_split.insert(1, ["0"] * max(0, len(right_split[0]) - len(left_split[0])))
    right_split.insert(1, ["0"] * max(0, len(left_split[0]) - len(right_split[0])))

    return (list(itertools.chain(*left_split)), list(itertools.chain(*right_split)))


class SpecifierSet(BaseSpecifier):
    """This class abstracts handling of a set of version specifiers.

    It can be passed a single specifier (``>=3.0``), a comma-separated list of
    specifiers (``>=3.0,!=3.1``), or no specifier at all.
    """

    def __init__(
        self, specifiers: str = "", prereleases: Optional[bool] = None
    ) -> None:
        """Initialize a SpecifierSet instance.

        :param specifiers:
            The string representation of a specifier or a comma-separated list of
            specifiers which will be parsed and normalized before use.
        :param prereleases:
            This tells the SpecifierSet if it should accept prerelease versions if
            applicable or not. The default of ``None`` will autodetect it from the
            given specifiers.

        :raises InvalidSpecifier:
            If the given ``specifiers`` are not parseable than this exception will be
            raised.
        """

        # Split on `,` to break each individual specifier into it's own item, and
        # strip each item to remove leading/trailing whitespace.
        split_specifiers = [s.strip() for s in specifiers.split(",") if s.strip()]

        # Parsed each individual specifier, attempting first to make it a
        # Specifier.
        parsed: Set[Specifier] = set()
        for specifier in split_specifiers:
            parsed.add(Specifier(specifier))

        # Turn our parsed specifiers into a frozen set and save them for later.
        self._specs = frozenset(parsed)

        # Store our prereleases value so we can use it later to determine if
        # we accept prereleases or not.
        self._prereleases = prereleases

    @property
    def prereleases(self) -> Optional[bool]:
        # If we have been given an explicit prerelease modifier, then we'll
        # pass that through here.
        if self._prereleases is not None:
            return self._prereleases

        # If we don't have any specifiers, and we don't have a forced value,
        # then we'll just return None since we don't know if this should have
        # pre-releases or not.
        if not self._specs:
            return None

        # Otherwise we'll see if any of the given specifiers accept
        # prereleases, if any of them do we'll return True, otherwise False.
        return any(s.prereleases for s in self._specs)

    @prereleases.setter
    def prereleases(self, value: bool) -> None:
        self._prereleases = value

    def __repr__(self) -> str:
        """A representation of the specifier set that shows all internal state.

        Note that the ordering of the individual specifiers within the set may not
        match the input string.

        >>> SpecifierSet('>=1.0.0,!=2.0.0')
        =1.0.0')>
        >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=False)
        =1.0.0', prereleases=False)>
        >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=True)
        =1.0.0', prereleases=True)>
        """
        pre = (
            f", prereleases={self.prereleases!r}"
            if self._prereleases is not None
            else ""
        )

        return f""

    def __str__(self) -> str:
        """A string representation of the specifier set that can be round-tripped.

        Note that the ordering of the individual specifiers within the set may not
        match the input string.

        >>> str(SpecifierSet(">=1.0.0,!=1.0.1"))
        '!=1.0.1,>=1.0.0'
        >>> str(SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False))
        '!=1.0.1,>=1.0.0'
        """
        return ",".join(sorted(str(s) for s in self._specs))

    def __hash__(self) -> int:
        return hash(self._specs)

    def __and__(self, other: Union["SpecifierSet", str]) -> "SpecifierSet":
        """Return a SpecifierSet which is a combination of the two sets.

        :param other: The other object to combine with.

        >>> SpecifierSet(">=1.0.0,!=1.0.1") & '<=2.0.0,!=2.0.1'
        =1.0.0')>
        >>> SpecifierSet(">=1.0.0,!=1.0.1") & SpecifierSet('<=2.0.0,!=2.0.1')
        =1.0.0')>
        """
        if isinstance(other, str):
            other = SpecifierSet(other)
        elif not isinstance(other, SpecifierSet):
            return NotImplemented

        specifier = SpecifierSet()
        specifier._specs = frozenset(self._specs | other._specs)

        if self._prereleases is None and other._prereleases is not None:
            specifier._prereleases = other._prereleases
        elif self._prereleases is not None and other._prereleases is None:
            specifier._prereleases = self._prereleases
        elif self._prereleases == other._prereleases:
            specifier._prereleases = self._prereleases
        else:
            raise ValueError(
                "Cannot combine SpecifierSets with True and False prerelease "
                "overrides."
            )

        return specifier

    def __eq__(self, other: object) -> bool:
        """Whether or not the two SpecifierSet-like objects are equal.

        :param other: The other object to check against.

        The value of :attr:`prereleases` is ignored.

        >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.1")
        True
        >>> (SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False) ==
        ...  SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True))
        True
        >>> SpecifierSet(">=1.0.0,!=1.0.1") == ">=1.0.0,!=1.0.1"
        True
        >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0")
        False
        >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.2")
        False
        """
        if isinstance(other, (str, Specifier)):
            other = SpecifierSet(str(other))
        elif not isinstance(other, SpecifierSet):
            return NotImplemented

        return self._specs == other._specs

    def __len__(self) -> int:
        """Returns the number of specifiers in this specifier set."""
        return len(self._specs)

    def __iter__(self) -> Iterator[Specifier]:
        """
        Returns an iterator over all the underlying :class:`Specifier` instances
        in this specifier set.

        >>> sorted(SpecifierSet(">=1.0.0,!=1.0.1"), key=str)
        [, =1.0.0')>]
        """
        return iter(self._specs)

    def __contains__(self, item: UnparsedVersion) -> bool:
        """Return whether or not the item is contained in this specifier.

        :param item: The item to check for.

        This is used for the ``in`` operator and behaves the same as
        :meth:`contains` with no ``prereleases`` argument passed.

        >>> "1.2.3" in SpecifierSet(">=1.0.0,!=1.0.1")
        True
        >>> Version("1.2.3") in SpecifierSet(">=1.0.0,!=1.0.1")
        True
        >>> "1.0.1" in SpecifierSet(">=1.0.0,!=1.0.1")
        False
        >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1")
        False
        >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True)
        True
        """
        return self.contains(item)

    def contains(
        self,
        item: UnparsedVersion,
        prereleases: Optional[bool] = None,
        installed: Optional[bool] = None,
    ) -> bool:
        """Return whether or not the item is contained in this SpecifierSet.

        :param item:
            The item to check for, which can be a version string or a
            :class:`Version` instance.
        :param prereleases:
            Whether or not to match prereleases with this SpecifierSet. If set to
            ``None`` (the default), it uses :attr:`prereleases` to determine
            whether or not prereleases are allowed.

        >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.2.3")
        True
        >>> SpecifierSet(">=1.0.0,!=1.0.1").contains(Version("1.2.3"))
        True
        >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.0.1")
        False
        >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1")
        False
        >>> SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True).contains("1.3.0a1")
        True
        >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1", prereleases=True)
        True
        """
        # Ensure that our item is a Version instance.
        if not isinstance(item, Version):
            item = Version(item)

        # Determine if we're forcing a prerelease or not, if we're not forcing
        # one for this particular filter call, then we'll use whatever the
        # SpecifierSet thinks for whether or not we should support prereleases.
        if prereleases is None:
            prereleases = self.prereleases

        # We can determine if we're going to allow pre-releases by looking to
        # see if any of the underlying items supports them. If none of them do
        # and this item is a pre-release then we do not allow it and we can
        # short circuit that here.
        # Note: This means that 1.0.dev1 would not be contained in something
        #       like >=1.0.devabc however it would be in >=1.0.debabc,>0.0.dev0
        if not prereleases and item.is_prerelease:
            return False

        if installed and item.is_prerelease:
            item = Version(item.base_version)

        # We simply dispatch to the underlying specs here to make sure that the
        # given version is contained within all of them.
        # Note: This use of all() here means that an empty set of specifiers
        #       will always return True, this is an explicit design decision.
        return all(s.contains(item, prereleases=prereleases) for s in self._specs)

    def filter(
        self, iterable: Iterable[UnparsedVersionVar], prereleases: Optional[bool] = None
    ) -> Iterator[UnparsedVersionVar]:
        """Filter items in the given iterable, that match the specifiers in this set.

        :param iterable:
            An iterable that can contain version strings and :class:`Version` instances.
            The items in the iterable will be filtered according to the specifier.
        :param prereleases:
            Whether or not to allow prereleases in the returned iterator. If set to
            ``None`` (the default), it will be intelligently decide whether to allow
            prereleases or not (based on the :attr:`prereleases` attribute, and
            whether the only versions matching are prereleases).

        This method is smarter than just ``filter(SpecifierSet(...).contains, [...])``
        because it implements the rule from :pep:`440` that a prerelease item
        SHOULD be accepted if no other versions match the given specifier.

        >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", "1.5a1"]))
        ['1.3']
        >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", Version("1.4")]))
        ['1.3', ]
        >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.5a1"]))
        []
        >>> list(SpecifierSet(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True))
        ['1.3', '1.5a1']
        >>> list(SpecifierSet(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"]))
        ['1.3', '1.5a1']

        An "empty" SpecifierSet will filter items based on the presence of prerelease
        versions in the set.

        >>> list(SpecifierSet("").filter(["1.3", "1.5a1"]))
        ['1.3']
        >>> list(SpecifierSet("").filter(["1.5a1"]))
        ['1.5a1']
        >>> list(SpecifierSet("", prereleases=True).filter(["1.3", "1.5a1"]))
        ['1.3', '1.5a1']
        >>> list(SpecifierSet("").filter(["1.3", "1.5a1"], prereleases=True))
        ['1.3', '1.5a1']
        """
        # Determine if we're forcing a prerelease or not, if we're not forcing
        # one for this particular filter call, then we'll use whatever the
        # SpecifierSet thinks for whether or not we should support prereleases.
        if prereleases is None:
            prereleases = self.prereleases

        # If we have any specifiers, then we want to wrap our iterable in the
        # filter method for each one, this will act as a logical AND amongst
        # each specifier.
        if self._specs:
            for spec in self._specs:
                iterable = spec.filter(iterable, prereleases=bool(prereleases))
            return iter(iterable)
        # If we do not have any specifiers, then we need to have a rough filter
        # which will filter out any pre-releases, unless there are no final
        # releases.
        else:
            filtered: List[UnparsedVersionVar] = []
            found_prereleases: List[UnparsedVersionVar] = []

            for item in iterable:
                parsed_version = _coerce_version(item)

                # Store any item which is a pre-release for later unless we've
                # already found a final version or we are accepting prereleases
                if parsed_version.is_prerelease and not prereleases:
                    if not filtered:
                        found_prereleases.append(item)
                else:
                    filtered.append(item)

            # If we've found no items except for pre-releases, then we'll go
            # ahead and use the pre-releases
            if not filtered and found_prereleases and prereleases is None:
                return iter(found_prereleases)

            return iter(filtered)
PK~\ǔ%node-gyp/gyp/pylib/packaging/utils.pynu[# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.

import re
from typing import FrozenSet, NewType, Tuple, Union, cast

from .tags import Tag, parse_tag
from .version import InvalidVersion, Version

BuildTag = Union[Tuple[()], Tuple[int, str]]
NormalizedName = NewType("NormalizedName", str)


class InvalidName(ValueError):
    """
    An invalid distribution name; users should refer to the packaging user guide.
    """


class InvalidWheelFilename(ValueError):
    """
    An invalid wheel filename was found, users should refer to PEP 427.
    """


class InvalidSdistFilename(ValueError):
    """
    An invalid sdist filename was found, users should refer to the packaging user guide.
    """


# Core metadata spec for `Name`
_validate_regex = re.compile(
    r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$", re.IGNORECASE
)
_canonicalize_regex = re.compile(r"[-_.]+")
_normalized_regex = re.compile(r"^([a-z0-9]|[a-z0-9]([a-z0-9-](?!--))*[a-z0-9])$")
# PEP 427: The build number must start with a digit.
_build_tag_regex = re.compile(r"(\d+)(.*)")


def canonicalize_name(name: str, *, validate: bool = False) -> NormalizedName:
    if validate and not _validate_regex.match(name):
        raise InvalidName(f"name is invalid: {name!r}")
    # This is taken from PEP 503.
    value = _canonicalize_regex.sub("-", name).lower()
    return cast(NormalizedName, value)


def is_normalized_name(name: str) -> bool:
    return _normalized_regex.match(name) is not None


def canonicalize_version(
    version: Union[Version, str], *, strip_trailing_zero: bool = True
) -> str:
    """
    This is very similar to Version.__str__, but has one subtle difference
    with the way it handles the release segment.
    """
    if isinstance(version, str):
        try:
            parsed = Version(version)
        except InvalidVersion:
            # Legacy versions cannot be normalized
            return version
    else:
        parsed = version

    parts = []

    # Epoch
    if parsed.epoch != 0:
        parts.append(f"{parsed.epoch}!")

    # Release segment
    release_segment = ".".join(str(x) for x in parsed.release)
    if strip_trailing_zero:
        # NB: This strips trailing '.0's to normalize
        release_segment = re.sub(r"(\.0)+$", "", release_segment)
    parts.append(release_segment)

    # Pre-release
    if parsed.pre is not None:
        parts.append("".join(str(x) for x in parsed.pre))

    # Post-release
    if parsed.post is not None:
        parts.append(f".post{parsed.post}")

    # Development release
    if parsed.dev is not None:
        parts.append(f".dev{parsed.dev}")

    # Local version segment
    if parsed.local is not None:
        parts.append(f"+{parsed.local}")

    return "".join(parts)


def parse_wheel_filename(
    filename: str,
) -> Tuple[NormalizedName, Version, BuildTag, FrozenSet[Tag]]:
    if not filename.endswith(".whl"):
        raise InvalidWheelFilename(
            f"Invalid wheel filename (extension must be '.whl'): {filename}"
        )

    filename = filename[:-4]
    dashes = filename.count("-")
    if dashes not in (4, 5):
        raise InvalidWheelFilename(
            f"Invalid wheel filename (wrong number of parts): {filename}"
        )

    parts = filename.split("-", dashes - 2)
    name_part = parts[0]
    # See PEP 427 for the rules on escaping the project name.
    if "__" in name_part or re.match(r"^[\w\d._]*$", name_part, re.UNICODE) is None:
        raise InvalidWheelFilename(f"Invalid project name: {filename}")
    name = canonicalize_name(name_part)

    try:
        version = Version(parts[1])
    except InvalidVersion as e:
        raise InvalidWheelFilename(
            f"Invalid wheel filename (invalid version): {filename}"
        ) from e

    if dashes == 5:
        build_part = parts[2]
        build_match = _build_tag_regex.match(build_part)
        if build_match is None:
            raise InvalidWheelFilename(
                f"Invalid build number: {build_part} in '{filename}'"
            )
        build = cast(BuildTag, (int(build_match.group(1)), build_match.group(2)))
    else:
        build = ()
    tags = parse_tag(parts[-1])
    return (name, version, build, tags)


def parse_sdist_filename(filename: str) -> Tuple[NormalizedName, Version]:
    if filename.endswith(".tar.gz"):
        file_stem = filename[: -len(".tar.gz")]
    elif filename.endswith(".zip"):
        file_stem = filename[: -len(".zip")]
    else:
        raise InvalidSdistFilename(
            f"Invalid sdist filename (extension must be '.tar.gz' or '.zip'):"
            f" {filename}"
        )

    # We are requiring a PEP 440 version, which cannot contain dashes,
    # so we split on the last dash.
    name_part, sep, version_part = file_stem.rpartition("-")
    if not sep:
        raise InvalidSdistFilename(f"Invalid sdist filename: {filename}")

    name = canonicalize_name(name_part)

    try:
        version = Version(version_part)
    except InvalidVersion as e:
        raise InvalidSdistFilename(
            f"Invalid sdist filename (invalid version): {filename}"
        ) from e

    return (name, version)
PK~\b(node-gyp/gyp/pylib/packaging/_elffile.pynu["""
ELF file parser.

This provides a class ``ELFFile`` that parses an ELF executable in a similar
interface to ``ZipFile``. Only the read interface is implemented.

Based on: https://gist.github.com/lyssdod/f51579ae8d93c8657a5564aefc2ffbca
ELF header: https://refspecs.linuxfoundation.org/elf/gabi4+/ch4.eheader.html
"""

import enum
import os
import struct
from typing import IO, Optional, Tuple


class ELFInvalid(ValueError):
    pass


class EIClass(enum.IntEnum):
    C32 = 1
    C64 = 2


class EIData(enum.IntEnum):
    Lsb = 1
    Msb = 2


class EMachine(enum.IntEnum):
    I386 = 3
    S390 = 22
    Arm = 40
    X8664 = 62
    AArc64 = 183


class ELFFile:
    """
    Representation of an ELF executable.
    """

    def __init__(self, f: IO[bytes]) -> None:
        self._f = f

        try:
            ident = self._read("16B")
        except struct.error:
            raise ELFInvalid("unable to parse identification")
        magic = bytes(ident[:4])
        if magic != b"\x7fELF":
            raise ELFInvalid(f"invalid magic: {magic!r}")

        self.capacity = ident[4]  # Format for program header (bitness).
        self.encoding = ident[5]  # Data structure encoding (endianness).

        try:
            # e_fmt: Format for program header.
            # p_fmt: Format for section header.
            # p_idx: Indexes to find p_type, p_offset, and p_filesz.
            e_fmt, self._p_fmt, self._p_idx = {
                (1, 1): ("HHIIIIIHHH", ">IIIIIIII", (0, 1, 4)),  # 32-bit MSB.
                (2, 1): ("HHIQQQIHHH", ">IIQQQQQQ", (0, 2, 5)),  # 64-bit MSB.
            }[(self.capacity, self.encoding)]
        except KeyError:
            raise ELFInvalid(
                f"unrecognized capacity ({self.capacity}) or "
                f"encoding ({self.encoding})"
            )

        try:
            (
                _,
                self.machine,  # Architecture type.
                _,
                _,
                self._e_phoff,  # Offset of program header.
                _,
                self.flags,  # Processor-specific flags.
                _,
                self._e_phentsize,  # Size of section.
                self._e_phnum,  # Number of sections.
            ) = self._read(e_fmt)
        except struct.error as e:
            raise ELFInvalid("unable to parse machine and section information") from e

    def _read(self, fmt: str) -> Tuple[int, ...]:
        return struct.unpack(fmt, self._f.read(struct.calcsize(fmt)))

    @property
    def interpreter(self) -> Optional[str]:
        """
        The path recorded in the ``PT_INTERP`` section header.
        """
        for index in range(self._e_phnum):
            self._f.seek(self._e_phoff + self._e_phentsize * index)
            try:
                data = self._read(self._p_fmt)
            except struct.error:
                continue
            if data[self._p_idx[0]] != 3:  # Not PT_INTERP.
                continue
            self._f.seek(data[self._p_idx[1]])
            return os.fsdecode(self._f.read(data[self._p_idx[2]])).strip("\0")
        return None
PK~\Ulz6%6%*node-gyp/gyp/pylib/packaging/_manylinux.pynu[import collections
import contextlib
import functools
import os
import re
import sys
import warnings
from typing import Dict, Generator, Iterator, NamedTuple, Optional, Sequence, Tuple

from ._elffile import EIClass, EIData, ELFFile, EMachine

EF_ARM_ABIMASK = 0xFF000000
EF_ARM_ABI_VER5 = 0x05000000
EF_ARM_ABI_FLOAT_HARD = 0x00000400


# `os.PathLike` not a generic type until Python 3.9, so sticking with `str`
# as the type for `path` until then.
@contextlib.contextmanager
def _parse_elf(path: str) -> Generator[Optional[ELFFile], None, None]:
    try:
        with open(path, "rb") as f:
            yield ELFFile(f)
    except (OSError, TypeError, ValueError):
        yield None


def _is_linux_armhf(executable: str) -> bool:
    # hard-float ABI can be detected from the ELF header of the running
    # process
    # https://static.docs.arm.com/ihi0044/g/aaelf32.pdf
    with _parse_elf(executable) as f:
        return (
            f is not None
            and f.capacity == EIClass.C32
            and f.encoding == EIData.Lsb
            and f.machine == EMachine.Arm
            and f.flags & EF_ARM_ABIMASK == EF_ARM_ABI_VER5
            and f.flags & EF_ARM_ABI_FLOAT_HARD == EF_ARM_ABI_FLOAT_HARD
        )


def _is_linux_i686(executable: str) -> bool:
    with _parse_elf(executable) as f:
        return (
            f is not None
            and f.capacity == EIClass.C32
            and f.encoding == EIData.Lsb
            and f.machine == EMachine.I386
        )


def _have_compatible_abi(executable: str, archs: Sequence[str]) -> bool:
    if "armv7l" in archs:
        return _is_linux_armhf(executable)
    if "i686" in archs:
        return _is_linux_i686(executable)
    allowed_archs = {"x86_64", "aarch64", "ppc64", "ppc64le", "s390x", "loongarch64"}
    return any(arch in allowed_archs for arch in archs)


# If glibc ever changes its major version, we need to know what the last
# minor version was, so we can build the complete list of all versions.
# For now, guess what the highest minor version might be, assume it will
# be 50 for testing. Once this actually happens, update the dictionary
# with the actual value.
_LAST_GLIBC_MINOR: Dict[int, int] = collections.defaultdict(lambda: 50)


class _GLibCVersion(NamedTuple):
    major: int
    minor: int


def _glibc_version_string_confstr() -> Optional[str]:
    """
    Primary implementation of glibc_version_string using os.confstr.
    """
    # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely
    # to be broken or missing. This strategy is used in the standard library
    # platform module.
    # https://github.com/python/cpython/blob/fcf1d003bf4f0100c/Lib/platform.py#L175-L183
    try:
        # Should be a string like "glibc 2.17".
        version_string: str = getattr(os, "confstr")("CS_GNU_LIBC_VERSION")
        assert version_string is not None
        _, version = version_string.rsplit()
    except (AssertionError, AttributeError, OSError, ValueError):
        # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)...
        return None
    return version


def _glibc_version_string_ctypes() -> Optional[str]:
    """
    Fallback implementation of glibc_version_string using ctypes.
    """
    try:
        import ctypes
    except ImportError:
        return None

    # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen
    # manpage says, "If filename is NULL, then the returned handle is for the
    # main program". This way we can let the linker do the work to figure out
    # which libc our process is actually using.
    #
    # We must also handle the special case where the executable is not a
    # dynamically linked executable. This can occur when using musl libc,
    # for example. In this situation, dlopen() will error, leading to an
    # OSError. Interestingly, at least in the case of musl, there is no
    # errno set on the OSError. The single string argument used to construct
    # OSError comes from libc itself and is therefore not portable to
    # hard code here. In any case, failure to call dlopen() means we
    # can proceed, so we bail on our attempt.
    try:
        process_namespace = ctypes.CDLL(None)
    except OSError:
        return None

    try:
        gnu_get_libc_version = process_namespace.gnu_get_libc_version
    except AttributeError:
        # Symbol doesn't exist -> therefore, we are not linked to
        # glibc.
        return None

    # Call gnu_get_libc_version, which returns a string like "2.5"
    gnu_get_libc_version.restype = ctypes.c_char_p
    version_str: str = gnu_get_libc_version()
    # py2 / py3 compatibility:
    if not isinstance(version_str, str):
        version_str = version_str.decode("ascii")

    return version_str


def _glibc_version_string() -> Optional[str]:
    """Returns glibc version string, or None if not using glibc."""
    return _glibc_version_string_confstr() or _glibc_version_string_ctypes()


def _parse_glibc_version(version_str: str) -> Tuple[int, int]:
    """Parse glibc version.

    We use a regexp instead of str.split because we want to discard any
    random junk that might come after the minor version -- this might happen
    in patched/forked versions of glibc (e.g. Linaro's version of glibc
    uses version strings like "2.20-2014.11"). See gh-3588.
    """
    m = re.match(r"(?P[0-9]+)\.(?P[0-9]+)", version_str)
    if not m:
        warnings.warn(
            f"Expected glibc version with 2 components major.minor,"
            f" got: {version_str}",
            RuntimeWarning,
        )
        return -1, -1
    return int(m.group("major")), int(m.group("minor"))


@functools.lru_cache()
def _get_glibc_version() -> Tuple[int, int]:
    version_str = _glibc_version_string()
    if version_str is None:
        return (-1, -1)
    return _parse_glibc_version(version_str)


# From PEP 513, PEP 600
def _is_compatible(arch: str, version: _GLibCVersion) -> bool:
    sys_glibc = _get_glibc_version()
    if sys_glibc < version:
        return False
    # Check for presence of _manylinux module.
    try:
        import _manylinux  # noqa
    except ImportError:
        return True
    if hasattr(_manylinux, "manylinux_compatible"):
        result = _manylinux.manylinux_compatible(version[0], version[1], arch)
        if result is not None:
            return bool(result)
        return True
    if version == _GLibCVersion(2, 5):
        if hasattr(_manylinux, "manylinux1_compatible"):
            return bool(_manylinux.manylinux1_compatible)
    if version == _GLibCVersion(2, 12):
        if hasattr(_manylinux, "manylinux2010_compatible"):
            return bool(_manylinux.manylinux2010_compatible)
    if version == _GLibCVersion(2, 17):
        if hasattr(_manylinux, "manylinux2014_compatible"):
            return bool(_manylinux.manylinux2014_compatible)
    return True


_LEGACY_MANYLINUX_MAP = {
    # CentOS 7 w/ glibc 2.17 (PEP 599)
    (2, 17): "manylinux2014",
    # CentOS 6 w/ glibc 2.12 (PEP 571)
    (2, 12): "manylinux2010",
    # CentOS 5 w/ glibc 2.5 (PEP 513)
    (2, 5): "manylinux1",
}


def platform_tags(archs: Sequence[str]) -> Iterator[str]:
    """Generate manylinux tags compatible to the current platform.

    :param archs: Sequence of compatible architectures.
        The first one shall be the closest to the actual architecture and be the part of
        platform tag after the ``linux_`` prefix, e.g. ``x86_64``.
        The ``linux_`` prefix is assumed as a prerequisite for the current platform to
        be manylinux-compatible.

    :returns: An iterator of compatible manylinux tags.
    """
    if not _have_compatible_abi(sys.executable, archs):
        return
    # Oldest glibc to be supported regardless of architecture is (2, 17).
    too_old_glibc2 = _GLibCVersion(2, 16)
    if set(archs) & {"x86_64", "i686"}:
        # On x86/i686 also oldest glibc to be supported is (2, 5).
        too_old_glibc2 = _GLibCVersion(2, 4)
    current_glibc = _GLibCVersion(*_get_glibc_version())
    glibc_max_list = [current_glibc]
    # We can assume compatibility across glibc major versions.
    # https://sourceware.org/bugzilla/show_bug.cgi?id=24636
    #
    # Build a list of maximum glibc versions so that we can
    # output the canonical list of all glibc from current_glibc
    # down to too_old_glibc2, including all intermediary versions.
    for glibc_major in range(current_glibc.major - 1, 1, -1):
        glibc_minor = _LAST_GLIBC_MINOR[glibc_major]
        glibc_max_list.append(_GLibCVersion(glibc_major, glibc_minor))
    for arch in archs:
        for glibc_max in glibc_max_list:
            if glibc_max.major == too_old_glibc2.major:
                min_minor = too_old_glibc2.minor
            else:
                # For other glibc major versions oldest supported is (x, 0).
                min_minor = -1
            for glibc_minor in range(glibc_max.minor, min_minor, -1):
                glibc_version = _GLibCVersion(glibc_max.major, glibc_minor)
                tag = "manylinux_{}_{}".format(*glibc_version)
                if _is_compatible(arch, glibc_version):
                    yield f"{tag}_{arch}"
                # Handle the legacy manylinux1, manylinux2010, manylinux2014 tags.
                if glibc_version in _LEGACY_MANYLINUX_MAP:
                    legacy_tag = _LEGACY_MANYLINUX_MAP[glibc_version]
                    if _is_compatible(arch, glibc_version):
                        yield f"{legacy_tag}_{arch}"
PK~\͆node-gyp/gyp/gyp.batnu[@rem Copyright (c) 2009 Google Inc. All rights reserved.
@rem Use of this source code is governed by a BSD-style license that can be
@rem found in the LICENSE file.

@python "%~dp0gyp_main.py" %*
PK~\=$4node-gyp/gyp/gyp_main.pynu[#!/usr/bin/env python3

# Copyright (c) 2009 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import os
import sys
import subprocess


def IsCygwin():
    # Function copied from pylib/gyp/common.py
    try:
        out = subprocess.Popen(
            "uname", stdout=subprocess.PIPE, stderr=subprocess.STDOUT
        )
        stdout, _ = out.communicate()
        return "CYGWIN" in stdout.decode("utf-8")
    except Exception:
        return False


def UnixifyPath(path):
    try:
        if not IsCygwin():
            return path
        out = subprocess.Popen(
            ["cygpath", "-u", path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT
        )
        stdout, _ = out.communicate()
        return stdout.decode("utf-8")
    except Exception:
        return path


# Make sure we're using the version of pylib in this repo, not one installed
# elsewhere on the system. Also convert to Unix style path on Cygwin systems,
# else the 'gyp' library will not be found
path = UnixifyPath(sys.argv[0])
sys.path.insert(0, os.path.join(os.path.dirname(path), "pylib"))
import gyp  # noqa: E402

if __name__ == "__main__":
    sys.exit(gyp.script_main())
PK~\5%node-gyp/gyp/LICENSEnu[Copyright (c) 2020 Node.js contributors. All rights reserved.
Copyright (c) 2009 Google Inc. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

   * Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
   * Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
   * Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
PK~\Ynode-gyp/gyp/gypnu[#!/bin/sh
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

set -e
base=$(dirname "$0")
exec python "${base}/gyp_main.py" "$@"
PK~\IjVnode-gyp/gyp/pyproject.tomlnu[[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"

[project]
name = "gyp-next"
version = "0.16.1"
authors = [
  { name="Node.js contributors", email="ryzokuken@disroot.org" },
]
description = "A fork of the GYP build system for use in the Node.js projects"
readme = "README.md"
license = { file="LICENSE" }
requires-python = ">=3.8"
# The Python module "packaging" is vendored in the "pylib/packaging" directory to support Python >= 3.12.
# dependencies = ["packaging>=23.1"]  # Uncomment this line if the vendored version is removed.
classifiers = [
    "Development Status :: 3 - Alpha",
    "Environment :: Console",
    "Intended Audience :: Developers",
    "License :: OSI Approved :: BSD License",
    "Natural Language :: English",
    "Programming Language :: Python",
    "Programming Language :: Python :: 3",
    "Programming Language :: Python :: 3.8",
    "Programming Language :: Python :: 3.9",
    "Programming Language :: Python :: 3.10",
    "Programming Language :: Python :: 3.11",
]

[project.optional-dependencies]
dev = ["flake8", "ruff", "pytest"]

[project.scripts]
gyp = "gyp:script_main"

[project.urls]
"Homepage" = "https://github.com/nodejs/gyp-next"

[tool.ruff]
lint.select = [
  "C4",   # flake8-comprehensions
  "C90",  # McCabe cyclomatic complexity
  "DTZ",  # flake8-datetimez
  "E",    # pycodestyle
  "F",    # Pyflakes
  "G",    # flake8-logging-format
  "ICN",  # flake8-import-conventions
  "INT",  # flake8-gettext
  "PL",   # Pylint
  "PYI",  # flake8-pyi
  "RSE",  # flake8-raise
  "RUF",  # Ruff-specific rules
  "T10",  # flake8-debugger
  "TCH",  # flake8-type-checking
  "TID",  # flake8-tidy-imports
  "UP",   # pyupgrade
  "W",    # pycodestyle
  "YTT",  # flake8-2020
  # "A",    # flake8-builtins
  # "ANN",  # flake8-annotations
  # "ARG",  # flake8-unused-arguments
  # "B",    # flake8-bugbear
  # "BLE",  # flake8-blind-except
  # "COM",  # flake8-commas
  # "D",    # pydocstyle
  # "DJ",   # flake8-django
  # "EM",   # flake8-errmsg
  # "ERA",  # eradicate
  # "EXE",  # flake8-executable
  # "FBT",  # flake8-boolean-trap
  # "I",    # isort
  # "INP",  # flake8-no-pep420
  # "ISC",  # flake8-implicit-str-concat
  # "N",    # pep8-naming
  # "NPY",  # NumPy-specific rules
  # "PD",   # pandas-vet
  # "PGH",  # pygrep-hooks
  # "PIE",  # flake8-pie
  # "PT",   # flake8-pytest-style
  # "PTH",  # flake8-use-pathlib
  # "Q",    # flake8-quotes
  # "RET",  # flake8-return
  # "S",    # flake8-bandit
  # "SIM",  # flake8-simplify
  # "SLF",  # flake8-self
  # "T20",  # flake8-print
  # "TRY",  # tryceratops
]
lint.ignore = [
  "E721",
  "PLC1901",
  "PLR0402",
  "PLR1714",
  "PLR2004",
  "PLR5501",
  "PLW0603",
  "PLW2901",
  "PYI024",
  "RUF005",
  "RUF012",
  "UP031",
]
extend-exclude = ["pylib/packaging"]
line-length = 88
target-version = "py37"

[tool.ruff.lint.mccabe]
max-complexity = 101

[tool.ruff.lint.pylint]
max-args = 11
max-branches = 108
max-returns = 10
max-statements = 286

[tool.setuptools]
package-dir = {"" = "pylib"}
packages = ["gyp", "gyp.generator"]
PK~\'node-gyp/gyp/data/win/large-pdb-shim.ccnu[// Copyright (c) 2013 Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This file is used to generate an empty .pdb -- with a 4KB pagesize -- that is
// then used during the final link for modules that have large PDBs. Otherwise,
// the linker will generate a pdb with a page size of 1KB, which imposes a limit
// of 1GB on the .pdb. By generating an initial empty .pdb with the compiler
// (rather than the linker), this limit is avoided. With this in place PDBs may
// grow to 2GB.
//
// This file is referenced by the msvs_large_pdb mechanism in MSVSUtil.py.
PK~\%Cnode-gyp/gyp/test_gyp.pynu[#!/usr/bin/env python3
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""gyptest.py -- test runner for GYP tests."""


import argparse
import os
import platform
import subprocess
import sys
import time


def is_test_name(f):
    return f.startswith("gyptest") and f.endswith(".py")


def find_all_gyptest_files(directory):
    result = []
    for root, dirs, files in os.walk(directory):
        result.extend([os.path.join(root, f) for f in files if is_test_name(f)])
    result.sort()
    return result


def main(argv=None):
    if argv is None:
        argv = sys.argv

    parser = argparse.ArgumentParser()
    parser.add_argument("-a", "--all", action="store_true", help="run all tests")
    parser.add_argument("-C", "--chdir", action="store", help="change to directory")
    parser.add_argument(
        "-f",
        "--format",
        action="store",
        default="",
        help="run tests with the specified formats",
    )
    parser.add_argument(
        "-G",
        "--gyp_option",
        action="append",
        default=[],
        help="Add -G options to the gyp command line",
    )
    parser.add_argument(
        "-l", "--list", action="store_true", help="list available tests and exit"
    )
    parser.add_argument(
        "-n",
        "--no-exec",
        action="store_true",
        help="no execute, just print the command line",
    )
    parser.add_argument(
        "--path", action="append", default=[], help="additional $PATH directory"
    )
    parser.add_argument(
        "-q",
        "--quiet",
        action="store_true",
        help="quiet, don't print anything unless there are failures",
    )
    parser.add_argument(
        "-v",
        "--verbose",
        action="store_true",
        help="print configuration info and test results.",
    )
    parser.add_argument("tests", nargs="*")
    args = parser.parse_args(argv[1:])

    if args.chdir:
        os.chdir(args.chdir)

    if args.path:
        extra_path = [os.path.abspath(p) for p in args.path]
        extra_path = os.pathsep.join(extra_path)
        os.environ["PATH"] = extra_path + os.pathsep + os.environ["PATH"]

    if not args.tests:
        if not args.all:
            sys.stderr.write("Specify -a to get all tests.\n")
            return 1
        args.tests = ["test"]

    tests = []
    for arg in args.tests:
        if os.path.isdir(arg):
            tests.extend(find_all_gyptest_files(os.path.normpath(arg)))
        else:
            if not is_test_name(os.path.basename(arg)):
                print(arg, "is not a valid gyp test name.", file=sys.stderr)
                sys.exit(1)
            tests.append(arg)

    if args.list:
        for test in tests:
            print(test)
        sys.exit(0)

    os.environ["PYTHONPATH"] = os.path.abspath("test/lib")

    if args.verbose:
        print_configuration_info()

    if args.gyp_option and not args.quiet:
        print("Extra Gyp options: %s\n" % args.gyp_option)

    if args.format:
        format_list = args.format.split(",")
    else:
        format_list = {
            "aix5": ["make"],
            "os400": ["make"],
            "freebsd7": ["make"],
            "freebsd8": ["make"],
            "openbsd5": ["make"],
            "cygwin": ["msvs"],
            "win32": ["msvs", "ninja"],
            "linux": ["make", "ninja"],
            "linux2": ["make", "ninja"],
            "linux3": ["make", "ninja"],
            # TODO: Re-enable xcode-ninja.
            # https://bugs.chromium.org/p/gyp/issues/detail?id=530
            # 'darwin':   ['make', 'ninja', 'xcode', 'xcode-ninja'],
            "darwin": ["make", "ninja", "xcode"],
        }[sys.platform]

    gyp_options = []
    for option in args.gyp_option:
        gyp_options += ["-G", option]

    runner = Runner(format_list, tests, gyp_options, args.verbose)
    runner.run()

    if not args.quiet:
        runner.print_results()

    return 1 if runner.failures else 0


def print_configuration_info():
    print("Test configuration:")
    if sys.platform == "darwin":
        sys.path.append(os.path.abspath("test/lib"))
        import TestMac

        print(f"  Mac {platform.mac_ver()[0]} {platform.mac_ver()[2]}")
        print(f"  Xcode {TestMac.Xcode.Version()}")
    elif sys.platform == "win32":
        sys.path.append(os.path.abspath("pylib"))
        import gyp.MSVSVersion

        print("  Win %s %s\n" % platform.win32_ver()[0:2])
        print("  MSVS %s" % gyp.MSVSVersion.SelectVisualStudioVersion().Description())
    elif sys.platform in ("linux", "linux2"):
        print("  Linux %s" % " ".join(platform.linux_distribution()))
    print(f"  Python {platform.python_version()}")
    print(f"  PYTHONPATH={os.environ['PYTHONPATH']}")
    print()


class Runner:
    def __init__(self, formats, tests, gyp_options, verbose):
        self.formats = formats
        self.tests = tests
        self.verbose = verbose
        self.gyp_options = gyp_options
        self.failures = []
        self.num_tests = len(formats) * len(tests)
        num_digits = len(str(self.num_tests))
        self.fmt_str = "[%%%dd/%%%dd] (%%s) %%s" % (num_digits, num_digits)
        self.isatty = sys.stdout.isatty() and not self.verbose
        self.env = os.environ.copy()
        self.hpos = 0

    def run(self):
        run_start = time.time()

        i = 1
        for fmt in self.formats:
            for test in self.tests:
                self.run_test(test, fmt, i)
                i += 1

        if self.isatty:
            self.erase_current_line()

        self.took = time.time() - run_start

    def run_test(self, test, fmt, i):
        if self.isatty:
            self.erase_current_line()

        msg = self.fmt_str % (i, self.num_tests, fmt, test)
        self.print_(msg)

        start = time.time()
        cmd = [sys.executable, test] + self.gyp_options
        self.env["TESTGYP_FORMAT"] = fmt
        proc = subprocess.Popen(
            cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=self.env
        )
        proc.wait()
        took = time.time() - start

        stdout = proc.stdout.read().decode("utf8")
        if proc.returncode == 2:
            res = "skipped"
        elif proc.returncode:
            res = "failed"
            self.failures.append(f"({test}) {fmt}")
        else:
            res = "passed"
        res_msg = f" {res} {took:.3f}s"
        self.print_(res_msg)

        if stdout and not stdout.endswith(("PASSED\n", "NO RESULT\n")):
            print()
            print("\n".join(f"    {line}" for line in stdout.splitlines()))
        elif not self.isatty:
            print()

    def print_(self, msg):
        print(msg, end="")
        index = msg.rfind("\n")
        if index == -1:
            self.hpos += len(msg)
        else:
            self.hpos = len(msg) - index
        sys.stdout.flush()

    def erase_current_line(self):
        print("\b" * self.hpos + " " * self.hpos + "\b" * self.hpos, end="")
        sys.stdout.flush()
        self.hpos = 0

    def print_results(self):
        num_failures = len(self.failures)
        if num_failures:
            print()
            if num_failures == 1:
                print("Failed the following test:")
            else:
                print("Failed the following %d tests:" % num_failures)
            print("\t" + "\n\t".join(sorted(self.failures)))
            print()
        print(
            "Ran %d tests in %.3fs, %d failed."
            % (self.num_tests, self.took, num_failures)
        )
        print()


if __name__ == "__main__":
    sys.exit(main())
PK~\&node-gyp/.release-please-manifest.jsonnu[{
    ".": "10.1.0"
}
PK~\}44node-gyp/addon.gypinu[{
  'variables' : {
    'node_engine_include_dir%': 'deps/v8/include',
    'node_host_binary%': 'node',
    'node_with_ltcg%': 'true',
  },
  'target_defaults': {
    'type': 'loadable_module',
    'win_delay_load_hook': 'true',
    'product_prefix': '',

    'conditions': [
      [ 'node_engine=="chakracore"', {
        'variables': {
          'node_engine_include_dir%': 'deps/chakrashim/include'
        },
      }]
    ],

    'include_dirs': [
      '<(node_root_dir)/include/node',
      '<(node_root_dir)/src',
      '<(node_root_dir)/deps/openssl/config',
      '<(node_root_dir)/deps/openssl/openssl/include',
      '<(node_root_dir)/deps/uv/include',
      '<(node_root_dir)/deps/zlib',
      '<(node_root_dir)/<(node_engine_include_dir)'
    ],
    'defines!': [
      'BUILDING_UV_SHARED=1',  # Inherited from common.gypi.
      'BUILDING_V8_SHARED=1',  # Inherited from common.gypi.
    ],
    'defines': [
      'NODE_GYP_MODULE_NAME=>(_target_name)',
      'USING_UV_SHARED=1',
      'USING_V8_SHARED=1',
      # Warn when using deprecated V8 APIs.
      'V8_DEPRECATION_WARNINGS=1'
    ],

    'target_conditions': [
      ['_type=="loadable_module"', {
        'product_extension': 'node',
        'defines': [
          'BUILDING_NODE_EXTENSION'
        ],
        'xcode_settings': {
          'OTHER_LDFLAGS': [
            '-undefined dynamic_lookup'
          ],
        },
      }],

      ['_type=="static_library"', {
        # set to `1` to *disable* the -T thin archive 'ld' flag.
        # older linkers don't support this flag.
        'standalone_static_library': '<(standalone_static_library)'
      }],

      ['_type!="executable"', {
        'conditions': [
          [ 'OS=="android"', {
            'cflags!': [ '-fPIE' ],
          }]
        ]
      }],

      ['_win_delay_load_hook=="true"', {
        # If the addon specifies `'win_delay_load_hook': 'true'` in its
        # binding.gyp, link a delay-load hook into the DLL. This hook ensures
        # that the addon will work regardless of whether the node/iojs binary
        # is named node.exe, iojs.exe, or something else.
        'conditions': [
          [ 'OS=="win"', {
            'defines': [ 'HOST_BINARY=\"<(node_host_binary)<(EXECUTABLE_SUFFIX)\"', ],
            'sources': [
              '<(node_gyp_dir)/src/win_delay_load_hook.cc',
            ],
            'msvs_settings': {
              'VCLinkerTool': {
                'DelayLoadDLLs': [ '<(node_host_binary)<(EXECUTABLE_SUFFIX)' ],
                # Don't print a linker warning when no imports from either .exe
                # are used.
                'AdditionalOptions': [ '/ignore:4199' ],
              },
            },
          }],
        ],
      }],
    ],

    'conditions': [
      [ 'OS=="mac"', {
        'defines': [
          '_DARWIN_USE_64_BIT_INODE=1'
        ],
        'xcode_settings': {
          'DYLIB_INSTALL_NAME_BASE': '@rpath'
        },
      }],
      [ 'OS=="aix"', {
        'ldflags': [
          '-Wl,-bimport:<(node_exp_file)'
        ],
      }],
      [ 'OS=="os400"', {
        'ldflags': [
          '-Wl,-bimport:<(node_exp_file)'
        ],
      }],
      [ 'OS=="zos"', {
        'conditions': [
          [ '"'
          # needs to have dll-interface to be used by
          # clients of class 'node::ObjectWrap'
          4251
        ],
      }, {
        # OS!="win"
        'defines': [
          '_LARGEFILE_SOURCE',
          '_FILE_OFFSET_BITS=64'
        ],
      }],
      [ 'OS in "freebsd openbsd netbsd solaris android" or \
         (OS=="linux" and target_arch!="ia32")', {
        'cflags': [ '-fPIC' ],
      }],
    ]
  }
}
PK~\Ŗ2node-gyp/SECURITY.mdnu[If you believe you have found a security issue in the software in this
repository, please consult https://github.com/nodejs/node/blob/HEAD/SECURITY.md.PK~\p}V
V
node-gyp/bin/node-gyp.jsnu[#!/usr/bin/env node

'use strict'

process.title = 'node-gyp'

const envPaths = require('env-paths')
const gyp = require('../')
const log = require('../lib/log')
const os = require('os')

/**
 * Process and execute the selected commands.
 */

const prog = gyp()
let completed = false
prog.parseArgv(process.argv)
prog.devDir = prog.opts.devdir

const homeDir = os.homedir()
if (prog.devDir) {
  prog.devDir = prog.devDir.replace(/^~/, homeDir)
} else if (homeDir) {
  prog.devDir = envPaths('node-gyp', { suffix: '' }).cache
} else {
  throw new Error(
    "node-gyp requires that the user's home directory is specified " +
    'in either of the environmental variables HOME or USERPROFILE. ' +
    'Overide with: --devdir /path/to/.node-gyp')
}

if (prog.todo.length === 0) {
  if (~process.argv.indexOf('-v') || ~process.argv.indexOf('--version')) {
    log.stdout('v%s', prog.version)
  } else {
    log.stdout('%s', prog.usage())
  }
  process.exit(0)
}

log.info('it worked if it ends with', 'ok')
log.verbose('cli', process.argv)
log.info('using', 'node-gyp@%s', prog.version)
log.info('using', 'node@%s | %s | %s', process.versions.node, process.platform, process.arch)

/**
 * Change dir if -C/--directory was passed.
 */

const dir = prog.opts.directory
if (dir) {
  const fs = require('fs')
  try {
    const stat = fs.statSync(dir)
    if (stat.isDirectory()) {
      log.info('chdir', dir)
      process.chdir(dir)
    } else {
      log.warn('chdir', dir + ' is not a directory')
    }
  } catch (e) {
    if (e.code === 'ENOENT') {
      log.warn('chdir', dir + ' is not a directory')
    } else {
      log.warn('chdir', 'error during chdir() "%s"', e.message)
    }
  }
}

async function run () {
  const command = prog.todo.shift()
  if (!command) {
    // done!
    completed = true
    log.info('ok')
    return
  }

  try {
    const args = await prog.commands[command.name](command.args) ?? []

    if (command.name === 'list') {
      if (args.length) {
        args.forEach((version) => log.stdout(version))
      } else {
        log.stdout('No node development files installed. Use `node-gyp install` to install a version.')
      }
    } else if (args.length >= 1) {
      log.stdout(...args.slice(1))
    }

    // now run the next command in the queue
    return run()
  } catch (err) {
    log.error(command.name + ' error')
    log.error('stack', err.stack)
    errorMessage()
    log.error('not ok')
    return process.exit(1)
  }
}

process.on('exit', function (code) {
  if (!completed && !code) {
    log.error('Completion callback never invoked!')
    issueMessage()
    process.exit(6)
  }
})

process.on('uncaughtException', function (err) {
  log.error('UNCAUGHT EXCEPTION')
  log.error('stack', err.stack)
  issueMessage()
  process.exit(7)
})

function errorMessage () {
  // copied from npm's lib/utils/error-handler.js
  const os = require('os')
  log.error('System', os.type() + ' ' + os.release())
  log.error('command', process.argv
    .map(JSON.stringify).join(' '))
  log.error('cwd', process.cwd())
  log.error('node -v', process.version)
  log.error('node-gyp -v', 'v' + prog.package.version)
}

function issueMessage () {
  errorMessage()
  log.error('', ['Node-gyp failed to build your package.',
    'Try to update npm and/or node-gyp and if it does not help file an issue with the package author.'
  ].join('\n'))
}

// start running the given commands!
run()
PK~\Z--node-gyp/README.mdnu[# `node-gyp` - Node.js native addon build tool

[![Build Status](https://github.com/nodejs/node-gyp/workflows/Tests/badge.svg?branch=main)](https://github.com/nodejs/node-gyp/actions?query=workflow%3ATests+branch%3Amain)
![npm](https://img.shields.io/npm/dm/node-gyp)

`node-gyp` is a cross-platform command-line tool written in Node.js for
compiling native addon modules for Node.js. It contains a vendored copy of the
[gyp-next](https://github.com/nodejs/gyp-next) project that was previously used
by the Chromium team and extended to support the development of Node.js native
addons.

Note that `node-gyp` is _not_ used to build Node.js itself.

All current and LTS target versions of Node.js are supported. Depending on what version of Node.js is actually installed on your system
`node-gyp` downloads the necessary development files or headers for the target version. List of stable Node.js versions can be found on [Node.js website](https://nodejs.org/en/about/previous-releases).

## Features

 * The same build commands work on any of the supported platforms
 * Supports the targeting of different versions of Node.js

## Installation

You can install `node-gyp` using `npm`:

``` bash
npm install -g node-gyp
```

Depending on your operating system, you will need to install:

### On Unix

   * [A supported version of Python](https://devguide.python.org/versions/)
   * `make`
   * A proper C/C++ compiler toolchain, like [GCC](https://gcc.gnu.org)

### On macOS

   * [A supported version of Python](https://devguide.python.org/versions/)
   * `Xcode Command Line Tools` which will install `clang`, `clang++`, and `make`.
     * Install the `Xcode Command Line Tools` standalone by running `xcode-select --install`. -- OR --
     * Alternatively, if you already have the [full Xcode installed](https://developer.apple.com/xcode/download/), you can install the Command Line Tools under the menu `Xcode -> Open Developer Tool -> More Developer Tools...`.


### On Windows

Install the current [version of Python](https://devguide.python.org/versions/) from the
[Microsoft Store](https://apps.microsoft.com/store/search?publisher=Python+Software+Foundation).

Install tools and configuration manually:
   * Install Visual C++ Build Environment: For Visual Studio 2019 or later, use the `Desktop development with C++` workload from [Visual Studio Community](https://visualstudio.microsoft.com/thank-you-downloading-visual-studio/?sku=Community).  For a version older than Visual Studio 2019, install [Visual Studio Build Tools](https://visualstudio.microsoft.com/thank-you-downloading-visual-studio/?sku=BuildTools) with the `Visual C++ build tools` option.

   If the above steps didn't work for you, please visit [Microsoft's Node.js Guidelines for Windows](https://github.com/Microsoft/nodejs-guidelines/blob/master/windows-environment.md#compiling-native-addon-modules) for additional tips.

   To target native ARM64 Node.js on Windows on ARM, add the components "Visual C++ compilers and libraries for ARM64" and "Visual C++ ATL for ARM64".

   To use the native ARM64 C++ compiler on Windows on ARM, ensure that you have Visual Studio 2022 [17.4 or later](https://devblogs.microsoft.com/visualstudio/arm64-visual-studio-is-officially-here/) installed.

It's advised to install following Powershell module: [VSSetup](https://github.com/microsoft/vssetup.powershell) using `Install-Module VSSetup -Scope CurrentUser`.
This will make Visual Studio detection logic to use more flexible and accessible method, avoiding Powershell's `ConstrainedLanguage` mode.

### Configuring Python Dependency

`node-gyp` requires that you have installed a [supported version of Python](https://devguide.python.org/versions/).
If you have multiple versions of Python installed, you can identify which version
`node-gyp` should use in one of the following ways:

1. by setting the `--python` command-line option, e.g.:

``` bash
node-gyp  --python /path/to/executable/python
```

2. If `node-gyp` is called by way of `npm`, *and* you have multiple versions of
Python installed, then you can set the `npm_config_python` environment variable
to the appropriate path:
``` bash
export npm_config_python=/path/to/executable/python
```
    Or on Windows:
```console
py --list-paths  # To see the installed Python versions
set npm_config_python=C:\path\to\python.exe
```

3. If the `PYTHON` environment variable is set to the path of a Python executable,
then that version will be used if it is a supported version.

4. If the `NODE_GYP_FORCE_PYTHON` environment variable is set to the path of a
Python executable, it will be used instead of any of the other configured or
built-in Python search paths. If it's not a compatible version, no further
searching will be done.

### Build for Third Party Node.js Runtimes

When building modules for third-party Node.js runtimes like Electron, which have
different build configurations from the official Node.js distribution, you
should use `--dist-url` or `--nodedir` flags to specify the headers of the
runtime to build for.

Also when `--dist-url` or `--nodedir` flags are passed, node-gyp will use the
`config.gypi` shipped in the headers distribution to generate build
configurations, which is different from the default mode that would use the
`process.config` object of the running Node.js instance.

Some old versions of Electron shipped malformed `config.gypi` in their headers
distributions, and you might need to pass `--force-process-config` to node-gyp
to work around configuration errors.

## How to Use

To compile your native addon first go to its root directory:

``` bash
cd my_node_addon
```

The next step is to generate the appropriate project build files for the current
platform. Use `configure` for that:

``` bash
node-gyp configure
```

Auto-detection fails for Visual C++ Build Tools 2015, so `--msvs_version=2015`
needs to be added (not needed when run by npm as configured above):
``` bash
node-gyp configure --msvs_version=2015
```

__Note__: The `configure` step looks for a `binding.gyp` file in the current
directory to process. See below for instructions on creating a `binding.gyp` file.

Now you will have either a `Makefile` (on Unix platforms) or a `vcxproj` file
(on Windows) in the `build/` directory. Next, invoke the `build` command:

``` bash
node-gyp build
```

Now you have your compiled `.node` bindings file! The compiled bindings end up
in `build/Debug/` or `build/Release/`, depending on the build mode. At this point,
you can require the `.node` file with Node.js and run your tests!

__Note:__ To create a _Debug_ build of the bindings file, pass the `--debug` (or
`-d`) switch when running either the `configure`, `build` or `rebuild` commands.

## The `binding.gyp` file

A `binding.gyp` file describes the configuration to build your module, in a
JSON-like format. This file gets placed in the root of your package, alongside
`package.json`.

A barebones `gyp` file appropriate for building a Node.js addon could look like:

```python
{
  "targets": [
    {
      "target_name": "binding",
      "sources": [ "src/binding.cc" ]
    }
  ]
}
```

## Further reading

The **[docs](./docs/)** directory contains additional documentation on specific node-gyp topics that may be useful if you are experiencing problems installing or building addons using node-gyp.

Some additional resources for Node.js native addons and writing `gyp` configuration files:

 * ["Going Native" a nodeschool.io tutorial](http://nodeschool.io/#goingnative)
 * ["Hello World" node addon example](https://github.com/nodejs/node/tree/main/test/addons/hello-world)
 * [gyp user documentation](https://gyp.gsrc.io/docs/UserDocumentation.md)
 * [gyp input format reference](https://gyp.gsrc.io/docs/InputFormatReference.md)
 * [*"binding.gyp" files out in the wild* wiki page](./docs/binding.gyp-files-in-the-wild.md)

## Commands

`node-gyp` responds to the following commands:

| **Command**   | **Description**
|:--------------|:---------------------------------------------------------------
| `help`        | Shows the help dialog
| `build`       | Invokes `make`/`msbuild.exe` and builds the native addon
| `clean`       | Removes the `build` directory if it exists
| `configure`   | Generates project build files for the current platform
| `rebuild`     | Runs `clean`, `configure` and `build` all in a row
| `install`     | Installs Node.js header files for the given version
| `list`        | Lists the currently installed Node.js header versions
| `remove`      | Removes the Node.js header files for the given version


## Command Options

`node-gyp` accepts the following command options:

| **Command**                       | **Description**
|:----------------------------------|:------------------------------------------
| `-j n`, `--jobs n`                | Run `make` in parallel. The value `max` will use all available CPU cores
| `--target=v6.2.1`                 | Node.js version to build for (default is `process.version`)
| `--silly`, `--loglevel=silly`     | Log all progress to console
| `--verbose`, `--loglevel=verbose` | Log most progress to console
| `--silent`, `--loglevel=silent`   | Don't log anything to console
| `debug`, `--debug`                | Make Debug build (default is `Release`)
| `--release`, `--no-debug`         | Make Release build
| `-C $dir`, `--directory=$dir`     | Run command in different directory
| `--make=$make`                    | Override `make` command (e.g. `gmake`)
| `--thin=yes`                      | Enable thin static libraries
| `--arch=$arch`                    | Set target architecture (e.g. ia32)
| `--tarball=$path`                 | Get headers from a local tarball
| `--devdir=$path`                  | SDK download directory (default is OS cache directory)
| `--ensure`                        | Don't reinstall headers if already present
| `--dist-url=$url`                 | Download header tarball from custom URL
| `--proxy=$url`                    | Set HTTP(S) proxy for downloading header tarball
| `--noproxy=$urls`                 | Set urls to ignore proxies when downloading header tarball
| `--cafile=$cafile`                | Override default CA chain (to download tarball)
| `--nodedir=$path`                 | Set the path to the node source code
| `--python=$path`                  | Set path to the Python binary
| `--msvs_version=$version`         | Set Visual Studio version (Windows only)
| `--solution=$solution`            | Set Visual Studio Solution version (Windows only)
| `--force-process-config`          | Force using runtime's `process.config` object to generate `config.gypi` file

## Configuration

### Environment variables

Use the form `npm_config_OPTION_NAME` for any of the command options listed
above (dashes in option names should be replaced by underscores).

For example, to set `devdir` equal to `/tmp/.gyp`, you would:

Run this on Unix:

```bash
export npm_config_devdir=/tmp/.gyp
```

Or this on Windows:

```console
set npm_config_devdir=c:\temp\.gyp
```

### `npm` configuration for npm versions before v9

Use the form `OPTION_NAME` for any of the command options listed above.

For example, to set `devdir` equal to `/tmp/.gyp`, you would run:

```bash
npm config set [--global] devdir /tmp/.gyp
```

**Note:** Configuration set via `npm` will only be used when `node-gyp`
is run via `npm`, not when `node-gyp` is run directly.

## License

`node-gyp` is available under the MIT license. See the [LICENSE
file](LICENSE) for details.
PK~\#!$node-gyp/macOS_Catalina_acid_test.shnu[#!/bin/bash

pkgs=(
  "com.apple.pkg.DeveloperToolsCLILeo" # standalone
  "com.apple.pkg.DeveloperToolsCLI"    # from XCode
  "com.apple.pkg.CLTools_Executables"  # Mavericks
)

for pkg in "${pkgs[@]}"; do
  output=$(/usr/sbin/pkgutil --pkg-info "$pkg" 2>/dev/null)
  if [ "$output" ]; then
    version=$(echo "$output" | grep 'version' | cut -d' ' -f2)
    break
  fi
done

if [ "$version" ]; then
  echo "Command Line Tools version: $version"
else
  echo >&2 'Command Line Tools not found'
fi
PK~\@node-gyp/CHANGELOG.mdnu[# Changelog

## [10.1.0](https://github.com/nodejs/node-gyp/compare/v10.0.1...v10.1.0) (2024-03-13)


### Features

* improve visual studio detection ([#2957](https://github.com/nodejs/node-gyp/issues/2957)) ([109e3d4](https://github.com/nodejs/node-gyp/commit/109e3d4245504a7b75c99f578e1203c0ef4b518e))


### Core

* add support for locally installed headers ([#2964](https://github.com/nodejs/node-gyp/issues/2964)) ([3298731](https://github.com/nodejs/node-gyp/commit/329873141f0d3e3787d3c006801431da04e4ed0c))
* **deps:** bump actions/setup-python from 4 to 5 ([#2960](https://github.com/nodejs/node-gyp/issues/2960)) ([3f0df7e](https://github.com/nodejs/node-gyp/commit/3f0df7e9334e49e8c7f6fdbbb9e1e6c5a8cca53b))
* **deps:** bump google-github-actions/release-please-action ([#2961](https://github.com/nodejs/node-gyp/issues/2961)) ([b1f1808](https://github.com/nodejs/node-gyp/commit/b1f1808bfff0d51e6d3eb696ab6a5b89b7b9630c))
* print Python executable path using UTF-8 ([#2995](https://github.com/nodejs/node-gyp/issues/2995)) ([c472912](https://github.com/nodejs/node-gyp/commit/c4729129daa9bb5204246b857826fb391ac961e1))
* update supported vs versions ([#2959](https://github.com/nodejs/node-gyp/issues/2959)) ([391cc5b](https://github.com/nodejs/node-gyp/commit/391cc5b9b25cffe0cb2edcba3583414a771b4a15))


### Doc

* npm is currently v10 ([#2970](https://github.com/nodejs/node-gyp/issues/2970)) ([7705a22](https://github.com/nodejs/node-gyp/commit/7705a22f31a62076e9f8429780a459f4ad71ea4c))
* remove outdated Node versions from readme ([#2955](https://github.com/nodejs/node-gyp/issues/2955)) ([ae8478e](https://github.com/nodejs/node-gyp/commit/ae8478ec32d9b2fa71b591ac22cdf867ef2e9a7d))
* remove outdated update engines.node reference in 10.0.0 changelog ([b42e796](https://github.com/nodejs/node-gyp/commit/b42e7966177f006f3d1aab1d27885d8372c8ed01))


### Miscellaneous

* only run release please on push ([cff9ac2](https://github.com/nodejs/node-gyp/commit/cff9ac2c3083769a383e00bc60b91562f03116e3))
* upgrade release please action from v2 to v4 ([#2982](https://github.com/nodejs/node-gyp/issues/2982)) ([0035d8e](https://github.com/nodejs/node-gyp/commit/0035d8e9dc98b94f0bc8cd9023a6fa635003703e))

### [10.0.1](https://www.github.com/nodejs/node-gyp/compare/v10.0.0...v10.0.1) (2023-11-02)


### Bug Fixes

* use local `util` for `findAccessibleSync()` ([b39e681](https://www.github.com/nodejs/node-gyp/commit/b39e6819aa9e2c45107d6e60a4913ca036ebfbfd))


### Miscellaneous

* add parallel test logging ([7de1f5f](https://www.github.com/nodejs/node-gyp/commit/7de1f5f32d550d26d48fe4f76aed5866744edcba))
* lint fixes ([4e0ed99](https://www.github.com/nodejs/node-gyp/commit/4e0ed992566f43abc6e988af091ad07fde04acbf))
* use platform specific timeouts in tests ([a68586a](https://www.github.com/nodejs/node-gyp/commit/a68586a67d0af238300662cc062422b42820044d))

## [10.0.0](https://www.github.com/nodejs/node-gyp/compare/v9.4.0...v10.0.0) (2023-10-28)


### ⚠ BREAKING CHANGES

* use .npmignore file to limit which files are published (#2921)
* the `Gyp` class exported is now created using ECMAScript classes and therefore might have small differences to classes that were previously created with `util.inherits`.
* All internal functions have been coverted to return promises and no longer accept callbacks. This is not a breaking change for users but may be breaking to consumers of `node-gyp` if you are requiring internal functions directly.
* `node-gyp` now supports node `^16.14.0 || >=18.0.0`

### Features

* convert all internal functions to async/await ([355622f](https://www.github.com/nodejs/node-gyp/commit/355622f4aac3bd3056b9e03aac5fa2f42a4b3576))
* convert internal classes from util.inherits to classes ([d52997e](https://www.github.com/nodejs/node-gyp/commit/d52997e975b9da6e0cea3d9b99873e9ddc768679))
* drop node 14 support ([#2929](https://www.github.com/nodejs/node-gyp/issues/2929)) ([1b3bd34](https://www.github.com/nodejs/node-gyp/commit/1b3bd341b40f384988d03207ce8187e93ba609bc))
* drop rimraf dependency ([4a50fe3](https://www.github.com/nodejs/node-gyp/commit/4a50fe31574217c4b2a798fc72b19947a64ceea1))
* **gyp:** update gyp to v0.16.1 ([#2923](https://www.github.com/nodejs/node-gyp/issues/2923)) ([707927c](https://www.github.com/nodejs/node-gyp/commit/707927cd579205ef2b4b17e61c1cce24c056b452))
* replace npmlog with proc-log ([4a50fe3](https://www.github.com/nodejs/node-gyp/commit/4a50fe31574217c4b2a798fc72b19947a64ceea1))
* update engines.node to ^14.17.0 || ^16.13.0 || >=18.0.0 ([4a50fe3](https://www.github.com/nodejs/node-gyp/commit/4a50fe31574217c4b2a798fc72b19947a64ceea1))
* use .npmignore file to limit which files are published ([#2921](https://www.github.com/nodejs/node-gyp/issues/2921)) ([864a979](https://www.github.com/nodejs/node-gyp/commit/864a979930cf0ef5ad64bc887b901fa8955d058f))


### Bug Fixes

* create Python symlink only during builds, and clean it up after ([#2721](https://www.github.com/nodejs/node-gyp/issues/2721)) ([0f1f667](https://www.github.com/nodejs/node-gyp/commit/0f1f667b737d21905e283df100a2cb639993562a))
* promisify build command ([4a50fe3](https://www.github.com/nodejs/node-gyp/commit/4a50fe31574217c4b2a798fc72b19947a64ceea1))
* use fs/promises in favor of fs.promises ([4a50fe3](https://www.github.com/nodejs/node-gyp/commit/4a50fe31574217c4b2a798fc72b19947a64ceea1))


### Tests

* increase mocha timeout ([#2887](https://www.github.com/nodejs/node-gyp/issues/2887)) ([445c28f](https://www.github.com/nodejs/node-gyp/commit/445c28fabc5fbdf9c3bb3341fb70660a3530f6ad))
* update expired certs ([#2908](https://www.github.com/nodejs/node-gyp/issues/2908)) ([5746691](https://www.github.com/nodejs/node-gyp/commit/5746691a36f7b37019d4b8d4e9616aec43d20410))


### Doc

* Add note about Python symlinks (PR 2362) to CHANGELOG.md for 9.1.0 ([#2783](https://www.github.com/nodejs/node-gyp/issues/2783)) ([b3d41ae](https://www.github.com/nodejs/node-gyp/commit/b3d41aeb737ddd54cc292f363abc561dcc0a614e))
* README.md Do not hardcode the supported versions of Python ([#2880](https://www.github.com/nodejs/node-gyp/issues/2880)) ([bb93b94](https://www.github.com/nodejs/node-gyp/commit/bb93b946a9c74934b59164deb52128cf913c97d5))
* update applicable GitHub links from master to main ([#2843](https://www.github.com/nodejs/node-gyp/issues/2843)) ([d644ce4](https://www.github.com/nodejs/node-gyp/commit/d644ce48311edf090d0e920ad449e5766c757933))
* Update windows installation instructions in README.md ([#2882](https://www.github.com/nodejs/node-gyp/issues/2882)) ([c9caa2e](https://www.github.com/nodejs/node-gyp/commit/c9caa2ecf3c7deae68444ce8fabb32d2dca651cd))


### Core

* find python checks order changed on windows ([#2872](https://www.github.com/nodejs/node-gyp/issues/2872)) ([b030555](https://www.github.com/nodejs/node-gyp/commit/b030555cdb754d9c23906e7e707115cd077bbf76))
* glob@10.3.10 ([#2926](https://www.github.com/nodejs/node-gyp/issues/2926)) ([4bef1ec](https://www.github.com/nodejs/node-gyp/commit/4bef1ecc7554097d92beb397fbe1a546c5227545))
* glob@8.0.3 ([4a50fe3](https://www.github.com/nodejs/node-gyp/commit/4a50fe31574217c4b2a798fc72b19947a64ceea1))
* make-fetch-happen@13.0.0 ([#2927](https://www.github.com/nodejs/node-gyp/issues/2927)) ([059bb6f](https://www.github.com/nodejs/node-gyp/commit/059bb6fd41bb50955a9efbd97887773d60d53221))
* nopt@^7.0.0 ([4a50fe3](https://www.github.com/nodejs/node-gyp/commit/4a50fe31574217c4b2a798fc72b19947a64ceea1))
* standard@17.0.0 and fix linting errors ([4a50fe3](https://www.github.com/nodejs/node-gyp/commit/4a50fe31574217c4b2a798fc72b19947a64ceea1))
* which@3.0.0 ([4a50fe3](https://www.github.com/nodejs/node-gyp/commit/4a50fe31574217c4b2a798fc72b19947a64ceea1))
* which@4.0.0 ([#2928](https://www.github.com/nodejs/node-gyp/issues/2928)) ([e388255](https://www.github.com/nodejs/node-gyp/commit/e38825531403aabeae7abe58e76867f31b832f36))


### Miscellaneous

* add check engines script to CI ([#2922](https://www.github.com/nodejs/node-gyp/issues/2922)) ([21a7249](https://www.github.com/nodejs/node-gyp/commit/21a7249b40d8f95e7721e450fd18764adb1648a7))
* empty commit to add changelog entries from [#2770](https://www.github.com/nodejs/node-gyp/issues/2770) ([4a50fe3](https://www.github.com/nodejs/node-gyp/commit/4a50fe31574217c4b2a798fc72b19947a64ceea1))
* GitHub Workflows security hardening ([#2740](https://www.github.com/nodejs/node-gyp/issues/2740)) ([26683e9](https://www.github.com/nodejs/node-gyp/commit/26683e993df038fb94d89f2276f3535e4522d79a))
* misc testing fixes ([#2930](https://www.github.com/nodejs/node-gyp/issues/2930)) ([4e493d4](https://www.github.com/nodejs/node-gyp/commit/4e493d4fb262d12ac52c84979071ccc79e666a1a))
* run tests after release please PR ([3032e10](https://www.github.com/nodejs/node-gyp/commit/3032e1061cc2b7b49f83c397d385bafddc6b0214))

## [9.4.0](https://www.github.com/nodejs/node-gyp/compare/v9.3.1...v9.4.0) (2023-06-12)


### Features

* add support for native windows arm64 build tools ([bb76021](https://www.github.com/nodejs/node-gyp/commit/bb76021d35964d2bb125bc6214286f35ae4e6cad))
* Upgrade Python linting from flake8 to ruff ([#2815](https://www.github.com/nodejs/node-gyp/issues/2815)) ([fc0ddc6](https://www.github.com/nodejs/node-gyp/commit/fc0ddc6523c62b10e5ca1257500b3ceac01450a7))


### Bug Fixes

* extract tarball to temp directory on Windows ([#2846](https://www.github.com/nodejs/node-gyp/issues/2846)) ([aaa117c](https://www.github.com/nodejs/node-gyp/commit/aaa117c514430aa2c1e568b95df1b6ed1c1fd3b6))
* log statement is for devDir not nodedir ([#2840](https://www.github.com/nodejs/node-gyp/issues/2840)) ([55048f8](https://www.github.com/nodejs/node-gyp/commit/55048f8be5707c295fb0876306aded75638a8b63))


### Miscellaneous

* get update-gyp.py to work with Python >= v3.5 ([#2826](https://www.github.com/nodejs/node-gyp/issues/2826)) ([337e8e6](https://www.github.com/nodejs/node-gyp/commit/337e8e68209bd2481cbb11dacce61234dc5c9419))


### Doc

* docs/README.md add advise about deprecated node-sass ([#2828](https://www.github.com/nodejs/node-gyp/issues/2828)) ([6f3c2d3](https://www.github.com/nodejs/node-gyp/commit/6f3c2d3c6c0de0dbf8c7245f34c2e0b3eea53812))
* Update README.md ([#2822](https://www.github.com/nodejs/node-gyp/issues/2822)) ([c7927e2](https://www.github.com/nodejs/node-gyp/commit/c7927e228dfde059c93e08c26b54dd8026144583))


### Tests

* remove deprecated Node.js and Python ([#2868](https://www.github.com/nodejs/node-gyp/issues/2868)) ([a0b3d1c](https://www.github.com/nodejs/node-gyp/commit/a0b3d1c3afed71a74501476fcbc6ee3fface4d13))

### [9.3.1](https://www.github.com/nodejs/node-gyp/compare/v9.3.0...v9.3.1) (2022-12-16)


### Bug Fixes

* increase node 12 support to ^12.13 ([#2771](https://www.github.com/nodejs/node-gyp/issues/2771)) ([888efb9](https://www.github.com/nodejs/node-gyp/commit/888efb9055857afee6a6b54550722cf9ae3ee323))


### Miscellaneous

* update python test matrix ([#2774](https://www.github.com/nodejs/node-gyp/issues/2774)) ([38f01fa](https://www.github.com/nodejs/node-gyp/commit/38f01fa57d10fdb3db7697121d957bc2e0e96508))

## [9.3.0](https://www.github.com/nodejs/node-gyp/compare/v9.2.0...v9.3.0) (2022-10-10)


### Features

* **gyp:** update gyp to v0.14.0 ([#2749](https://www.github.com/nodejs/node-gyp/issues/2749)) ([713b8dc](https://www.github.com/nodejs/node-gyp/commit/713b8dcdbf44532ca9453a127da266386cc737f8))
* remove support for VS2015 in Node.js >=19 ([#2746](https://www.github.com/nodejs/node-gyp/issues/2746)) ([131d1a4](https://www.github.com/nodejs/node-gyp/commit/131d1a463baf034a04154bcda753a8295f112a34))
* support IBM Open XL C/C++ on z/OS ([#2743](https://www.github.com/nodejs/node-gyp/issues/2743)) ([7d0c83d](https://www.github.com/nodejs/node-gyp/commit/7d0c83d2a95aca743dff972826d0da26203acfc4))

## [9.2.0](https://www.github.com/nodejs/node-gyp/compare/v9.1.0...v9.2.0) (2022-10-02)


### Features

* Add proper support for IBM i ([a26494f](https://www.github.com/nodejs/node-gyp/commit/a26494fbb8883d9ef784503979e115dec3e2791e))
* **gyp:** update gyp to v0.13.0 ([3e2a532](https://www.github.com/nodejs/node-gyp/commit/3e2a5324f1c24f3a04bca04cf54fe23d5c4d5e50))


### Bug Fixes

* node.js debugger adds stderr (but exit code is 0) -> shouldn't throw ([#2719](https://www.github.com/nodejs/node-gyp/issues/2719)) ([c379a74](https://www.github.com/nodejs/node-gyp/commit/c379a744c65c7ab07c2c3193d9c7e8f25ae1b05e))


### Core

* enable support for zoslib on z/OS ([#2600](https://www.github.com/nodejs/node-gyp/issues/2600)) ([83c0a12](https://www.github.com/nodejs/node-gyp/commit/83c0a12bf23b4cbf3125d41f9e2d4201db76c9ae))


### Miscellaneous

* update dependency - nopt@6.0.0 ([#2707](https://www.github.com/nodejs/node-gyp/issues/2707)) ([8958ecf](https://www.github.com/nodejs/node-gyp/commit/8958ecf2bb719227bbcbf155891c3186ee219a2e))

## [9.1.0](https://www.github.com/nodejs/node-gyp/compare/v9.0.0...v9.1.0) (2022-07-13)


### Features

* Update function getSDK() to support Windows 11 SDK ([#2565](https://www.github.com/nodejs/node-gyp/issues/2565)) ([ea8520e](https://www.github.com/nodejs/node-gyp/commit/ea8520e3855374bd15b6d001fe112d58a8d7d737))


### Bug Fixes

* extend tap timeout length to allow for slow CI ([6f74c76](https://www.github.com/nodejs/node-gyp/commit/6f74c762fe3c19bdd20245cb5c02e2dfa65d9451))
* new ca & server certs, bundle in .js file and unpack for testing ([147e3d3](https://www.github.com/nodejs/node-gyp/commit/147e3d34f44a97deb7aa507207680cf0f4e662a2))
* re-label ([#2689](https://www.github.com/nodejs/node-gyp/issues/2689)) ([f0b7863](https://www.github.com/nodejs/node-gyp/commit/f0b7863dadfa365afc173025ae95351aec79abd9))
* typo on readme ([bf81cd4](https://www.github.com/nodejs/node-gyp/commit/bf81cd452b931dd4dfa82762c23dd530a075d992))


### Doc

* update docs/README.md with latest version number ([62d2815](https://www.github.com/nodejs/node-gyp/commit/62d28151bf8266a34e1bcceeb25b4e6e2ae5ca5d))


### Core

* update due to rename of primary branch ([ca1f068](https://www.github.com/nodejs/node-gyp/commit/ca1f0681a5567ca8cd51acebccd37a633f19bc6a))
* Add Python symlink to path (for non-Windows OSes only) ([#2362](https://github.com/nodejs/node-gyp/pull/2362)) ([b9ddcd5](https://github.com/nodejs/node-gyp/commit/b9ddcd5bbd93b05b03674836b6ebdae2c2e74c8c))


### Tests

* Try msvs-version: [2016, 2019, 2022] ([#2700](https://www.github.com/nodejs/node-gyp/issues/2700)) ([68b5b5b](https://www.github.com/nodejs/node-gyp/commit/68b5b5be9c94ac20c55e88654ff6f55234d7130a))
* Upgrade GitHub Actions ([#2623](https://www.github.com/nodejs/node-gyp/issues/2623)) ([245cd5b](https://www.github.com/nodejs/node-gyp/commit/245cd5bbe4441d4f05e88f2fa20a86425419b6af))
* Upgrade GitHub Actions ([#2701](https://www.github.com/nodejs/node-gyp/issues/2701)) ([1c64ca7](https://www.github.com/nodejs/node-gyp/commit/1c64ca7f4702c6eb43ecd16fbd67b5d939041621))

## [9.0.0](https://www.github.com/nodejs/node-gyp/compare/v8.4.1...v9.0.0) (2022-02-24)


### ⚠ BREAKING CHANGES

* increase "engines" to "node" : "^12.22 || ^14.13 || >=16" (#2601)

### Bug Fixes

* _ in npm_config_ env variables ([eef4eef](https://www.github.com/nodejs/node-gyp/commit/eef4eefccb13ff6a32db862709ee5b2d4edf7e95))
* update make-fetch-happen to a minimum of 10.0.3 ([839e414](https://www.github.com/nodejs/node-gyp/commit/839e414b63790c815a4a370d0feee8f24a94d40f))


### Miscellaneous

* add minimal SECURITY.md ([#2560](https://www.github.com/nodejs/node-gyp/issues/2560)) ([c2a1850](https://www.github.com/nodejs/node-gyp/commit/c2a185056e2e589b520fbc0bcc59c2935cd07ede))


### Doc

* Add notes/disclaimers for upgrading the copy of node-gyp that npm uses ([#2585](https://www.github.com/nodejs/node-gyp/issues/2585)) ([faf6d48](https://www.github.com/nodejs/node-gyp/commit/faf6d48f8a77c08a313baf9332358c4b1231c73c))
* Rename and update Common-issues.md --> docs/README.md ([#2567](https://www.github.com/nodejs/node-gyp/issues/2567)) ([2ef5fb8](https://www.github.com/nodejs/node-gyp/commit/2ef5fb86277c4d81baffc0b9f642a8d86be1bfa5))
* rephrase explanation of which node-gyp is used by npm ([#2587](https://www.github.com/nodejs/node-gyp/issues/2587)) ([a2f2988](https://www.github.com/nodejs/node-gyp/commit/a2f298870692022302fa27a1d42363c4a72df407))
* title match content ([#2574](https://www.github.com/nodejs/node-gyp/issues/2574)) ([6e8f93b](https://www.github.com/nodejs/node-gyp/commit/6e8f93be0443f2649d4effa7bc773a9da06a33b4))
* Update Python versions ([#2571](https://www.github.com/nodejs/node-gyp/issues/2571)) ([e069f13](https://www.github.com/nodejs/node-gyp/commit/e069f13658a8bfb5fd60f74708cf8be0856d92e3))


### Core

* add lib.target as path for searching libnode on z/OS ([1d499dd](https://www.github.com/nodejs/node-gyp/commit/1d499dd5606f39de2d34fa822fd0fa5ce17fbd06))
* increase "engines" to "node" : "^12.22 || ^14.13 || >=16" ([#2601](https://www.github.com/nodejs/node-gyp/issues/2601)) ([6562f92](https://www.github.com/nodejs/node-gyp/commit/6562f92a6f2e67aeae081ddf5272ff117f1fab07))
* make-fetch-happen@10.0.1 ([78f6660](https://www.github.com/nodejs/node-gyp/commit/78f66604e0df480d4f36a8fa4f3618c046a6fbdc))

### [8.4.1](https://www.github.com/nodejs/node-gyp/compare/v8.4.0...v8.4.1) (2021-11-19)


### Bug Fixes

* windows command missing space ([#2553](https://www.github.com/nodejs/node-gyp/issues/2553)) ([cc37b88](https://www.github.com/nodejs/node-gyp/commit/cc37b880690706d3c5d04d5a68c76c392a0a23ed))


### Doc

* fix typo in powershell node-gyp update ([787cf7f](https://www.github.com/nodejs/node-gyp/commit/787cf7f8e5ddd5039e02b64ace6b7b15e06fe0a4))


### Core

* npmlog@6.0.0 ([8083f6b](https://www.github.com/nodejs/node-gyp/commit/8083f6b855bd7f3326af04c5f5269fc28d7f2508))

## [8.4.0](https://www.github.com/nodejs/node-gyp/compare/v8.3.0...v8.4.0) (2021-11-05)


### Features

* build with config.gypi from node headers ([a27dc08](https://www.github.com/nodejs/node-gyp/commit/a27dc08696911c6d81e76cc228697243069103c1))
* support vs2022 ([#2533](https://www.github.com/nodejs/node-gyp/issues/2533)) ([5a00387](https://www.github.com/nodejs/node-gyp/commit/5a00387e5f8018264a1822f6c4d5dbf425f21cf6))

## [8.3.0](https://www.github.com/nodejs/node-gyp/compare/v8.2.0...v8.3.0) (2021-10-11)


### Features

* **gyp:** update gyp to v0.10.0 ([#2521](https://www.github.com/nodejs/node-gyp/issues/2521)) ([5585792](https://www.github.com/nodejs/node-gyp/commit/5585792922a97f0629f143c560efd74470eae87f))


### Tests

* Python 3.10 was release on Oct. 4th ([#2504](https://www.github.com/nodejs/node-gyp/issues/2504)) ([0a67dcd](https://www.github.com/nodejs/node-gyp/commit/0a67dcd1307f3560495219253241eafcbf4e2a69))


### Miscellaneous

* **deps:** bump make-fetch-happen from 8.0.14 to 9.1.0 ([b05b4fe](https://www.github.com/nodejs/node-gyp/commit/b05b4fe9891f718f40edf547e9b50e982826d48a))
* refactor the creation of config.gypi file ([f2ad87f](https://www.github.com/nodejs/node-gyp/commit/f2ad87ff65f98ad66daa7225ad59d99b759a2b07))

## [8.2.0](https://www.github.com/nodejs/node-gyp/compare/v8.1.0...v8.2.0) (2021-08-23)


### Features

* **gyp:** update gyp to v0.9.6 ([#2481](https://www.github.com/nodejs/node-gyp/issues/2481)) ([ed9a9ed](https://www.github.com/nodejs/node-gyp/commit/ed9a9ed653a17c84afa3c327161992d0da7d0cea))


### Bug Fixes

* add error arg back into catch block for older Node.js users ([5cde818](https://www.github.com/nodejs/node-gyp/commit/5cde818aac715477e9e9747966bb6b4c4ed070a8))
* change default gyp update message ([#2420](https://www.github.com/nodejs/node-gyp/issues/2420)) ([cfd12ff](https://www.github.com/nodejs/node-gyp/commit/cfd12ff3bb0eb4525173413ef6a94b3cd8398cad))
* doc how to update node-gyp independently from npm ([c8c0af7](https://www.github.com/nodejs/node-gyp/commit/c8c0af72e78141a02b5da4cd4d704838333a90bd))
* missing spaces ([f0882b1](https://www.github.com/nodejs/node-gyp/commit/f0882b1264b2fa701adbc81a3be0b3cba80e333d))


### Core

* deep-copy process.config during configure ([#2368](https://www.github.com/nodejs/node-gyp/issues/2368)) ([5f1a06c](https://www.github.com/nodejs/node-gyp/commit/5f1a06c50f3b0c3d292f64948f85a004cfcc5c87))


### Miscellaneous

* **deps:** bump tar from 6.1.0 to 6.1.2 ([#2474](https://www.github.com/nodejs/node-gyp/issues/2474)) ([ec15a3e](https://www.github.com/nodejs/node-gyp/commit/ec15a3e5012004172713c11eebcc9d852d32d380))
* fix typos discovered by codespell ([#2442](https://www.github.com/nodejs/node-gyp/issues/2442)) ([2d0ce55](https://www.github.com/nodejs/node-gyp/commit/2d0ce5595e232a3fc7c562cdf39efb77e2312cc1))
* GitHub Actions Test on node: [12.x, 14.x, 16.x] ([#2439](https://www.github.com/nodejs/node-gyp/issues/2439)) ([b7bccdb](https://www.github.com/nodejs/node-gyp/commit/b7bccdb527d93b0bb0ce99713f083ce2985fe85c))


### Doc

* correct link to "binding.gyp files out in the wild" ([#2483](https://www.github.com/nodejs/node-gyp/issues/2483)) ([660dd7b](https://www.github.com/nodejs/node-gyp/commit/660dd7b2a822c184be8027b300e68be67b366772))
* **wiki:** Add a link to the node-midi binding.gyp file. ([b354711](https://www.github.com/nodejs/node-gyp/commit/b3547115f6e356358138310e857c7f1ec627a8a7))
* **wiki:** add bcrypt ([e199cfa](https://www.github.com/nodejs/node-gyp/commit/e199cfa8fc6161492d2a6ade2190510d0ebf7c0f))
* **wiki:** Add helpful information ([4eda827](https://www.github.com/nodejs/node-gyp/commit/4eda8275c03dae6d2f5c40f3c1dbe930d84b0f2b))
* **wiki:** Add node-canvas ([13a9553](https://www.github.com/nodejs/node-gyp/commit/13a955317b39caf98fd1f412d8d3f41599e979fd))
* **wiki:** Add node-openvg-canvas and node-openvg. ([61f709e](https://www.github.com/nodejs/node-gyp/commit/61f709ec4d9f256a6467e9ff84430a48eeb629d1))
* **wiki:** add one more example ([77f3632](https://www.github.com/nodejs/node-gyp/commit/77f363272930d3d4d24fd3973be22e6237128fcc))
* **wiki:** add topcube, node-osmium, and node-osrm ([1a75d2b](https://www.github.com/nodejs/node-gyp/commit/1a75d2bf2f562ba50846893a516e111cfbb50885))
* **wiki:** Added details for properly fixing ([3d4d9d5](https://www.github.com/nodejs/node-gyp/commit/3d4d9d52d6b5b49de06bb0bb5b68e2686d2b7ebd))
* **wiki:** Added Ghostscript4JS ([bf4bed1](https://www.github.com/nodejs/node-gyp/commit/bf4bed1b96a7d22fba6f97f4552ad09f32ac3737))
* **wiki:** added levelup ([1575bce](https://www.github.com/nodejs/node-gyp/commit/1575bce3a53db628bfb023fd6f3258fdf98c3195))
* **wiki:** Added nk-mysql (nodamysql) ([5b4f2d0](https://www.github.com/nodejs/node-gyp/commit/5b4f2d0e1d5d3eadfd03aaf9c1668340f76c4bea))
* **wiki:** Added nk-xrm-installer .gyp references, including .py scripts for providing complete reference to examples of fetching source via http, extracting, and moving files (as opposed to copying) ([ceb3088](https://www.github.com/nodejs/node-gyp/commit/ceb30885b74f6789374ef52267b84767be93ebe4))
* **wiki:** Added tip about resolving frustrating LNK1181 error ([e64798d](https://www.github.com/nodejs/node-gyp/commit/e64798de8cac6031ad598a86d7599e81b4d20b17))
* **wiki:** ADDED: Node.js binding to OpenCV ([e2dc777](https://www.github.com/nodejs/node-gyp/commit/e2dc77730b09d7ee8682d7713a7603a2d7aacabd))
* **wiki:** Adding link to node-cryptopp's gyp file ([875adbe](https://www.github.com/nodejs/node-gyp/commit/875adbe2a4669fa5f2be0250ffbf98fb55e800fd))
* **wiki:** Adding the sharp library to the list ([9dce0e4](https://www.github.com/nodejs/node-gyp/commit/9dce0e41650c3fa973e6135a79632d022c662a1d))
* **wiki:** Adds node-fann ([23e3d48](https://www.github.com/nodejs/node-gyp/commit/23e3d485ed894ba7c631e9c062f5e366b50c416c))
* **wiki:** Adds node-inotify and v8-profiler ([b6e542f](https://www.github.com/nodejs/node-gyp/commit/b6e542f644dbbfe22b88524ec500696e06ee4af7))
* **wiki:** Bumping Python version from 2.3 to 2.7 as per the node-gyp readme ([55ebd6e](https://www.github.com/nodejs/node-gyp/commit/55ebd6ebacde975bf84f7bf4d8c66e64cc7cd0da))
* **wiki:** C++ build tools version upgraded ([5b899b7](https://www.github.com/nodejs/node-gyp/commit/5b899b70db729c392ced7c98e8e17590c6499fc3))
* **wiki:** change bcrypt url to binding.gyp file ([e11bdd8](https://www.github.com/nodejs/node-gyp/commit/e11bdd84de6144492d3eb327d67cbf2d62da1a76))
* **wiki:** Clarification + direct link to VS2010 ([531c724](https://www.github.com/nodejs/node-gyp/commit/531c724561d947b5d870de8d52dd8c3c51c5ec2d))
* **wiki:** Correcting the link to node-osmium ([fae7516](https://www.github.com/nodejs/node-gyp/commit/fae7516a1d2829b6e234eaded74fb112ebd79a05))
* **wiki:** Created "binding.gyp" files out in the wild (markdown) ([d4fd143](https://www.github.com/nodejs/node-gyp/commit/d4fd14355bbe57f229f082f47bb2b3670868203f))
* **wiki:** Created Common issues (markdown) ([a38299e](https://www.github.com/nodejs/node-gyp/commit/a38299ea340ceb0e732c6dc6a1b4760257644839))
* **wiki:** Created Error: "pre" versions of node cannot be installed (markdown) ([98bc80d](https://www.github.com/nodejs/node-gyp/commit/98bc80d7a62ba70c881f3c39d94f804322e57852))
* **wiki:** Created Linking to OpenSSL (markdown) ([c46d00d](https://www.github.com/nodejs/node-gyp/commit/c46d00d83bac5173dea8bbbb175a1a7de74fdaca))
* **wiki:** Created Updating npm's bundled node gyp (markdown) ([e0ac8d1](https://www.github.com/nodejs/node-gyp/commit/e0ac8d15af46aadd1c220599e63199b154a514e6))
* **wiki:** Created use of undeclared identifier 'TypedArray' (markdown) ([65ba711](https://www.github.com/nodejs/node-gyp/commit/65ba71139e9b7f64ac823e575ee9dbf17d937ce4))
* **wiki:** Created Visual Studio 2010 Setup (markdown) ([5b80e83](https://www.github.com/nodejs/node-gyp/commit/5b80e834c8f79dda9fb2770a876ff3cf649c06f3))
* **wiki:** Created Visual studio 2012 setup (markdown) ([becef31](https://www.github.com/nodejs/node-gyp/commit/becef316b6c46a33e783667720ee074a0141d1a5))
* **wiki:** Destroyed Visual Studio 2010 Setup (markdown) ([93423b4](https://www.github.com/nodejs/node-gyp/commit/93423b43606de9664aeb79635825f5e9941ec9bc))
* **wiki:** Destroyed Visual studio 2012 setup (markdown) ([3601508](https://www.github.com/nodejs/node-gyp/commit/3601508bb10fa05da0ddc7e70d57e4b4dd679657))
* **wiki:** Different commands for Windows npm v6 vs. v7 ([0fce46b](https://www.github.com/nodejs/node-gyp/commit/0fce46b53340c85e8091cde347d5ed23a443c82f))
* **wiki:** Drop  in favor of ([9285ff6](https://www.github.com/nodejs/node-gyp/commit/9285ff6e451c52c070a05f05f0a9602621d91d53))
* **wiki:** Explicit link to Visual C++ 2010 Express ([378c363](https://www.github.com/nodejs/node-gyp/commit/378c3632f02c096ed819ec8f2611c65bef0c0554))
* **wiki:** fix link to gyp file used to build libsqlite3 ([54db8d7](https://www.github.com/nodejs/node-gyp/commit/54db8d7ac33e3f98220960b5d86cfa18a75b53cb))
* **wiki:** Fix link to node-zipfile ([92e49a8](https://www.github.com/nodejs/node-gyp/commit/92e49a858ed69cb4847a26a5676ab56ef5e2de33))
* **wiki:** fixed node-serialport link ([954ee53](https://www.github.com/nodejs/node-gyp/commit/954ee530b3972d1db591fce32368e4e31b5a25d8))
* **wiki:** I highly missing it in common issue as every windows biggner face that issue ([d617fae](https://www.github.com/nodejs/node-gyp/commit/d617faee29c40871ca5c8f93efd0ce929a40d541))
* **wiki:** if ouns that the -h did not help. I founs on github that there was support for visual studio 2015, while i couldn't install node-red beacuse it kept telling me the key 2015 was missing. looking in he gyp python code i found the local file was bot up t dat with the github repo. updating took several efforts before i tried to drop the -g option. ([408b72f](https://www.github.com/nodejs/node-gyp/commit/408b72f561329408daeb17834436e381406efcc8))
* **wiki:** If permissions error, please try  and then the command. ([ee8e1c1](https://www.github.com/nodejs/node-gyp/commit/ee8e1c1e5334096d58e0d6bca6c006f2ee9c88cb))
* **wiki:** Improve Unix instructions ([c3e5487](https://www.github.com/nodejs/node-gyp/commit/c3e548736645b535ea5bce613d74ca3e98598243))
* **wiki:** link to docs/ from README ([b52e487](https://www.github.com/nodejs/node-gyp/commit/b52e487eac1eb421573d1e67114a242eeff45a00))
* **wiki:** Lower case L ([3aa2c6b](https://www.github.com/nodejs/node-gyp/commit/3aa2c6bdb07971b87505e32e32548d75264bd19f))
* **wiki:** Make changes discussed in https://github.com/nodejs/node-gyp/issues/2416 ([1dcad87](https://www.github.com/nodejs/node-gyp/commit/1dcad873539027511a5f0243baf770ea90f6f4e2))
* **wiki:** move wiki docs into doc/ ([f0a4835](https://www.github.com/nodejs/node-gyp/commit/f0a48355d86534ec3bdabcdb3ce3340fa2e17f39))
* **wiki:** node-sass in the wild ([d310a73](https://www.github.com/nodejs/node-gyp/commit/d310a73d64d0065050377baac7047472f7424a1b))
* **wiki:** node-srs was a 404 ([bbca21a](https://www.github.com/nodejs/node-gyp/commit/bbca21a1e1ede4c473aff365ca71989a5bda7b57))
* **wiki:** Note: VS2010 seems to be no longer available!  VS2013 or nothing! ([7b5dcaf](https://www.github.com/nodejs/node-gyp/commit/7b5dcafafccdceae4b8f2b53ac9081a694b6ade8))
* **wiki:** safer doc names, remove unnecessary TypedArray doc ([161c235](https://www.github.com/nodejs/node-gyp/commit/161c2353ef5b562f4acfb2fd77608fcbd0800fc0))
* **wiki:** sorry, forgot to mention a specific windows version. ([d69dffc](https://www.github.com/nodejs/node-gyp/commit/d69dffc16c2b1e3c60dcb5d1c35a49270ba22a35))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([7444b47](https://www.github.com/nodejs/node-gyp/commit/7444b47a7caac1e14d1da474a7fcfcf88d328017))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([d766b74](https://www.github.com/nodejs/node-gyp/commit/d766b7427851e6c2edc02e2504a7be9be7e330c0))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([d319b0e](https://www.github.com/nodejs/node-gyp/commit/d319b0e98c7085de8e51bc5595eba4264b99a7d5))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([3c6692d](https://www.github.com/nodejs/node-gyp/commit/3c6692d538f0ce973869aa237118b7d2483feccd))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([93392d5](https://www.github.com/nodejs/node-gyp/commit/93392d559ce6f250b9c7fe8177e6c88603809dc1))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([8841158](https://www.github.com/nodejs/node-gyp/commit/88411588f300e9b7c00fe516ecd977a1feeeb15c))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([81bfa1f](https://www.github.com/nodejs/node-gyp/commit/81bfa1f1b63d522a9f8a9ae9ca0c7ae90fe75140))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([d1cd237](https://www.github.com/nodejs/node-gyp/commit/d1cd237bad06fa507adb354b9e2181a14dc63d24))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([3de9e17](https://www.github.com/nodejs/node-gyp/commit/3de9e17e0b8a387eafe7bd18d0ec1e3191d118e8))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([a9b7096](https://www.github.com/nodejs/node-gyp/commit/a9b70968fb956eab3b95672048b94350e1565ca3))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([3236069](https://www.github.com/nodejs/node-gyp/commit/3236069689e7e0eb15b324fce74ab58158956f98))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([1462755](https://www.github.com/nodejs/node-gyp/commit/14627556966e5d513bdb8e5208f0e1300f68991f))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([7ab1337](https://www.github.com/nodejs/node-gyp/commit/7ab133752a6c402bb96dcd3d671d73e03e9487ad))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([640895d](https://www.github.com/nodejs/node-gyp/commit/640895d36b7448c646a3b850c1e159106f83c724))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([ced8c96](https://www.github.com/nodejs/node-gyp/commit/ced8c968457f285ab8989c291d28173d7730833c))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([27b883a](https://www.github.com/nodejs/node-gyp/commit/27b883a350ad0db6b9130d7b996f35855ec34c7a))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([d29fb13](https://www.github.com/nodejs/node-gyp/commit/d29fb134f1c4b9dd729ba95f2979e69e0934809f))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([2765891](https://www.github.com/nodejs/node-gyp/commit/27658913e6220cf0371b4b73e25a0e4ab11108a1))
* **wiki:** Updated "binding.gyp" files out in the wild (markdown) ([dc97766](https://www.github.com/nodejs/node-gyp/commit/dc9776648d432bca6775c176641f16da14522d4c))
* **wiki:** Updated Error: "pre" versions of node cannot be installed (markdown) ([e9f8b33](https://www.github.com/nodejs/node-gyp/commit/e9f8b33d1f87d04f22cb09a814d7c55d0fa38446))
* **wiki:** Updated Home (markdown) ([3407109](https://www.github.com/nodejs/node-gyp/commit/3407109325cf7ba1e925656b9eb75feffab0557c))
* **wiki:** Updated Home (markdown) ([6e392bc](https://www.github.com/nodejs/node-gyp/commit/6e392bcdd3dd1691773e6e16e1dffc35931b81e0))
* **wiki:** Updated Home (markdown) ([65efe32](https://www.github.com/nodejs/node-gyp/commit/65efe32ccb8d446ce569453364f922dd9d27c945))
* **wiki:** Updated Home (markdown) ([ea28f09](https://www.github.com/nodejs/node-gyp/commit/ea28f0947af91fa638be355143f5df89d2e431c8))
* **wiki:** Updated Home (markdown) ([0e37ff4](https://www.github.com/nodejs/node-gyp/commit/0e37ff48b306c12149661b375895741d3d710da7))
* **wiki:** Updated Home (markdown) ([b398ef4](https://www.github.com/nodejs/node-gyp/commit/b398ef46f660d2b1506508550dadfb4c35639e4b))
* **wiki:** Updated Linking to OpenSSL (markdown) ([8919028](https://www.github.com/nodejs/node-gyp/commit/8919028921fd304f08044098434f0dc6071fb7cf))
* **wiki:** Updated Linking to OpenSSL (markdown) ([c00eb77](https://www.github.com/nodejs/node-gyp/commit/c00eb778fc7dc27e4dab3a9219035ea20458b33b))
* **wiki:** Updated node-levelup to node-leveldown (broken links) ([59668bb](https://www.github.com/nodejs/node-gyp/commit/59668bb0b904feccf3c09afa2fd37378c77af967))
* **wiki:** Updated Updating npm's bundled node gyp (markdown) ([d314854](https://www.github.com/nodejs/node-gyp/commit/d31485415ef69d46effa6090c95698341965de1b))
* **wiki:** Updated Updating npm's bundled node gyp (markdown) ([11858b0](https://www.github.com/nodejs/node-gyp/commit/11858b0655d1eee00c62ad628e719d4378803d14))
* **wiki:** Updated Updating npm's bundled node gyp (markdown) ([33561e9](https://www.github.com/nodejs/node-gyp/commit/33561e9cbf5f4eb46111318503c77df2c6eb484a))
* **wiki:** Updated Updating npm's bundled node gyp (markdown) ([4a7f2d0](https://www.github.com/nodejs/node-gyp/commit/4a7f2d0d869a65c99a78504976567017edadf657))
* **wiki:** Updated Updating npm's bundled node gyp (markdown) ([979a706](https://www.github.com/nodejs/node-gyp/commit/979a7063b950c088a7f4896fc3a48e1d00dfd231))
* **wiki:** Updated Updating npm's bundled node gyp (markdown) ([e50e04d](https://www.github.com/nodejs/node-gyp/commit/e50e04d7b6a3754ea0aa11fe8cef491b3bc5bdd4))

## [8.1.0](https://www.github.com/nodejs/node-gyp/compare/v8.0.0...v8.1.0) (2021-05-28)


### Features

* **gyp:** update gyp to v0.9.1 ([#2402](https://www.github.com/nodejs/node-gyp/issues/2402)) ([814b1b0](https://www.github.com/nodejs/node-gyp/commit/814b1b0eda102afb9fc87e81638a9cf5b650bb10))


### Miscellaneous

* add `release-please-action` for automated releases ([#2395](https://www.github.com/nodejs/node-gyp/issues/2395)) ([07e9d7c](https://www.github.com/nodejs/node-gyp/commit/07e9d7c7ee80ba119ea760c635f72fd8e7efe198))


### Core

* fail gracefully if we can't find the username ([#2375](https://www.github.com/nodejs/node-gyp/issues/2375)) ([fca4795](https://www.github.com/nodejs/node-gyp/commit/fca4795512c67dc8420aaa0d913b5b89a4b147f3))
* log as yes/no whether build dir was created ([#2370](https://www.github.com/nodejs/node-gyp/issues/2370)) ([245dee5](https://www.github.com/nodejs/node-gyp/commit/245dee5b62581309946872ae253226ea3a42c0e3))


### Doc

* fix v8.0.0 release date ([4b83c3d](https://www.github.com/nodejs/node-gyp/commit/4b83c3de7300457919d53f26d96ea9ad6f6bedd8))
* remove redundant version info ([#2403](https://www.github.com/nodejs/node-gyp/issues/2403)) ([1423670](https://www.github.com/nodejs/node-gyp/commit/14236709de64b100a424396b91a5115639daa0ef))
* Update README.md Visual Studio Community page polski to auto ([#2371](https://www.github.com/nodejs/node-gyp/issues/2371)) ([1b4697a](https://www.github.com/nodejs/node-gyp/commit/1b4697abf69ef574a48faf832a7098f4c6c224a5))

## v8.0.0 2021-04-03

* [[`0d8a6f1b19`](https://github.com/nodejs/node-gyp/commit/0d8a6f1b19)] - **ci**: update actions/setup-node to v2 (#2302) (Sora Morimoto) [#2302](https://github.com/nodejs/node-gyp/pull/2302)
* [[`15a5c7d45b`](https://github.com/nodejs/node-gyp/commit/15a5c7d45b)] - **ci**: migrate deprecated grammar (#2285) (Jiawen Geng) [#2285](https://github.com/nodejs/node-gyp/pull/2285)
* [[`06ddde27f9`](https://github.com/nodejs/node-gyp/commit/06ddde27f9)] - **deps**: sync mutual dependencies with npm (DeeDeeG) [#2348](https://github.com/nodejs/node-gyp/pull/2348)
* [[`a5fd1f41e3`](https://github.com/nodejs/node-gyp/commit/a5fd1f41e3)] - **doc**: add downloads badge (#2352) (Jiawen Geng) [#2352](https://github.com/nodejs/node-gyp/pull/2352)
* [[`cc1cbce056`](https://github.com/nodejs/node-gyp/commit/cc1cbce056)] - **doc**: update macOS\_Catalina.md (#2293) (iMrLopez) [#2293](https://github.com/nodejs/node-gyp/pull/2293)
* [[`6287118fc4`](https://github.com/nodejs/node-gyp/commit/6287118fc4)] - **doc**: updated README.md to copy easily (#2281) (மனோஜ்குமார் பழனிச்சாமி) [#2281](https://github.com/nodejs/node-gyp/pull/2281)
* [[`66c0f04467`](https://github.com/nodejs/node-gyp/commit/66c0f04467)] - **doc**: add missing `sudo` to Catalina doc (Karl Horky) [#2244](https://github.com/nodejs/node-gyp/pull/2244)
* [[`0da2e0140d`](https://github.com/nodejs/node-gyp/commit/0da2e0140d)] - **gyp**: update gyp to v0.8.1 (#2355) (DeeDeeG) [#2355](https://github.com/nodejs/node-gyp/pull/2355)
* [[`0093ec8646`](https://github.com/nodejs/node-gyp/commit/0093ec8646)] - **gyp**: Improve our flake8 linting tests (Christian Clauss) [#2356](https://github.com/nodejs/node-gyp/pull/2356)
* [[`a78b584236`](https://github.com/nodejs/node-gyp/commit/a78b584236)] - **(SEMVER-MAJOR)** **gyp**: remove support for Python 2 (#2300) (Christian Clauss) [#2300](https://github.com/nodejs/node-gyp/pull/2300)
* [[`c3c510d89e`](https://github.com/nodejs/node-gyp/commit/c3c510d89e)] - **gyp**: update gyp to v0.8.0 (#2318) (Christian Clauss) [#2318](https://github.com/nodejs/node-gyp/pull/2318)
* [[`9e1397c52e`](https://github.com/nodejs/node-gyp/commit/9e1397c52e)] - **(SEMVER-MAJOR)** **gyp**: update gyp to v0.7.0 (#2284) (Jiawen Geng) [#2284](https://github.com/nodejs/node-gyp/pull/2284)
* [[`1bd18f3e77`](https://github.com/nodejs/node-gyp/commit/1bd18f3e77)] - **(SEMVER-MAJOR)** **lib**: drop Python 2 support in find-python.js (#2333) (DeeDeeG) [#2333](https://github.com/nodejs/node-gyp/pull/2333)
* [[`e81602ef55`](https://github.com/nodejs/node-gyp/commit/e81602ef55)] - **(SEMVER-MAJOR)** **lib**: migrate requests to fetch (#2220) (Matias Lopez) [#2220](https://github.com/nodejs/node-gyp/pull/2220)
* [[`392b7760b4`](https://github.com/nodejs/node-gyp/commit/392b7760b4)] - **lib**: avoid changing process.config (#2322) (Michaël Zasso) [#2322](https://github.com/nodejs/node-gyp/pull/2322)

## v7.1.2 2020-10-17

* [[`096e3aded5`](https://github.com/nodejs/node-gyp/commit/096e3aded5)] - **gyp**: update gyp to 0.6.2 (Myles Borins) [#2241](https://github.com/nodejs/node-gyp/pull/2241)
* [[`54f97cd243`](https://github.com/nodejs/node-gyp/commit/54f97cd243)] - **doc**: add cmd to reset `xcode-select` to initial state (Valera Rozuvan) [#2235](https://github.com/nodejs/node-gyp/pull/2235)

## v7.1.1 2020-10-15

This release restores the location of shared library builds to the pre-v7
location. In v7.0.0 until this release, shared library outputs were placed
in a lib.target subdirectory inside the build/{Release,Debug} directory for
builds using `make` (Linux, etc.). This is inconsistent with macOS (Xcode)
behavior and previous node-gyp behavior so has been reverted.
We consider this a bug-fix rather than semver-major change.

* [[`18bf2d1d38`](https://github.com/nodejs/node-gyp/commit/18bf2d1d38)] - **deps**: update deps to match npm@7 (Rod Vagg) [#2240](https://github.com/nodejs/node-gyp/pull/2240)
* [[`ee6a837cb7`](https://github.com/nodejs/node-gyp/commit/ee6a837cb7)] - **gyp**: update gyp to 0.6.1 (Rod Vagg) [#2238](https://github.com/nodejs/node-gyp/pull/2238)
* [[`3e7f8ccafc`](https://github.com/nodejs/node-gyp/commit/3e7f8ccafc)] - **lib**: better log message when ps fails (Martin Midtgaard) [#2229](https://github.com/nodejs/node-gyp/pull/2229)
* [[`7fb314339f`](https://github.com/nodejs/node-gyp/commit/7fb314339f)] - **test**: GitHub Actions: Test on Python 3.9 (Christian Clauss) [#2230](https://github.com/nodejs/node-gyp/pull/2230)
* [[`754996b9ec`](https://github.com/nodejs/node-gyp/commit/754996b9ec)] - **doc**: replace status badges with new Actions badge (Rod Vagg) [#2218](https://github.com/nodejs/node-gyp/pull/2218)
* [[`2317dc400c`](https://github.com/nodejs/node-gyp/commit/2317dc400c)] - **ci**: switch to GitHub Actions (Shelley Vohr) [#2210](https://github.com/nodejs/node-gyp/pull/2210)
* [[`2cca9b74f7`](https://github.com/nodejs/node-gyp/commit/2cca9b74f7)] - **doc**: drop the --production flag for installing windows-build-tools (DeeDeeG) [#2206](https://github.com/nodejs/node-gyp/pull/2206)

## v7.1.0 2020-08-12

* [[`aaf33c3029`](https://github.com/nodejs/node-gyp/commit/aaf33c3029)] - **build**: add update-gyp script (Samuel Attard) [#2167](https://github.com/nodejs/node-gyp/pull/2167)
* * [[`3baa4e4172`](https://github.com/nodejs/node-gyp/commit/3baa4e4172)] - **(SEMVER-MINOR)** **gyp**: update gyp to 0.4.0 (Samuel Attard) [#2165](https://github.com/nodejs/node-gyp/pull/2165)
* * [[`f461d56c53`](https://github.com/nodejs/node-gyp/commit/f461d56c53)] - **(SEMVER-MINOR)** **build**: support apple silicon (arm64 darwin) builds (Samuel Attard) [#2165](https://github.com/nodejs/node-gyp/pull/2165)
* * [[`ee6fa7d3bc`](https://github.com/nodejs/node-gyp/commit/ee6fa7d3bc)] - **docs**: note that node-gyp@7 should solve Catalina CLT issues (Rod Vagg) [#2156](https://github.com/nodejs/node-gyp/pull/2156)
* * [[`4fc8ff179d`](https://github.com/nodejs/node-gyp/commit/4fc8ff179d)] - **doc**: silence curl for macOS Catalina acid test (Chia Wei Ong) [#2150](https://github.com/nodejs/node-gyp/pull/2150)
* * [[`7857cb2eb1`](https://github.com/nodejs/node-gyp/commit/7857cb2eb1)] - **deps**: increase "engines" to "node" : "\>= 10.12.0" (DeeDeeG) [#2153](https://github.com/nodejs/node-gyp/pull/2153)

## v7.0.0 2020-06-03

* [[`e18a61afc1`](https://github.com/nodejs/node-gyp/commit/e18a61afc1)] - **build**: shrink bloated addon binaries on windows (Shelley Vohr) [#2060](https://github.com/nodejs/node-gyp/pull/2060)
* [[`4937722cf5`](https://github.com/nodejs/node-gyp/commit/4937722cf5)] - **(SEMVER-MAJOR)** **deps**: replace mkdirp with {recursive} mkdir (Rod Vagg) [#2123](https://github.com/nodejs/node-gyp/pull/2123)
* [[`d45438a047`](https://github.com/nodejs/node-gyp/commit/d45438a047)] - **(SEMVER-MAJOR)** **deps**: update deps, match to npm@7 (Rod Vagg) [#2126](https://github.com/nodejs/node-gyp/pull/2126)
* [[`ba4f34b7d6`](https://github.com/nodejs/node-gyp/commit/ba4f34b7d6)] - **doc**: update catalina xcode clt download link (Dario Vladovic) [#2133](https://github.com/nodejs/node-gyp/pull/2133)
* [[`f7bfce96ed`](https://github.com/nodejs/node-gyp/commit/f7bfce96ed)] - **doc**: update acid test and introduce curl|bash test script (Dario Vladovic) [#2105](https://github.com/nodejs/node-gyp/pull/2105)
* [[`e529f3309d`](https://github.com/nodejs/node-gyp/commit/e529f3309d)] - **doc**: update README to reflect upgrade to gyp-next (Ujjwal Sharma) [#2092](https://github.com/nodejs/node-gyp/pull/2092)
* [[`9aed6286a3`](https://github.com/nodejs/node-gyp/commit/9aed6286a3)] - **doc**: give more attention to Catalina issues doc (Matheus Marchini) [#2134](https://github.com/nodejs/node-gyp/pull/2134)
* [[`963f2a7b48`](https://github.com/nodejs/node-gyp/commit/963f2a7b48)] - **doc**: improve Catalina discoverability for search engines (Matheus Marchini) [#2135](https://github.com/nodejs/node-gyp/pull/2135)
* [[`7b75af349b`](https://github.com/nodejs/node-gyp/commit/7b75af349b)] - **doc**: add macOS Catalina software update info (Karl Horky) [#2078](https://github.com/nodejs/node-gyp/pull/2078)
* [[`4f23c7bee2`](https://github.com/nodejs/node-gyp/commit/4f23c7bee2)] - **doc**: update link to the code of conduct (#2073) (Michaël Zasso) [#2073](https://github.com/nodejs/node-gyp/pull/2073)
* [[`473cfa283f`](https://github.com/nodejs/node-gyp/commit/473cfa283f)] - **doc**: note in README that Python 3.8 is supported (#2072) (Michaël Zasso) [#2072](https://github.com/nodejs/node-gyp/pull/2072)
* [[`e7402b4a7c`](https://github.com/nodejs/node-gyp/commit/e7402b4a7c)] - **doc**: update catalina xcode cli tools download link (#2044) (Dario Vladović) [#2044](https://github.com/nodejs/node-gyp/pull/2044)
* [[`35de45984f`](https://github.com/nodejs/node-gyp/commit/35de45984f)] - **doc**: update catalina xcode cli tools download link; formatting (Jonathan Hult) [#2034](https://github.com/nodejs/node-gyp/pull/2034)
* [[`48642191f5`](https://github.com/nodejs/node-gyp/commit/48642191f5)] - **doc**: add download link for Command Line Tools for Xcode (Przemysław Bitkowski) [#2029](https://github.com/nodejs/node-gyp/pull/2029)
* [[`ae5b150051`](https://github.com/nodejs/node-gyp/commit/ae5b150051)] - **doc**: Catalina suggestion: remove /Library/Developer/CommandLineTools (Christian Clauss) [#2022](https://github.com/nodejs/node-gyp/pull/2022)
* [[`d1dea13fe4`](https://github.com/nodejs/node-gyp/commit/d1dea13fe4)] - **doc**: fix changelog 6.1.0 release year to be 2020 (Quentin Vernot) [#2021](https://github.com/nodejs/node-gyp/pull/2021)
* [[`6356117b08`](https://github.com/nodejs/node-gyp/commit/6356117b08)] - **doc, bin**: stop suggesting opening  node-gyp issues (Bartosz Sosnowski) [#2096](https://github.com/nodejs/node-gyp/pull/2096)
* [[`a6b76a8b48`](https://github.com/nodejs/node-gyp/commit/a6b76a8b48)] - **gyp**: update gyp to 0.2.1 (Ujjwal Sharma) [#2092](https://github.com/nodejs/node-gyp/pull/2092)
* [[`ebc34ec823`](https://github.com/nodejs/node-gyp/commit/ebc34ec823)] - **gyp**: update gyp to 0.2.0 (Ujjwal Sharma) [#2092](https://github.com/nodejs/node-gyp/pull/2092)
* [[`972780bde7`](https://github.com/nodejs/node-gyp/commit/972780bde7)] - **(SEMVER-MAJOR)** **gyp**: sync code base with nodejs repo (#1975) (Michaël Zasso) [#1975](https://github.com/nodejs/node-gyp/pull/1975)
* [[`c255ffbf6a`](https://github.com/nodejs/node-gyp/commit/c255ffbf6a)] - **lib**: drop "-2" flag for "py.exe" launcher (DeeDeeG) [#2131](https://github.com/nodejs/node-gyp/pull/2131)
* [[`1f7e1e93b5`](https://github.com/nodejs/node-gyp/commit/1f7e1e93b5)] - **lib**: ignore VS instances that cause COMExceptions (Andrew Casey) [#2018](https://github.com/nodejs/node-gyp/pull/2018)
* [[`741ab096d5`](https://github.com/nodejs/node-gyp/commit/741ab096d5)] - **test**: remove support for EOL versions of Node.js (Shelley Vohr)
* [[`ca86ef2539`](https://github.com/nodejs/node-gyp/commit/ca86ef2539)] - **test**: bump actions/checkout from v1 to v2 (BSKY) [#2063](https://github.com/nodejs/node-gyp/pull/2063)

## v6.1.0 2020-01-08

* [[`9a7dd16b76`](https://github.com/nodejs/node-gyp/commit/9a7dd16b76)] - **doc**: remove backticks from Python version list (Rod Vagg) [#2011](https://github.com/nodejs/node-gyp/pull/2011)
* [[`26cd6eaea6`](https://github.com/nodejs/node-gyp/commit/26cd6eaea6)] - **doc**: add GitHub Actions badge (#1994) (Rod Vagg) [#1994](https://github.com/nodejs/node-gyp/pull/1994)
* [[`312c12ef4f`](https://github.com/nodejs/node-gyp/commit/312c12ef4f)] - **doc**: update macOS\_Catalina.md (#1992) (James Home) [#1992](https://github.com/nodejs/node-gyp/pull/1992)
* [[`f7b6b6b77b`](https://github.com/nodejs/node-gyp/commit/f7b6b6b77b)] - **doc**: fix typo in README.md (#1985) (Suraneti Rodsuwan) [#1985](https://github.com/nodejs/node-gyp/pull/1985)
* [[`6b8f2652dd`](https://github.com/nodejs/node-gyp/commit/6b8f2652dd)] - **doc**: add travis badge (Rod Vagg) [#1971](https://github.com/nodejs/node-gyp/pull/1971)
* [[`20aa0b44f7`](https://github.com/nodejs/node-gyp/commit/20aa0b44f7)] - **doc**: macOS Catalina add two commands (Christian Clauss) [#1962](https://github.com/nodejs/node-gyp/pull/1962)
* [[`14f2a07a39`](https://github.com/nodejs/node-gyp/commit/14f2a07a39)] - **gyp**: list(dict) so we can del dict(key) while iterating (Christian Clauss) [#2009](https://github.com/nodejs/node-gyp/pull/2009)
* [[`f242ce4d2c`](https://github.com/nodejs/node-gyp/commit/f242ce4d2c)] - **lib**: compatibility with semver ≥ 7 (`new` for semver.Range) (Xavier Guimard) [#2006](https://github.com/nodejs/node-gyp/pull/2006)
* [[`3bcba2a01a`](https://github.com/nodejs/node-gyp/commit/3bcba2a01a)] - **(SEMVER-MINOR)** **lib**: noproxy support, match proxy detection to `request` (Matias Lopez) [#1978](https://github.com/nodejs/node-gyp/pull/1978)
* [[`470cc2178e`](https://github.com/nodejs/node-gyp/commit/470cc2178e)] - **test**: remove old docker test harness (#1993) (Rod Vagg) [#1993](https://github.com/nodejs/node-gyp/pull/1993)
* [[`31ecc8421d`](https://github.com/nodejs/node-gyp/commit/31ecc8421d)] - **test**: add Windows to GitHub Actions testing (#1996) (Christian Clauss) [#1996](https://github.com/nodejs/node-gyp/pull/1996)
* [[`5a729e86ee`](https://github.com/nodejs/node-gyp/commit/5a729e86ee)] - **test**: fix typo in header download test (#2001) (Richard Lau) [#2001](https://github.com/nodejs/node-gyp/pull/2001)
* [[`345c70e56d`](https://github.com/nodejs/node-gyp/commit/345c70e56d)] - **test**: direct python invocation & simpler pyenv (Matias Lopez) [#1979](https://github.com/nodejs/node-gyp/pull/1979)
* [[`d6a7e0e1fb`](https://github.com/nodejs/node-gyp/commit/d6a7e0e1fb)] - **test**: fix macOS Travis on Python 2.7 & 3.7 (Christian Clauss) [#1979](https://github.com/nodejs/node-gyp/pull/1979)
* [[`5a64e9bd32`](https://github.com/nodejs/node-gyp/commit/5a64e9bd32)] - **test**: initial Github Actions with Ubuntu & macOS (Christian Clauss) [#1985](https://github.com/nodejs/node-gyp/pull/1985)
* [[`04da736d38`](https://github.com/nodejs/node-gyp/commit/04da736d38)] - **test**: fix Python unittests (cclauss) [#1961](https://github.com/nodejs/node-gyp/pull/1961)
* [[`0670e5189d`](https://github.com/nodejs/node-gyp/commit/0670e5189d)] - **test**: add header download test (Rod Vagg) [#1796](https://github.com/nodejs/node-gyp/pull/1796)
* [[`c506a6a150`](https://github.com/nodejs/node-gyp/commit/c506a6a150)] - **test**: configure proper devDir for invoking configure() (Rod Vagg) [#1796](https://github.com/nodejs/node-gyp/pull/1796)

## v6.0.1 2019-11-01

* [[`8ec2e681d5`](https://github.com/nodejs/node-gyp/commit/8ec2e681d5)] - **doc**: add macOS\_Catalina.md document (cclauss) [#1940](https://github.com/nodejs/node-gyp/pull/1940)
* [[`1b11be63cc`](https://github.com/nodejs/node-gyp/commit/1b11be63cc)] - **gyp**: python3 fixes: utf8 decode, use of 'None' in eval (Wilfried Goesgens) [#1925](https://github.com/nodejs/node-gyp/pull/1925)
* [[`c0282daa48`](https://github.com/nodejs/node-gyp/commit/c0282daa48)] - **gyp**: iteritems() -\> items() in compile\_commands\_json.py (cclauss) [#1947](https://github.com/nodejs/node-gyp/pull/1947)
* [[`d8e09a1b6a`](https://github.com/nodejs/node-gyp/commit/d8e09a1b6a)] - **gyp**: make cmake python3 compatible (gengjiawen) [#1944](https://github.com/nodejs/node-gyp/pull/1944)
* [[`9c0f3404f0`](https://github.com/nodejs/node-gyp/commit/9c0f3404f0)] - **gyp**: fix TypeError in XcodeVersion() (Christian Clauss) [#1939](https://github.com/nodejs/node-gyp/pull/1939)
* [[`bb2eb72a3f`](https://github.com/nodejs/node-gyp/commit/bb2eb72a3f)] - **gyp**: finish decode stdout on Python 3 (Christian Clauss) [#1937](https://github.com/nodejs/node-gyp/pull/1937)
* [[`f0693413d9`](https://github.com/nodejs/node-gyp/commit/f0693413d9)] - **src,win**: allow 403 errors for arm64 node.lib (Richard Lau) [#1934](https://github.com/nodejs/node-gyp/pull/1934)
* [[`c60c22de58`](https://github.com/nodejs/node-gyp/commit/c60c22de58)] - **deps**: update deps to roughly match current npm@6 (Rod Vagg) [#1920](https://github.com/nodejs/node-gyp/pull/1920)
* [[`b91718eefc`](https://github.com/nodejs/node-gyp/commit/b91718eefc)] - **test**: upgrade Linux Travis CI to Python 3.8 (Christian Clauss) [#1923](https://github.com/nodejs/node-gyp/pull/1923)
* [[`3538a317b6`](https://github.com/nodejs/node-gyp/commit/3538a317b6)] - **doc**: adjustments to the README.md for new users (Dan Pike) [#1919](https://github.com/nodejs/node-gyp/pull/1919)
* [[`4fff8458c0`](https://github.com/nodejs/node-gyp/commit/4fff8458c0)] - **travis**: ignore failed `brew upgrade npm`, update xcode (Christian Clauss) [#1932](https://github.com/nodejs/node-gyp/pull/1932)
* [[`60e4488f08`](https://github.com/nodejs/node-gyp/commit/60e4488f08)] - **build**: avoid bare exceptions in xcode\_emulation.py (Christian Clauss) [#1932](https://github.com/nodejs/node-gyp/pull/1932)
* [[`032db2a2d0`](https://github.com/nodejs/node-gyp/commit/032db2a2d0)] - **lib,install**: always download SHA sums on Windows (Sam Hughes) [#1926](https://github.com/nodejs/node-gyp/pull/1926)
* [[`5a83630c33`](https://github.com/nodejs/node-gyp/commit/5a83630c33)] - **travis**: add Windows + Python 3.8 to the mix (Rod Vagg) [#1921](https://github.com/nodejs/node-gyp/pull/1921)

## v6.0.0 2019-10-04

* [[`dd0e97ef0b`](https://github.com/nodejs/node-gyp/commit/dd0e97ef0b)] - **(SEMVER-MAJOR)** **lib**: try to find `python` after `python3` (Sam Roberts) [#1907](https://github.com/nodejs/node-gyp/pull/1907)
* [[`f60ed47d14`](https://github.com/nodejs/node-gyp/commit/f60ed47d14)] - **travis**: add Python 3.5 and 3.6 tests on Linux (Christian Clauss) [#1903](https://github.com/nodejs/node-gyp/pull/1903)
* [[`c763ca1838`](https://github.com/nodejs/node-gyp/commit/c763ca1838)] - **(SEMVER-MAJOR)** **doc**: Declare that node-gyp is Python 3 compatible (cclauss) [#1811](https://github.com/nodejs/node-gyp/pull/1811)
* [[`3d1c60ab81`](https://github.com/nodejs/node-gyp/commit/3d1c60ab81)] - **(SEMVER-MAJOR)** **lib**: accept Python 3 by default (João Reis) [#1844](https://github.com/nodejs/node-gyp/pull/1844)
* [[`c6e3b65a23`](https://github.com/nodejs/node-gyp/commit/c6e3b65a23)] - **(SEMVER-MAJOR)** **lib**: raise the minimum Python version from 2.6 to 2.7 (cclauss) [#1818](https://github.com/nodejs/node-gyp/pull/1818)

## v5.1.1 2020-05-25

* [[`bdd3a79abe`](https://github.com/nodejs/node-gyp/commit/bdd3a79abe)] - **build**: shrink bloated addon binaries on windows (Shelley Vohr) [#2060](https://github.com/nodejs/node-gyp/pull/2060)
* [[`1f2ba75bc0`](https://github.com/nodejs/node-gyp/commit/1f2ba75bc0)] - **doc**: add macOS Catalina software update info (Karl Horky) [#2078](https://github.com/nodejs/node-gyp/pull/2078)
* [[`c106d915f5`](https://github.com/nodejs/node-gyp/commit/c106d915f5)] - **doc**: update catalina xcode cli tools download link (#2044) (Dario Vladović) [#2044](https://github.com/nodejs/node-gyp/pull/2044)
* [[`9a6fea92e2`](https://github.com/nodejs/node-gyp/commit/9a6fea92e2)] - **doc**: update catalina xcode cli tools download link; formatting (Jonathan Hult) [#2034](https://github.com/nodejs/node-gyp/pull/2034)
* [[`59b0b1add8`](https://github.com/nodejs/node-gyp/commit/59b0b1add8)] - **doc**: add download link for Command Line Tools for Xcode (Przemysław Bitkowski) [#2029](https://github.com/nodejs/node-gyp/pull/2029)
* [[`bb8d0e7b10`](https://github.com/nodejs/node-gyp/commit/bb8d0e7b10)] - **doc**: Catalina suggestion: remove /Library/Developer/CommandLineTools (Christian Clauss) [#2022](https://github.com/nodejs/node-gyp/pull/2022)
* [[`fb2e80d4e3`](https://github.com/nodejs/node-gyp/commit/fb2e80d4e3)] - **doc**: update link to the code of conduct (#2073) (Michaël Zasso) [#2073](https://github.com/nodejs/node-gyp/pull/2073)
* [[`251d9c885c`](https://github.com/nodejs/node-gyp/commit/251d9c885c)] - **doc**: note in README that Python 3.8 is supported (#2072) (Michaël Zasso) [#2072](https://github.com/nodejs/node-gyp/pull/2072)
* [[`2b6fc3c8d6`](https://github.com/nodejs/node-gyp/commit/2b6fc3c8d6)] - **doc, bin**: stop suggesting opening  node-gyp issues (Bartosz Sosnowski) [#2096](https://github.com/nodejs/node-gyp/pull/2096)
* [[`a876ae58ad`](https://github.com/nodejs/node-gyp/commit/a876ae58ad)] - **test**: bump actions/checkout from v1 to v2 (BSKY) [#2063](https://github.com/nodejs/node-gyp/pull/2063)

## v5.1.0 2020-02-05

* [[`f37a8b40d0`](https://github.com/nodejs/node-gyp/commit/f37a8b40d0)] - **doc**: add GitHub Actions badge (#1994) (Rod Vagg) [#1994](https://github.com/nodejs/node-gyp/pull/1994)
* [[`cb3f6aae5e`](https://github.com/nodejs/node-gyp/commit/cb3f6aae5e)] - **doc**: update macOS\_Catalina.md (#1992) (James Home) [#1992](https://github.com/nodejs/node-gyp/pull/1992)
* [[`0607596a4c`](https://github.com/nodejs/node-gyp/commit/0607596a4c)] - **doc**: fix typo in README.md (#1985) (Suraneti Rodsuwan) [#1985](https://github.com/nodejs/node-gyp/pull/1985)
* [[`0d5a415a14`](https://github.com/nodejs/node-gyp/commit/0d5a415a14)] - **doc**: add travis badge (Rod Vagg) [#1971](https://github.com/nodejs/node-gyp/pull/1971)
* [[`103740cd95`](https://github.com/nodejs/node-gyp/commit/103740cd95)] - **gyp**: list(dict) so we can del dict(key) while iterating (Christian Clauss) [#2009](https://github.com/nodejs/node-gyp/pull/2009)
* [[`278dcddbdd`](https://github.com/nodejs/node-gyp/commit/278dcddbdd)] - **lib**: ignore VS instances that cause COMExceptions (Andrew Casey) [#2018](https://github.com/nodejs/node-gyp/pull/2018)
* [[`1694907bbf`](https://github.com/nodejs/node-gyp/commit/1694907bbf)] - **lib**: compatibility with semver ≥ 7 (`new` for semver.Range) (Xavier Guimard) [#2006](https://github.com/nodejs/node-gyp/pull/2006)
* [[`a3f1143514`](https://github.com/nodejs/node-gyp/commit/a3f1143514)] - **(SEMVER-MINOR)** **lib**: noproxy support, match proxy detection to `request` (Matias Lopez) [#1978](https://github.com/nodejs/node-gyp/pull/1978)
* [[`52365819c7`](https://github.com/nodejs/node-gyp/commit/52365819c7)] - **test**: remove old docker test harness (#1993) (Rod Vagg) [#1993](https://github.com/nodejs/node-gyp/pull/1993)
* [[`bc509c511d`](https://github.com/nodejs/node-gyp/commit/bc509c511d)] - **test**: add Windows to GitHub Actions testing (#1996) (Christian Clauss) [#1996](https://github.com/nodejs/node-gyp/pull/1996)
* [[`91ee26dd48`](https://github.com/nodejs/node-gyp/commit/91ee26dd48)] - **test**: fix typo in header download test (#2001) (Richard Lau) [#2001](https://github.com/nodejs/node-gyp/pull/2001)
* [[`0923f344c9`](https://github.com/nodejs/node-gyp/commit/0923f344c9)] - **test**: direct python invocation & simpler pyenv (Matias Lopez) [#1979](https://github.com/nodejs/node-gyp/pull/1979)
* [[`32c8744b34`](https://github.com/nodejs/node-gyp/commit/32c8744b34)] - **test**: fix macOS Travis on Python 2.7 & 3.7 (Christian Clauss) [#1979](https://github.com/nodejs/node-gyp/pull/1979)
* [[`fd4b1351e4`](https://github.com/nodejs/node-gyp/commit/fd4b1351e4)] - **test**: initial Github Actions with Ubuntu & macOS (Christian Clauss) [#1985](https://github.com/nodejs/node-gyp/pull/1985)

## v5.0.7 2019-12-16

Republish of v5.0.6 with unnecessary tarball removed from pack file.

## v5.0.6 2019-12-16

* [[`cdec00286f`](https://github.com/nodejs/node-gyp/commit/cdec00286f)] - **doc**: adjustments to the README.md for new users (Dan Pike) [#1919](https://github.com/nodejs/node-gyp/pull/1919)
* [[`b7c8233ef2`](https://github.com/nodejs/node-gyp/commit/b7c8233ef2)] - **test**: fix Python unittests (cclauss) [#1961](https://github.com/nodejs/node-gyp/pull/1961)
* [[`e12b00ab0a`](https://github.com/nodejs/node-gyp/commit/e12b00ab0a)] - **doc**: macOS Catalina add two commands (Christian Clauss) [#1962](https://github.com/nodejs/node-gyp/pull/1962)
* [[`70b9890c0d`](https://github.com/nodejs/node-gyp/commit/70b9890c0d)] - **test**: add header download test (Rod Vagg) [#1796](https://github.com/nodejs/node-gyp/pull/1796)
* [[`4029fa8629`](https://github.com/nodejs/node-gyp/commit/4029fa8629)] - **test**: configure proper devDir for invoking configure() (Rod Vagg) [#1796](https://github.com/nodejs/node-gyp/pull/1796)
* [[`fe8b02cc8b`](https://github.com/nodejs/node-gyp/commit/fe8b02cc8b)] - **doc**: add macOS\_Catalina.md document (cclauss) [#1940](https://github.com/nodejs/node-gyp/pull/1940)
* [[`8ea47ce365`](https://github.com/nodejs/node-gyp/commit/8ea47ce365)] - **gyp**: python3 fixes: utf8 decode, use of 'None' in eval (Wilfried Goesgens) [#1925](https://github.com/nodejs/node-gyp/pull/1925)
* [[`c7229716ba`](https://github.com/nodejs/node-gyp/commit/c7229716ba)] - **gyp**: iteritems() -\> items() in compile\_commands\_json.py (cclauss) [#1947](https://github.com/nodejs/node-gyp/pull/1947)
* [[`2a18b2a0f8`](https://github.com/nodejs/node-gyp/commit/2a18b2a0f8)] - **gyp**: make cmake python3 compatible (gengjiawen) [#1944](https://github.com/nodejs/node-gyp/pull/1944)
* [[`70f391e844`](https://github.com/nodejs/node-gyp/commit/70f391e844)] - **gyp**: fix TypeError in XcodeVersion() (Christian Clauss) [#1939](https://github.com/nodejs/node-gyp/pull/1939)
* [[`9f4f0fa34e`](https://github.com/nodejs/node-gyp/commit/9f4f0fa34e)] - **gyp**: finish decode stdout on Python 3 (Christian Clauss) [#1937](https://github.com/nodejs/node-gyp/pull/1937)
* [[`7cf507906d`](https://github.com/nodejs/node-gyp/commit/7cf507906d)] - **src,win**: allow 403 errors for arm64 node.lib (Richard Lau) [#1934](https://github.com/nodejs/node-gyp/pull/1934)
* [[`ad0d182c01`](https://github.com/nodejs/node-gyp/commit/ad0d182c01)] - **deps**: update deps to roughly match current npm@6 (Rod Vagg) [#1920](https://github.com/nodejs/node-gyp/pull/1920)
* [[`1553081ed6`](https://github.com/nodejs/node-gyp/commit/1553081ed6)] - **test**: upgrade Linux Travis CI to Python 3.8 (Christian Clauss) [#1923](https://github.com/nodejs/node-gyp/pull/1923)
* [[`0705cae9aa`](https://github.com/nodejs/node-gyp/commit/0705cae9aa)] - **travis**: ignore failed `brew upgrade npm`, update xcode (Christian Clauss) [#1932](https://github.com/nodejs/node-gyp/pull/1932)
* [[`7bfdb6f5bf`](https://github.com/nodejs/node-gyp/commit/7bfdb6f5bf)] - **build**: avoid bare exceptions in xcode\_emulation.py (Christian Clauss) [#1932](https://github.com/nodejs/node-gyp/pull/1932)
* [[`7edf7658fa`](https://github.com/nodejs/node-gyp/commit/7edf7658fa)] - **lib,install**: always download SHA sums on Windows (Sam Hughes) [#1926](https://github.com/nodejs/node-gyp/pull/1926)
* [[`69056d04fe`](https://github.com/nodejs/node-gyp/commit/69056d04fe)] - **travis**: add Windows + Python 3.8 to the mix (Rod Vagg) [#1921](https://github.com/nodejs/node-gyp/pull/1921)

## v5.0.5 2019-10-04

* [[`3891391746`](https://github.com/nodejs/node-gyp/commit/3891391746)] - **doc**: reconcile README with Python 3 compat changes (Rod Vagg) [#1911](https://github.com/nodejs/node-gyp/pull/1911)
* [[`07f81f1920`](https://github.com/nodejs/node-gyp/commit/07f81f1920)] - **lib**: accept Python 3 after Python 2 (Sam Roberts) [#1910](https://github.com/nodejs/node-gyp/pull/1910)
* [[`04ce59f4a2`](https://github.com/nodejs/node-gyp/commit/04ce59f4a2)] - **doc**: clarify Python configuration, etc (Sam Roberts) [#1908](https://github.com/nodejs/node-gyp/pull/1908)
* [[`01c46ee3df`](https://github.com/nodejs/node-gyp/commit/01c46ee3df)] - **gyp**: add \_\_lt\_\_ to MSVSSolutionEntry (João Reis) [#1904](https://github.com/nodejs/node-gyp/pull/1904)
* [[`735d961b99`](https://github.com/nodejs/node-gyp/commit/735d961b99)] - **win**: support VS 2017 Desktop Express (João Reis) [#1902](https://github.com/nodejs/node-gyp/pull/1902)
* [[`3834156a92`](https://github.com/nodejs/node-gyp/commit/3834156a92)] - **test**: add Python 3.5 and 3.6 tests on Linux (cclauss) [#1909](https://github.com/nodejs/node-gyp/pull/1909)
* [[`1196e990d8`](https://github.com/nodejs/node-gyp/commit/1196e990d8)] - **src**: update to standard@14 (Rod Vagg) [#1899](https://github.com/nodejs/node-gyp/pull/1899)
* [[`53ee7dfe89`](https://github.com/nodejs/node-gyp/commit/53ee7dfe89)] - **gyp**: fix undefined name: cflags --\> ldflags (Christian Clauss) [#1901](https://github.com/nodejs/node-gyp/pull/1901)
* [[`5871dcf6c9`](https://github.com/nodejs/node-gyp/commit/5871dcf6c9)] - **src,win**: add support for fetching arm64 node.lib (Richard Townsend) [#1875](https://github.com/nodejs/node-gyp/pull/1875)

## v5.0.4 2019-09-27

* [[`1236869ffc`](https://github.com/nodejs/node-gyp/commit/1236869ffc)] - **gyp**: modify XcodeVersion() to convert "4.2" to "0420" and "10.0" to "1000" (Christian Clauss) [#1895](https://github.com/nodejs/node-gyp/pull/1895)
* [[`36638afe48`](https://github.com/nodejs/node-gyp/commit/36638afe48)] - **gyp**: more decode stdout on Python 3 (cclauss) [#1894](https://github.com/nodejs/node-gyp/pull/1894)
* [[`f753c167c5`](https://github.com/nodejs/node-gyp/commit/f753c167c5)] - **gyp**: decode stdout on Python 3 (cclauss) [#1890](https://github.com/nodejs/node-gyp/pull/1890)
* [[`60a4083523`](https://github.com/nodejs/node-gyp/commit/60a4083523)] - **doc**: update xcode install instructions to match Node's BUILDING (Nhan Khong) [#1884](https://github.com/nodejs/node-gyp/pull/1884)
* [[`19dbc9ac32`](https://github.com/nodejs/node-gyp/commit/19dbc9ac32)] - **deps**: update tar to 4.4.12 (Matheus Marchini) [#1889](https://github.com/nodejs/node-gyp/pull/1889)
* [[`5f3ed92181`](https://github.com/nodejs/node-gyp/commit/5f3ed92181)] - **bin**: fix the usage instructions (Halit Ogunc) [#1888](https://github.com/nodejs/node-gyp/pull/1888)
* [[`aab118edf1`](https://github.com/nodejs/node-gyp/commit/aab118edf1)] - **lib**: adding keep-alive header to download requests (Milad Farazmand) [#1863](https://github.com/nodejs/node-gyp/pull/1863)
* [[`1186e89326`](https://github.com/nodejs/node-gyp/commit/1186e89326)] - **lib**: ignore non-critical os.userInfo() failures (Rod Vagg) [#1835](https://github.com/nodejs/node-gyp/pull/1835)
* [[`785e527c3d`](https://github.com/nodejs/node-gyp/commit/785e527c3d)] - **doc**: fix missing argument for setting python path (lagorsse) [#1802](https://github.com/nodejs/node-gyp/pull/1802)
* [[`a97615196c`](https://github.com/nodejs/node-gyp/commit/a97615196c)] - **gyp**: rm semicolons (Python != JavaScript) (MattIPv4) [#1858](https://github.com/nodejs/node-gyp/pull/1858)
* [[`06019bac24`](https://github.com/nodejs/node-gyp/commit/06019bac24)] - **gyp**: assorted typo fixes (XhmikosR) [#1853](https://github.com/nodejs/node-gyp/pull/1853)
* [[`3f4972c1ca`](https://github.com/nodejs/node-gyp/commit/3f4972c1ca)] - **gyp**: use "is" when comparing to None (Vladyslav Burzakovskyy) [#1860](https://github.com/nodejs/node-gyp/pull/1860)
* [[`1cb4708073`](https://github.com/nodejs/node-gyp/commit/1cb4708073)] - **src,win**: improve unmanaged handling (Peter Sabath) [#1852](https://github.com/nodejs/node-gyp/pull/1852)
* [[`5553cd910e`](https://github.com/nodejs/node-gyp/commit/5553cd910e)] - **gyp**: improve Windows+Cygwin compatibility (Jose Quijada) [#1817](https://github.com/nodejs/node-gyp/pull/1817)
* [[`8bcb1fbb43`](https://github.com/nodejs/node-gyp/commit/8bcb1fbb43)] - **gyp**: Python 3 Windows fixes (João Reis) [#1843](https://github.com/nodejs/node-gyp/pull/1843)
* [[`2e24d0a326`](https://github.com/nodejs/node-gyp/commit/2e24d0a326)] - **test**: accept Python 3 in test-find-python.js (João Reis) [#1843](https://github.com/nodejs/node-gyp/pull/1843)
* [[`1267b4dc1c`](https://github.com/nodejs/node-gyp/commit/1267b4dc1c)] - **build**: add test run Python 3.7 on macOS (Christian Clauss) [#1843](https://github.com/nodejs/node-gyp/pull/1843)
* [[`da1b031aa3`](https://github.com/nodejs/node-gyp/commit/da1b031aa3)] - **build**: import StringIO on Python 2 and Python 3 (Christian Clauss) [#1836](https://github.com/nodejs/node-gyp/pull/1836)
* [[`fa0ed4aa42`](https://github.com/nodejs/node-gyp/commit/fa0ed4aa42)] - **build**: more Python 3 compat, replace compile with ast (cclauss) [#1820](https://github.com/nodejs/node-gyp/pull/1820)
* [[`18d5c7c9d0`](https://github.com/nodejs/node-gyp/commit/18d5c7c9d0)] - **win,src**: update win\_delay\_load\_hook.cc to work with /clr (Ivan Petrovic) [#1819](https://github.com/nodejs/node-gyp/pull/1819)

## v5.0.3 2019-07-17

* [[`66ad305775`](https://github.com/nodejs/node-gyp/commit/66ad305775)] - **python**: accept Python 3 conditionally (João Reis) [#1815](https://github.com/nodejs/node-gyp/pull/1815)
* [[`7e7fce3fed`](https://github.com/nodejs/node-gyp/commit/7e7fce3fed)] - **python**: move Python detection to its own file (João Reis) [#1815](https://github.com/nodejs/node-gyp/pull/1815)
* [[`e40c99e283`](https://github.com/nodejs/node-gyp/commit/e40c99e283)] - **src**: implement standard.js linting (Rod Vagg) [#1794](https://github.com/nodejs/node-gyp/pull/1794)
* [[`bb92c761a9`](https://github.com/nodejs/node-gyp/commit/bb92c761a9)] - **test**: add Node.js 6 on Windows to Travis CI (João Reis) [#1812](https://github.com/nodejs/node-gyp/pull/1812)
* [[`7fd924079f`](https://github.com/nodejs/node-gyp/commit/7fd924079f)] - **test**: increase tap timeout (João Reis) [#1812](https://github.com/nodejs/node-gyp/pull/1812)
* [[`7e8127068f`](https://github.com/nodejs/node-gyp/commit/7e8127068f)] - **test**: cover supported node versions with travis (Rod Vagg) [#1809](https://github.com/nodejs/node-gyp/pull/1809)
* [[`24109148df`](https://github.com/nodejs/node-gyp/commit/24109148df)] - **test**: downgrade to tap@^12 for continued Node 6 support (Rod Vagg) [#1808](https://github.com/nodejs/node-gyp/pull/1808)
* [[`656117cc4a`](https://github.com/nodejs/node-gyp/commit/656117cc4a)] - **win**: make VS path match case-insensitive (João Reis) [#1806](https://github.com/nodejs/node-gyp/pull/1806)

## v5.0.2 2019-06-27

* [[`2761afbf73`](https://github.com/nodejs/node-gyp/commit/2761afbf73)] - **build,test**: add duplicate symbol test (Gabriel Schulhof) [#1689](https://github.com/nodejs/node-gyp/pull/1689)
* [[`82f129d6de`](https://github.com/nodejs/node-gyp/commit/82f129d6de)] - **gyp**: replace optparse to argparse (KiYugadgeter) [#1591](https://github.com/nodejs/node-gyp/pull/1591)
* [[`afaaa29c61`](https://github.com/nodejs/node-gyp/commit/afaaa29c61)] - **gyp**: remove from \_\_future\_\_ import with\_statement (cclauss) [#1799](https://github.com/nodejs/node-gyp/pull/1799)
* [[`a991f633d6`](https://github.com/nodejs/node-gyp/commit/a991f633d6)] - **gyp**: fix the remaining Python 3 issues (cclauss) [#1793](https://github.com/nodejs/node-gyp/pull/1793)
* [[`f952b08f84`](https://github.com/nodejs/node-gyp/commit/f952b08f84)] - **gyp**: move from \_\_future\_\_ import to the top of the file (cclauss) [#1789](https://github.com/nodejs/node-gyp/pull/1789)
* [[`4f4a677dfa`](https://github.com/nodejs/node-gyp/commit/4f4a677dfa)] - **gyp**: use different default compiler for z/OS (Shuowang (Wayne) Zhang) [#1768](https://github.com/nodejs/node-gyp/pull/1768)
* [[`03683f09d6`](https://github.com/nodejs/node-gyp/commit/03683f09d6)] - **lib**: code de-duplication (Pavel Medvedev) [#965](https://github.com/nodejs/node-gyp/pull/965)
* [[`611bc3c89f`](https://github.com/nodejs/node-gyp/commit/611bc3c89f)] - **lib**: add .json suffix for explicit require (Rod Vagg) [#1787](https://github.com/nodejs/node-gyp/pull/1787)
* [[`d3478d7b0b`](https://github.com/nodejs/node-gyp/commit/d3478d7b0b)] - **meta**: add to .gitignore (Refael Ackermann) [#1573](https://github.com/nodejs/node-gyp/pull/1573)
* [[`7a9a038e9e`](https://github.com/nodejs/node-gyp/commit/7a9a038e9e)] - **test**: add parallel test runs on macOS and Windows (cclauss) [#1800](https://github.com/nodejs/node-gyp/pull/1800)
* [[`7dd7f2b2a2`](https://github.com/nodejs/node-gyp/commit/7dd7f2b2a2)] - **test**: fix Python syntax error in test-adding.js (cclauss) [#1793](https://github.com/nodejs/node-gyp/pull/1793)
* [[`395f843de0`](https://github.com/nodejs/node-gyp/commit/395f843de0)] - **test**: replace self-signed cert with 'localhost' (Rod Vagg) [#1795](https://github.com/nodejs/node-gyp/pull/1795)
* [[`a52c6eb9e8`](https://github.com/nodejs/node-gyp/commit/a52c6eb9e8)] - **test**: migrate from tape to tap (Rod Vagg) [#1795](https://github.com/nodejs/node-gyp/pull/1795)
* [[`ec2eb44a30`](https://github.com/nodejs/node-gyp/commit/ec2eb44a30)] - **test**: use Nan in duplicate\_symbols (Gabriel Schulhof) [#1689](https://github.com/nodejs/node-gyp/pull/1689)
* [[`1597c84aad`](https://github.com/nodejs/node-gyp/commit/1597c84aad)] - **test**: use Travis CI to run tests on every pull request (cclauss) [#1752](https://github.com/nodejs/node-gyp/pull/1752)
* [[`dd9bf929ac`](https://github.com/nodejs/node-gyp/commit/dd9bf929ac)] - **zos**: update compiler options (Shuowang (Wayne) Zhang) [#1768](https://github.com/nodejs/node-gyp/pull/1768)

## v5.0.1 2019-06-20

* [[`e3861722ed`](https://github.com/nodejs/node-gyp/commit/e3861722ed)] - **doc**: document --jobs max (David Sanders) [#1770](https://github.com/nodejs/node-gyp/pull/1770)
* [[`1cfdb28886`](https://github.com/nodejs/node-gyp/commit/1cfdb28886)] - **lib**: reintroduce support for iojs file naming for releases \>= 1 && \< 4 (Samuel Attard) [#1777](https://github.com/nodejs/node-gyp/pull/1777)

## v5.0.0 2019-06-13

* [[`8a83972743`](https://github.com/nodejs/node-gyp/commit/8a83972743)] - **(SEMVER-MAJOR)** **bin**: follow XDG OS conventions for storing data (Selwyn) [#1570](https://github.com/nodejs/node-gyp/pull/1570)
* [[`9e46872ea3`](https://github.com/nodejs/node-gyp/commit/9e46872ea3)] - **bin,lib**: remove extra comments/lines/spaces (Jon Moss) [#1508](https://github.com/nodejs/node-gyp/pull/1508)
* [[`8098ebdeb4`](https://github.com/nodejs/node-gyp/commit/8098ebdeb4)] - **deps**: replace `osenv` dependency with native `os` (Selwyn)
* [[`f83b457e03`](https://github.com/nodejs/node-gyp/commit/f83b457e03)] - **deps**: bump request to 2.8.7, fixes heok/hawk issues (Rohit Hazra) [#1492](https://github.com/nodejs/node-gyp/pull/1492)
* [[`323cee7323`](https://github.com/nodejs/node-gyp/commit/323cee7323)] - **deps**: pin `request` version range (Refael Ackermann) [#1300](https://github.com/nodejs/node-gyp/pull/1300)
* [[`c515912d08`](https://github.com/nodejs/node-gyp/commit/c515912d08)] - **doc**: improve issue template (Bartosz Sosnowski) [#1618](https://github.com/nodejs/node-gyp/pull/1618)
* [[`cca2d66727`](https://github.com/nodejs/node-gyp/commit/cca2d66727)] - **doc**: python info needs own header (Taylor D. Lee) [#1245](https://github.com/nodejs/node-gyp/pull/1245)
* [[`3e64c780f5`](https://github.com/nodejs/node-gyp/commit/3e64c780f5)] - **doc**: lint README.md (Jon Moss) [#1498](https://github.com/nodejs/node-gyp/pull/1498)
* [[`a20faedc91`](https://github.com/nodejs/node-gyp/commit/a20faedc91)] - **(SEMVER-MAJOR)** **gyp**: enable MARMASM items only on new VS versions (João Reis) [#1762](https://github.com/nodejs/node-gyp/pull/1762)
* [[`721eb691cf`](https://github.com/nodejs/node-gyp/commit/721eb691cf)] - **gyp**: teach MSVS generator about MARMASM Items (Jon Kunkee) [#1679](https://github.com/nodejs/node-gyp/pull/1679)
* [[`91744bfecc`](https://github.com/nodejs/node-gyp/commit/91744bfecc)] - **gyp**: add support for Windows on Arm (Richard Townsend) [#1739](https://github.com/nodejs/node-gyp/pull/1739)
* [[`a6e0a6c7ed`](https://github.com/nodejs/node-gyp/commit/a6e0a6c7ed)] - **gyp**: move compile\_commands\_json (Paul Maréchal) [#1661](https://github.com/nodejs/node-gyp/pull/1661)
* [[`92e8b52cee`](https://github.com/nodejs/node-gyp/commit/92e8b52cee)] - **gyp**: fix target --\> self.target (cclauss)
* [[`febdfa2137`](https://github.com/nodejs/node-gyp/commit/febdfa2137)] - **gyp**: fix sntex error (cclauss) [#1333](https://github.com/nodejs/node-gyp/pull/1333)
* [[`588d333c14`](https://github.com/nodejs/node-gyp/commit/588d333c14)] - **gyp**: \_winreg module was renamed to winreg in Python 3. (Craig Rodrigues)
* [[`98226d198c`](https://github.com/nodejs/node-gyp/commit/98226d198c)] - **gyp**: replace basestring with str, but only on Python 3. (Craig Rodrigues)
* [[`7535e4478e`](https://github.com/nodejs/node-gyp/commit/7535e4478e)] - **gyp**: replace deprecated functions (Craig Rodrigues)
* [[`2040cd21cc`](https://github.com/nodejs/node-gyp/commit/2040cd21cc)] - **gyp**: use print as a function, as specified in PEP 3105. (Craig Rodrigues)
* [[`abef93ded5`](https://github.com/nodejs/node-gyp/commit/abef93ded5)] - **gyp**: get ready for python 3 (cclauss)
* [[`43031fadcb`](https://github.com/nodejs/node-gyp/commit/43031fadcb)] - **python**: clean-up detection (João Reis) [#1582](https://github.com/nodejs/node-gyp/pull/1582)
* [[`49ab79d221`](https://github.com/nodejs/node-gyp/commit/49ab79d221)] - **python**: more informative error (Refael Ackermann) [#1269](https://github.com/nodejs/node-gyp/pull/1269)
* [[`997bc3c748`](https://github.com/nodejs/node-gyp/commit/997bc3c748)] - **readme**: add ARM64 info to MSVC setup instructions (Jon Kunkee) [#1655](https://github.com/nodejs/node-gyp/pull/1655)
* [[`788e767179`](https://github.com/nodejs/node-gyp/commit/788e767179)] - **test**: remove unused variable (João Reis)
* [[`6f5a408934`](https://github.com/nodejs/node-gyp/commit/6f5a408934)] - **tools**: fix usage of inherited -fPIC and -fPIE (Jens) [#1340](https://github.com/nodejs/node-gyp/pull/1340)
* [[`0efb8fb34b`](https://github.com/nodejs/node-gyp/commit/0efb8fb34b)] - **(SEMVER-MAJOR)** **win**: support running in VS Command Prompt (João Reis) [#1762](https://github.com/nodejs/node-gyp/pull/1762)
* [[`360ddbdf3a`](https://github.com/nodejs/node-gyp/commit/360ddbdf3a)] - **(SEMVER-MAJOR)** **win**: add support for Visual Studio 2019 (João Reis) [#1762](https://github.com/nodejs/node-gyp/pull/1762)
* [[`8f43f68275`](https://github.com/nodejs/node-gyp/commit/8f43f68275)] - **(SEMVER-MAJOR)** **win**: detect all VS versions in node-gyp (João Reis) [#1762](https://github.com/nodejs/node-gyp/pull/1762)
* [[`7fe4095974`](https://github.com/nodejs/node-gyp/commit/7fe4095974)] - **(SEMVER-MAJOR)** **win**: generic Visual Studio 2017 detection (João Reis) [#1762](https://github.com/nodejs/node-gyp/pull/1762)
* [[`7a71d68bce`](https://github.com/nodejs/node-gyp/commit/7a71d68bce)] - **win**: use msbuild from the configure stage (Bartosz Sosnowski) [#1654](https://github.com/nodejs/node-gyp/pull/1654)
* [[`d3b21220a0`](https://github.com/nodejs/node-gyp/commit/d3b21220a0)] - **win**: fix delay-load hook for electron 4 (Andy Dill)
* [[`81f3a92338`](https://github.com/nodejs/node-gyp/commit/81f3a92338)] - Update list of Node.js versions to test against. (Ben Noordhuis) [#1670](https://github.com/nodejs/node-gyp/pull/1670)
* [[`4748f6ab75`](https://github.com/nodejs/node-gyp/commit/4748f6ab75)] - Remove deprecated compatibility code. (Ben Noordhuis) [#1670](https://github.com/nodejs/node-gyp/pull/1670)
* [[`45e3221fd4`](https://github.com/nodejs/node-gyp/commit/45e3221fd4)] - Remove an outdated workaround for Python 2.4 (cclauss) [#1650](https://github.com/nodejs/node-gyp/pull/1650)
* [[`721dc7d314`](https://github.com/nodejs/node-gyp/commit/721dc7d314)] - Add ARM64 to MSBuild /Platform logic (Jon Kunkee) [#1655](https://github.com/nodejs/node-gyp/pull/1655)
* [[`a5b7410497`](https://github.com/nodejs/node-gyp/commit/a5b7410497)] - Add ESLint no-unused-vars rule (Jon Moss) [#1497](https://github.com/nodejs/node-gyp/pull/1497)

## v4.0.0 2019-04-24

* [[`ceed5cbe10`](https://github.com/nodejs/node-gyp/commit/ceed5cbe10)] - **deps**: updated tar package version to 4.4.8 (Pobegaylo Maksim) [#1713](https://github.com/nodejs/node-gyp/pull/1713)
* [[`374519e066`](https://github.com/nodejs/node-gyp/commit/374519e066)] - **(SEMVER-MAJOR)** Upgrade to tar v3 (isaacs) [#1212](https://github.com/nodejs/node-gyp/pull/1212)
* [[`e6699d13cd`](https://github.com/nodejs/node-gyp/commit/e6699d13cd)] - **test**: fix addon test for Node.js 12 and V8 7.4 (Richard Lau) [#1705](https://github.com/nodejs/node-gyp/pull/1705)
* [[`0c6bf530a0`](https://github.com/nodejs/node-gyp/commit/0c6bf530a0)] - **lib**: use print() for python version detection (GreenAddress) [#1534](https://github.com/nodejs/node-gyp/pull/1534)

## v3.8.0 2018-08-09

* [[`c5929cb4fe`](https://github.com/nodejs/node-gyp/commit/c5929cb4fe)] - **doc**: update Xcode preferences tab name. (Ivan Daniluk) [#1330](https://github.com/nodejs/node-gyp/pull/1330)
* [[`8b488da8b9`](https://github.com/nodejs/node-gyp/commit/8b488da8b9)] - **doc**: update link to commit guidelines (Jonas Hermsmeier) [#1456](https://github.com/nodejs/node-gyp/pull/1456)
* [[`b4fe8c16f9`](https://github.com/nodejs/node-gyp/commit/b4fe8c16f9)] - **doc**: fix visual studio links (Bartosz Sosnowski) [#1490](https://github.com/nodejs/node-gyp/pull/1490)
* [[`536759c7e9`](https://github.com/nodejs/node-gyp/commit/536759c7e9)] - **configure**: use sys.version\_info to get python version (Yang Guo) [#1504](https://github.com/nodejs/node-gyp/pull/1504)
* [[`94c39c604e`](https://github.com/nodejs/node-gyp/commit/94c39c604e)] - **gyp**: fix ninja build failure (GYP patch) (Daniel Bevenius) [nodejs/node#12484](https://github.com/nodejs/node/pull/12484)
* [[`e8ea74e0fa`](https://github.com/nodejs/node-gyp/commit/e8ea74e0fa)] - **tools**: patch gyp to avoid xcrun errors (Ujjwal Sharma) [nodejs/node#21520](https://github.com/nodejs/node/pull/21520)
* [[`ea9aff44f2`](https://github.com/nodejs/node-gyp/commit/ea9aff44f2)] - **tools**: fix "the the" typos in comments (Masashi Hirano) [nodejs/node#20716](https://github.com/nodejs/node/pull/20716)
* [[`207e5aa4fd`](https://github.com/nodejs/node-gyp/commit/207e5aa4fd)] - **gyp**: implement LD/LDXX for ninja and FIPS (Sam Roberts)
* [[`b416c5f4b7`](https://github.com/nodejs/node-gyp/commit/b416c5f4b7)] - **gyp**: enable cctest to use objects (gyp part) (Daniel Bevenius) [nodejs/node#12450](https://github.com/nodejs/node/pull/12450)
* [[`40692d016b`](https://github.com/nodejs/node-gyp/commit/40692d016b)] - **gyp**: add compile\_commands.json gyp generator (Ben Noordhuis) [nodejs/node#12450](https://github.com/nodejs/node/pull/12450)
* [[`fc3c4e2b10`](https://github.com/nodejs/node-gyp/commit/fc3c4e2b10)] - **gyp**: float gyp patch for long filenames (Anna Henningsen) [nodejs/node#7963](https://github.com/nodejs/node/pull/7963)
* [[`8aedbfdef6`](https://github.com/nodejs/node-gyp/commit/8aedbfdef6)] - **gyp**: backport GYP fix to fix AIX shared suffix (Stewart Addison)
* [[`6cd84b84fc`](https://github.com/nodejs/node-gyp/commit/6cd84b84fc)] - **test**: formatting and minor fixes for execFileSync replacement (Rod Vagg) [#1521](https://github.com/nodejs/node-gyp/pull/1521)
* [[`60e421363f`](https://github.com/nodejs/node-gyp/commit/60e421363f)] - **test**: added test/processExecSync.js for when execFileSync is not available. (Rohit Hazra) [#1492](https://github.com/nodejs/node-gyp/pull/1492)
* [[`969447c5bd`](https://github.com/nodejs/node-gyp/commit/969447c5bd)] - **deps**: bump request to 2.8.7, fixes heok/hawk issues (Rohit Hazra) [#1492](https://github.com/nodejs/node-gyp/pull/1492)
* [[`340403ccfe`](https://github.com/nodejs/node-gyp/commit/340403ccfe)] - **win**: improve parsing of SDK version (Alessandro Vergani) [#1516](https://github.com/nodejs/node-gyp/pull/1516)

## v3.7.0 2018-06-08

* [[`84cea7b30d`](https://github.com/nodejs/node-gyp/commit/84cea7b30d)] - Remove unused gyp test scripts. (Ben Noordhuis) [#1458](https://github.com/nodejs/node-gyp/pull/1458)
* [[`0540e4ec63`](https://github.com/nodejs/node-gyp/commit/0540e4ec63)] - **gyp**: escape spaces in filenames in make generator (Jeff Senn) [#1436](https://github.com/nodejs/node-gyp/pull/1436)
* [[`88fc6fa0ec`](https://github.com/nodejs/node-gyp/commit/88fc6fa0ec)] - Drop dependency on minimatch. (Brian Woodward) [#1158](https://github.com/nodejs/node-gyp/pull/1158)
* [[`1e203c5148`](https://github.com/nodejs/node-gyp/commit/1e203c5148)] - Fix include path when pointing to Node.js source (Richard Lau) [#1055](https://github.com/nodejs/node-gyp/pull/1055)
* [[`53d8cb967c`](https://github.com/nodejs/node-gyp/commit/53d8cb967c)] - Prefix build targets with /t: on Windows (Natalie Wolfe) [#1164](https://github.com/nodejs/node-gyp/pull/1164)
* [[`53a5f8ff38`](https://github.com/nodejs/node-gyp/commit/53a5f8ff38)] - **gyp**: add support for .mm files to msvs generator (Julien Racle) [#1167](https://github.com/nodejs/node-gyp/pull/1167)
* [[`dd8561e528`](https://github.com/nodejs/node-gyp/commit/dd8561e528)] - **zos**: don't use universal-new-lines mode (John Barboza) [#1451](https://github.com/nodejs/node-gyp/pull/1451)
* [[`e5a69010ed`](https://github.com/nodejs/node-gyp/commit/e5a69010ed)] - **zos**: add search locations for libnode.x (John Barboza) [#1451](https://github.com/nodejs/node-gyp/pull/1451)
* [[`79febace53`](https://github.com/nodejs/node-gyp/commit/79febace53)] - **doc**: update macOS information in README (Josh Parnham) [#1323](https://github.com/nodejs/node-gyp/pull/1323)
* [[`9425448945`](https://github.com/nodejs/node-gyp/commit/9425448945)] - **gyp**: don't print xcodebuild not found errors (Gibson Fahnestock) [#1370](https://github.com/nodejs/node-gyp/pull/1370)
* [[`6f1286f5b2`](https://github.com/nodejs/node-gyp/commit/6f1286f5b2)] - Fix infinite install loop. (Ben Noordhuis) [#1384](https://github.com/nodejs/node-gyp/pull/1384)
* [[`2580b9139e`](https://github.com/nodejs/node-gyp/commit/2580b9139e)] - Update `--nodedir` description in README. (Ben Noordhuis) [#1372](https://github.com/nodejs/node-gyp/pull/1372)
* [[`a61360391a`](https://github.com/nodejs/node-gyp/commit/a61360391a)] - Update README with another way to install on windows (JeffAtDeere) [#1352](https://github.com/nodejs/node-gyp/pull/1352)
* [[`47496bf6dc`](https://github.com/nodejs/node-gyp/commit/47496bf6dc)] - Fix IndexError when parsing GYP files. (Ben Noordhuis) [#1267](https://github.com/nodejs/node-gyp/pull/1267)
* [[`b2024dee7b`](https://github.com/nodejs/node-gyp/commit/b2024dee7b)] - **zos**: support platform (John Barboza) [#1276](https://github.com/nodejs/node-gyp/pull/1276)
* [[`90d86512f4`](https://github.com/nodejs/node-gyp/commit/90d86512f4)] - **win**: run PS with `-NoProfile` (Refael Ackermann) [#1292](https://github.com/nodejs/node-gyp/pull/1292)
* [[`2da5f86ef7`](https://github.com/nodejs/node-gyp/commit/2da5f86ef7)] - **doc**: add github PR and Issue templates (Gibson Fahnestock) [#1228](https://github.com/nodejs/node-gyp/pull/1228)
* [[`a46a770d68`](https://github.com/nodejs/node-gyp/commit/a46a770d68)] - **doc**: update proposed DCO and CoC (Mikeal Rogers) [#1229](https://github.com/nodejs/node-gyp/pull/1229)
* [[`7e803d58e0`](https://github.com/nodejs/node-gyp/commit/7e803d58e0)] - **doc**: headerify the Install instructions (Nick Schonning) [#1225](https://github.com/nodejs/node-gyp/pull/1225)
* [[`f27599193a`](https://github.com/nodejs/node-gyp/commit/f27599193a)] - **gyp**: update xml string encoding conversion (Liu Chao) [#1203](https://github.com/nodejs/node-gyp/pull/1203)
* [[`0a07e481f7`](https://github.com/nodejs/node-gyp/commit/0a07e481f7)] - **configure**: don't set ensure if tarball is set (Gibson Fahnestock) [#1220](https://github.com/nodejs/node-gyp/pull/1220)

## v3.6.3 2018-06-08

* [[`90cd2e8da9`](https://github.com/nodejs/node-gyp/commit/90cd2e8da9)] - **gyp**: fix regex to match multi-digit versions (Jonas Hermsmeier) [#1455](https://github.com/nodejs/node-gyp/pull/1455)
* [[`7900122337`](https://github.com/nodejs/node-gyp/commit/7900122337)] - deps: pin `request` version range (Refael Ackerman) [#1300](https://github.com/nodejs/node-gyp/pull/1300)

## v3.6.2 2017-06-01

* [[`72afdd62cd`](https://github.com/nodejs/node-gyp/commit/72afdd62cd)] - **build**: rename copyNodeLib() to doBuild() (Liu Chao) [#1206](https://github.com/nodejs/node-gyp/pull/1206)
* [[`bad903ac70`](https://github.com/nodejs/node-gyp/commit/bad903ac70)] - **win**: more robust parsing of SDK version (Refael Ackermann) [#1198](https://github.com/nodejs/node-gyp/pull/1198)
* [[`241752f381`](https://github.com/nodejs/node-gyp/commit/241752f381)] - Log dist-url. (Ben Noordhuis) [#1170](https://github.com/nodejs/node-gyp/pull/1170)
* [[`386746c7d1`](https://github.com/nodejs/node-gyp/commit/386746c7d1)] - **configure**: use full path in node_lib_file GYP var (Pavel Medvedev) [#964](https://github.com/nodejs/node-gyp/pull/964)
* [[`0913b2dd99`](https://github.com/nodejs/node-gyp/commit/0913b2dd99)] - **build, win**: use target_arch to link with node.lib (Pavel Medvedev) [#964](https://github.com/nodejs/node-gyp/pull/964)
* [[`c307b302f7`](https://github.com/nodejs/node-gyp/commit/c307b302f7)] - **doc**: blorb about setting `npm_config_OPTION_NAME` (Refael Ackermann) [#1185](https://github.com/nodejs/node-gyp/pull/1185)

## v3.6.1 2017-04-30

* [[`49801716c2`](https://github.com/nodejs/node-gyp/commit/49801716c2)] - **test**: fix test-find-python on v0.10.x buildbot. (Ben Noordhuis) [#1172](https://github.com/nodejs/node-gyp/pull/1172)
* [[`a83a3801fc`](https://github.com/nodejs/node-gyp/commit/a83a3801fc)] - **test**: fix test/test-configure-python on AIX (Richard Lau) [#1131](https://github.com/nodejs/node-gyp/pull/1131)
* [[`8a767145c9`](https://github.com/nodejs/node-gyp/commit/8a767145c9)] - **gyp**: Revert quote_cmd workaround (Kunal Pathak) [#1153](https://github.com/nodejs/node-gyp/pull/1153)
* [[`c09cf7671e`](https://github.com/nodejs/node-gyp/commit/c09cf7671e)] - **doc**: add a note for using `configure` on Windows (Vse Mozhet Byt) [#1152](https://github.com/nodejs/node-gyp/pull/1152)
* [[`da9cb5f411`](https://github.com/nodejs/node-gyp/commit/da9cb5f411)] - Delete superfluous .patch files. (Ben Noordhuis) [#1122](https://github.com/nodejs/node-gyp/pull/1122)

## v3.6.0 2017-03-16

* [[`ae141e1906`](https://github.com/nodejs/node-gyp/commit/ae141e1906)] - **win**: find and setup for VS2017 (Refael Ackermann) [#1130](https://github.com/nodejs/node-gyp/pull/1130)
* [[`ec5fc36a80`](https://github.com/nodejs/node-gyp/commit/ec5fc36a80)] - Add support to build node.js with chakracore for ARM. (Kunal Pathak) [#873](https://github.com/nodejs/node-gyp/pull/873)
* [[`a04ea3051a`](https://github.com/nodejs/node-gyp/commit/a04ea3051a)] - Add support to build node.js with chakracore. (Kunal Pathak) [#873](https://github.com/nodejs/node-gyp/pull/873)
* [[`93d7fa83c8`](https://github.com/nodejs/node-gyp/commit/93d7fa83c8)] - Upgrade semver dependency. (Ben Noordhuis) [#1107](https://github.com/nodejs/node-gyp/pull/1107)
* [[`ff9a6fadfd`](https://github.com/nodejs/node-gyp/commit/ff9a6fadfd)] - Update link of gyp as Google code is shutting down (Peter Dave Hello) [#1061](https://github.com/nodejs/node-gyp/pull/1061)

## v3.5.0 2017-01-10

* [[`762d19a39e`](https://github.com/nodejs/node-gyp/commit/762d19a39e)] - \[doc\] merge History.md and CHANGELOG.md (Rod Vagg)
* [[`80fc5c3d31`](https://github.com/nodejs/node-gyp/commit/80fc5c3d31)] - Fix deprecated dependency warning (Simone Primarosa) [#1069](https://github.com/nodejs/node-gyp/pull/1069)
* [[`05c44944fd`](https://github.com/nodejs/node-gyp/commit/05c44944fd)] - Open the build file with universal-newlines mode (Guy Margalit) [#1053](https://github.com/nodejs/node-gyp/pull/1053)
* [[`37ae7be114`](https://github.com/nodejs/node-gyp/commit/37ae7be114)] - Try python launcher when stock python is python 3. (Ben Noordhuis) [#992](https://github.com/nodejs/node-gyp/pull/992)
* [[`e3778d9907`](https://github.com/nodejs/node-gyp/commit/e3778d9907)] - Add lots of findPython() tests. (Ben Noordhuis) [#992](https://github.com/nodejs/node-gyp/pull/992)
* [[`afc766adf6`](https://github.com/nodejs/node-gyp/commit/afc766adf6)] - Unset executable bit for .bat files (Pavel Medvedev) [#969](https://github.com/nodejs/node-gyp/pull/969)
* [[`ddac348991`](https://github.com/nodejs/node-gyp/commit/ddac348991)] - Use push on PYTHONPATH and add tests (Michael Hart) [#990](https://github.com/nodejs/node-gyp/pull/990)
* [[`b182a19042`](https://github.com/nodejs/node-gyp/commit/b182a19042)] - ***Revert*** "add "path-array" dep" (Michael Hart) [#990](https://github.com/nodejs/node-gyp/pull/990)
* [[`7c08b85c5a`](https://github.com/nodejs/node-gyp/commit/7c08b85c5a)] - ***Revert*** "**configure**: use "path-array" for PYTHONPATH" (Michael Hart) [#990](https://github.com/nodejs/node-gyp/pull/990)
* [[`9c8d275526`](https://github.com/nodejs/node-gyp/commit/9c8d275526)] - Add --devdir flag. (Ben Noordhuis) [#916](https://github.com/nodejs/node-gyp/pull/916)
* [[`f6eab1f9e4`](https://github.com/nodejs/node-gyp/commit/f6eab1f9e4)] - **doc**: add windows-build-tools to readme (Felix Rieseberg) [#970](https://github.com/nodejs/node-gyp/pull/970)

## v3.4.0 2016-06-28

* [[`ce5fd04e94`](https://github.com/nodejs/node-gyp/commit/ce5fd04e94)] - **deps**: update minimatch version (delphiactual) [#961](https://github.com/nodejs/node-gyp/pull/961)
* [[`77383ddd85`](https://github.com/nodejs/node-gyp/commit/77383ddd85)] - Replace fs.accessSync call to fs.statSync (Richard Lau) [#955](https://github.com/nodejs/node-gyp/pull/955)
* [[`0dba4bda57`](https://github.com/nodejs/node-gyp/commit/0dba4bda57)] - **test**: add simple addon test (Richard Lau) [#955](https://github.com/nodejs/node-gyp/pull/955)
* [[`c4344b3889`](https://github.com/nodejs/node-gyp/commit/c4344b3889)] - **doc**: add --target option to README (Gibson Fahnestock) [#958](https://github.com/nodejs/node-gyp/pull/958)
* [[`cc778e9215`](https://github.com/nodejs/node-gyp/commit/cc778e9215)] - Override BUILDING_UV_SHARED, BUILDING_V8_SHARED. (Ben Noordhuis) [#915](https://github.com/nodejs/node-gyp/pull/915)
* [[`af35b2ad32`](https://github.com/nodejs/node-gyp/commit/af35b2ad32)] - Move VC++ Build Tools to Build Tools landing page. (Andrew Pardoe) [#953](https://github.com/nodejs/node-gyp/pull/953)
* [[`f31482e226`](https://github.com/nodejs/node-gyp/commit/f31482e226)] - **win**: work around __pfnDliNotifyHook2 type change (Alexis Campailla) [#952](https://github.com/nodejs/node-gyp/pull/952)
* [[`3df8222fa5`](https://github.com/nodejs/node-gyp/commit/3df8222fa5)] - Allow for npmlog@3.x (Rebecca Turner) [#950](https://github.com/nodejs/node-gyp/pull/950)
* [[`a4fa07b390`](https://github.com/nodejs/node-gyp/commit/a4fa07b390)] - More verbose error on locating msbuild.exe failure. (Mateusz Jaworski) [#930](https://github.com/nodejs/node-gyp/pull/930)
* [[`4ee31329e0`](https://github.com/nodejs/node-gyp/commit/4ee31329e0)] - **doc**: add command options to README.md (Gibson Fahnestock) [#937](https://github.com/nodejs/node-gyp/pull/937)
* [[`c8c7ca86b9`](https://github.com/nodejs/node-gyp/commit/c8c7ca86b9)] - Add --silent option for zero output. (Gibson Fahnestock) [#937](https://github.com/nodejs/node-gyp/pull/937)
* [[`ac29d23a7c`](https://github.com/nodejs/node-gyp/commit/ac29d23a7c)] - Upgrade to glob@7.0.3. (Ben Noordhuis) [#943](https://github.com/nodejs/node-gyp/pull/943)
* [[`15fd56be3d`](https://github.com/nodejs/node-gyp/commit/15fd56be3d)] - Enable V8 deprecation warnings for native modules (Matt Loring) [#920](https://github.com/nodejs/node-gyp/pull/920)
* [[`7f1c1b960c`](https://github.com/nodejs/node-gyp/commit/7f1c1b960c)] - **gyp**: improvements for android generator (Robert Chiras) [#935](https://github.com/nodejs/node-gyp/pull/935)
* [[`088082766c`](https://github.com/nodejs/node-gyp/commit/088082766c)] - Update Windows install instructions (Sara Itani) [#867](https://github.com/nodejs/node-gyp/pull/867)
* [[`625c1515f9`](https://github.com/nodejs/node-gyp/commit/625c1515f9)] - **gyp**: inherit CC/CXX for CC/CXX.host (Johan Bergström) [#908](https://github.com/nodejs/node-gyp/pull/908)
* [[`3bcb1720e4`](https://github.com/nodejs/node-gyp/commit/3bcb1720e4)] - Add support for the Python launcher on Windows (Patrick Westerhoff) [#894](https://github.com/nodejs/node-gyp/pull/894

## v3.3.1 2016-03-04

* [[`a981ef847a`](https://github.com/nodejs/node-gyp/commit/a981ef847a)] - **gyp**: fix android generator (Robert Chiras) [#889](https://github.com/nodejs/node-gyp/pull/889)

## v3.3.0 2016-02-16

* [[`818d854a4d`](https://github.com/nodejs/node-gyp/commit/818d854a4d)] - Introduce NODEJS_ORG_MIRROR and IOJS_ORG_MIRROR (Rod Vagg) [#878](https://github.com/nodejs/node-gyp/pull/878)
* [[`d1e4cc4b62`](https://github.com/nodejs/node-gyp/commit/d1e4cc4b62)] - **(SEMVER-MINOR)** Download headers tarball for ~0.12.10 || ~0.10.42 (Rod Vagg) [#877](https://github.com/nodejs/node-gyp/pull/877)
* [[`6e28ad1bea`](https://github.com/nodejs/node-gyp/commit/6e28ad1bea)] - Allow for npmlog@2.x (Rebecca Turner) [#861](https://github.com/nodejs/node-gyp/pull/861)
* [[`07371e5812`](https://github.com/nodejs/node-gyp/commit/07371e5812)] - Use -fPIC for NetBSD. (Marcin Cieślak) [#856](https://github.com/nodejs/node-gyp/pull/856)
* [[`8c4b0ffa50`](https://github.com/nodejs/node-gyp/commit/8c4b0ffa50)] - **(SEMVER-MINOR)** Add --cafile command line option. (Ben Noordhuis) [#837](https://github.com/nodejs/node-gyp/pull/837)
* [[`b3ad43498e`](https://github.com/nodejs/node-gyp/commit/b3ad43498e)] - **(SEMVER-MINOR)** Make download() function testable. (Ben Noordhuis) [#837](https://github.com/nodejs/node-gyp/pull/837)

## v3.2.1 2015-12-03

* [[`ab89b477c4`](https://github.com/nodejs/node-gyp/commit/ab89b477c4)] - Upgrade gyp to b3cef02. (Ben Noordhuis) [#831](https://github.com/nodejs/node-gyp/pull/831)
* [[`90078ecb17`](https://github.com/nodejs/node-gyp/commit/90078ecb17)] - Define WIN32_LEAN_AND_MEAN conditionally. (Ben Noordhuis) [#824](https://github.com/nodejs/node-gyp/pull/824)

## v3.2.0 2015-11-25

* [[`268f1ca4c7`](https://github.com/nodejs/node-gyp/commit/268f1ca4c7)] - Use result of `which` when searching for python. (Refael Ackermann) [#668](https://github.com/nodejs/node-gyp/pull/668)
* [[`817ed9bd78`](https://github.com/nodejs/node-gyp/commit/817ed9bd78)] - Add test for python executable search logic. (Ben Noordhuis) [#756](https://github.com/nodejs/node-gyp/pull/756)
* [[`0e2dfda1f3`](https://github.com/nodejs/node-gyp/commit/0e2dfda1f3)] - Fix test/test-options when run through `npm test`. (Ben Noordhuis) [#755](https://github.com/nodejs/node-gyp/pull/755)
* [[`9bfa0876b4`](https://github.com/nodejs/node-gyp/commit/9bfa0876b4)] - Add support for AIX (Michael Dawson) [#753](https://github.com/nodejs/node-gyp/pull/753)
* [[`a8d441a0a2`](https://github.com/nodejs/node-gyp/commit/a8d441a0a2)] - Update README for Windows 10 support. (Jason Williams) [#766](https://github.com/nodejs/node-gyp/pull/766)
* [[`d1d6015276`](https://github.com/nodejs/node-gyp/commit/d1d6015276)] - Update broken links and switch to HTTPS. (andrew morton)

## v3.1.0 2015-11-14

* [[`9049241f91`](https://github.com/nodejs/node-gyp/commit/9049241f91)] - **gyp**: don't use links at all, just copy the files instead (Nathan Zadoks)
* [[`8ef90348d1`](https://github.com/nodejs/node-gyp/commit/8ef90348d1)] - **gyp**: apply https://codereview.chromium.org/11361103/ (Nathan Rajlich)
* [[`a2ed0df84e`](https://github.com/nodejs/node-gyp/commit/a2ed0df84e)] - **gyp**: always install into $PRODUCT_DIR (Nathan Rajlich)
* [[`cc8b2fa83e`](https://github.com/nodejs/node-gyp/commit/cc8b2fa83e)] - Update gyp to b3cef02. (Imran Iqbal) [#781](https://github.com/nodejs/node-gyp/pull/781)
* [[`f5d86eb84e`](https://github.com/nodejs/node-gyp/commit/f5d86eb84e)] - Update to tar@2.0.0. (Edgar Muentes) [#797](https://github.com/nodejs/node-gyp/pull/797)
* [[`2ac7de02c4`](https://github.com/nodejs/node-gyp/commit/2ac7de02c4)] - Fix infinite loop with zero-length options. (Ben Noordhuis) [#745](https://github.com/nodejs/node-gyp/pull/745)
* [[`101bed639b`](https://github.com/nodejs/node-gyp/commit/101bed639b)] - This platform value came from debian package, and now the value (Jérémy Lal) [#738](https://github.com/nodejs/node-gyp/pull/738)

## v3.0.3 2015-09-14

* [[`ad827cda30`](https://github.com/nodejs/node-gyp/commit/ad827cda30)] - tarballUrl global and && when checking for iojs (Lars-Magnus Skog) [#729](https://github.com/nodejs/node-gyp/pull/729)

## v3.0.2 2015-09-12

* [[`6e8c3bf3c6`](https://github.com/nodejs/node-gyp/commit/6e8c3bf3c6)] - add back support for passing additional cmdline args (Rod Vagg) [#723](https://github.com/nodejs/node-gyp/pull/723)
* [[`ff82f2f3b9`](https://github.com/nodejs/node-gyp/commit/ff82f2f3b9)] - fixed broken link in docs to Visual Studio 2013 download (simon-p-r) [#722](https://github.com/nodejs/node-gyp/pull/722)

## v3.0.1 2015-09-08

* [[`846337e36b`](https://github.com/nodejs/node-gyp/commit/846337e36b)] - normalise versions for target == this comparison (Rod Vagg) [#716](https://github.com/nodejs/node-gyp/pull/716)

## v3.0.0 2015-09-08

* [[`9720d0373c`](https://github.com/nodejs/node-gyp/commit/9720d0373c)] - remove node_modules from tree (Rod Vagg) [#711](https://github.com/nodejs/node-gyp/pull/711)
* [[`6dcf220db7`](https://github.com/nodejs/node-gyp/commit/6dcf220db7)] - test version major directly, don't use semver.satisfies() (Rod Vagg) [#711](https://github.com/nodejs/node-gyp/pull/711)
* [[`938dd18d1c`](https://github.com/nodejs/node-gyp/commit/938dd18d1c)] - refactor for clarity, fix dist-url, add env var dist-url functionality (Rod Vagg) [#711](https://github.com/nodejs/node-gyp/pull/711)
* [[`9e9df66a06`](https://github.com/nodejs/node-gyp/commit/9e9df66a06)] - use process.release, make aware of io.js & node v4 differences (Rod Vagg) [#711](https://github.com/nodejs/node-gyp/pull/711)
* [[`1ea7ed01f4`](https://github.com/nodejs/node-gyp/commit/1ea7ed01f4)] - **deps**: update graceful-fs dependency to the latest (Sakthipriyan Vairamani) [#714](https://github.com/nodejs/node-gyp/pull/714)
* [[`0fbc387b35`](https://github.com/nodejs/node-gyp/commit/0fbc387b35)] - Update repository URLs. (Ben Noordhuis) [#715](https://github.com/nodejs/node-gyp/pull/715)
* [[`bbedb8868b`](https://github.com/nodejs/node-gyp/commit/bbedb8868b)] - **(SEMVER-MAJOR)** **win**: enable delay-load hook by default (Jeremiah Senkpiel) [#708](https://github.com/nodejs/node-gyp/pull/708)
* [[`85ed107565`](https://github.com/nodejs/node-gyp/commit/85ed107565)] - Merge pull request #664 from othiym23/othiym23/allow-semver-5 (Nathan Rajlich)
* [[`0c720d234c`](https://github.com/nodejs/node-gyp/commit/0c720d234c)] - allow semver@5 (Forrest L Norvell)

## 2.0.2 / 2015-07-14

  * Use HTTPS for dist url (#656, @SonicHedgehog)
  * Merge pull request #648 from nevosegal/master
  * Merge pull request #650 from magic890/patch-1
  * Updated Installation section on README
  * Updated link to gyp user documentation
  * Fix download error message spelling (#643, @tomxtobin)
  * Merge pull request #637 from lygstate/master
  * Set NODE_GYP_DIR for addon.gypi to setting absolute path for
    src/win_delay_load_hook.c, and fixes of the long relative path issue on Win32.
    Fixes #636 (#637, @lygstate).

## 2.0.1 / 2015-05-28

  * configure: try/catch the semver range.test() call
  * README: update for visual studio 2013 (#510, @samccone)

## 2.0.0 / 2015-05-24

  * configure: check for python2 executable by default, fallback to python
  * configure: don't clobber existing $PYTHONPATH
  * configure: use "path-array" for PYTHONPATH
  * gyp: fix for non-acsii userprofile name on Windows
  * gyp: always install into $PRODUCT_DIR
  * gyp: apply https://codereview.chromium.org/11361103/
  * gyp: don't use links at all, just copy the files instead
  * gyp: update gyp to e1c8fcf7
  * Updated README.md with updated Windows build info
  * Show URL when a download fails
  * package: add a "license" field
  * move HMODULE m declaration to top
  * Only add "-undefined dynamic_lookup" to loadable_module targets
  * win: optionally allow node.exe/iojs.exe to be renamed
  * Avoid downloading shasums if using tarPath
  * Add target name preprocessor define: `NODE_GYP_MODULE_NAME`
  * Show better error message in case of bad network settings
PK~\BC&validate-npm-package-name/package.jsonnu[{
  "_id": "validate-npm-package-name@5.0.1",
  "_inBundle": true,
  "_location": "/npm/validate-npm-package-name",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm",
    "/npm/init-package-json",
    "/npm/npm-package-arg"
  ],
  "author": {
    "name": "GitHub Inc."
  },
  "bugs": {
    "url": "https://github.com/npm/validate-npm-package-name/issues"
  },
  "description": "Give me a string and I'll tell you if it's a valid npm package name",
  "devDependencies": {
    "@npmcli/eslint-config": "^4.0.0",
    "@npmcli/template-oss": "4.22.0",
    "tap": "^16.0.1"
  },
  "directories": {
    "test": "test"
  },
  "engines": {
    "node": "^14.17.0 || ^16.13.0 || >=18.0.0"
  },
  "files": [
    "bin/",
    "lib/"
  ],
  "homepage": "https://github.com/npm/validate-npm-package-name",
  "keywords": [
    "npm",
    "package",
    "names",
    "validation"
  ],
  "license": "ISC",
  "main": "lib/",
  "name": "validate-npm-package-name",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/validate-npm-package-name.git"
  },
  "scripts": {
    "cov:test": "TAP_FLAGS='--cov' npm run test:code",
    "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"",
    "lintfix": "npm run lint -- --fix",
    "postlint": "template-oss-check",
    "posttest": "npm run lint",
    "snap": "tap",
    "template-oss-apply": "template-oss-apply --force",
    "test": "tap",
    "test:code": "tap ${TAP_FLAGS:-'--'} test/*.js",
    "test:style": "standard"
  },
  "tap": {
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.22.0",
    "publish": true
  },
  "version": "5.0.1"
}
PK~\!

&validate-npm-package-name/lib/index.jsnu['use strict'
const { builtinModules: builtins } = require('module')

var scopedPackagePattern = new RegExp('^(?:@([^/]+?)[/])?([^/]+?)$')
var blacklist = [
  'node_modules',
  'favicon.ico',
]

function validate (name) {
  var warnings = []
  var errors = []

  if (name === null) {
    errors.push('name cannot be null')
    return done(warnings, errors)
  }

  if (name === undefined) {
    errors.push('name cannot be undefined')
    return done(warnings, errors)
  }

  if (typeof name !== 'string') {
    errors.push('name must be a string')
    return done(warnings, errors)
  }

  if (!name.length) {
    errors.push('name length must be greater than zero')
  }

  if (name.match(/^\./)) {
    errors.push('name cannot start with a period')
  }

  if (name.match(/^_/)) {
    errors.push('name cannot start with an underscore')
  }

  if (name.trim() !== name) {
    errors.push('name cannot contain leading or trailing spaces')
  }

  // No funny business
  blacklist.forEach(function (blacklistedName) {
    if (name.toLowerCase() === blacklistedName) {
      errors.push(blacklistedName + ' is a blacklisted name')
    }
  })

  // Generate warnings for stuff that used to be allowed

  // core module names like http, events, util, etc
  if (builtins.includes(name.toLowerCase())) {
    warnings.push(name + ' is a core module name')
  }

  if (name.length > 214) {
    warnings.push('name can no longer contain more than 214 characters')
  }

  // mIxeD CaSe nAMEs
  if (name.toLowerCase() !== name) {
    warnings.push('name can no longer contain capital letters')
  }

  if (/[~'!()*]/.test(name.split('/').slice(-1)[0])) {
    warnings.push('name can no longer contain special characters ("~\'!()*")')
  }

  if (encodeURIComponent(name) !== name) {
    // Maybe it's a scoped package name, like @user/package
    var nameMatch = name.match(scopedPackagePattern)
    if (nameMatch) {
      var user = nameMatch[1]
      var pkg = nameMatch[2]
      if (encodeURIComponent(user) === user && encodeURIComponent(pkg) === pkg) {
        return done(warnings, errors)
      }
    }

    errors.push('name can only contain URL-friendly characters')
  }

  return done(warnings, errors)
}

var done = function (warnings, errors) {
  var result = {
    validForNewPackages: errors.length === 0 && warnings.length === 0,
    validForOldPackages: errors.length === 0,
    warnings: warnings,
    errors: errors,
  }
  if (!result.warnings.length) {
    delete result.warnings
  }
  if (!result.errors.length) {
    delete result.errors
  }
  return result
}

module.exports = validate
PK~\q6!validate-npm-package-name/LICENSEnu[Copyright (c) 2015, npm, Inc


Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
PK~\*json-parse-even-better-errors/package.jsonnu[{
  "_id": "json-parse-even-better-errors@3.0.2",
  "_inBundle": true,
  "_location": "/npm/json-parse-even-better-errors",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm",
    "/npm/@npmcli/arborist",
    "/npm/@npmcli/metavuln-calculator",
    "/npm/@npmcli/package-json",
    "/npm/libnpmversion",
    "/npm/parse-conflict-json",
    "/npm/read-package-json-fast"
  ],
  "author": {
    "name": "GitHub Inc."
  },
  "bugs": {
    "url": "https://github.com/npm/json-parse-even-better-errors/issues"
  },
  "description": "JSON.parse with context information on error",
  "devDependencies": {
    "@npmcli/eslint-config": "^4.0.0",
    "@npmcli/template-oss": "4.22.0",
    "tap": "^16.3.0"
  },
  "engines": {
    "node": "^14.17.0 || ^16.13.0 || >=18.0.0"
  },
  "files": [
    "bin/",
    "lib/"
  ],
  "homepage": "https://github.com/npm/json-parse-even-better-errors#readme",
  "keywords": [
    "JSON",
    "parser"
  ],
  "license": "MIT",
  "main": "lib/index.js",
  "name": "json-parse-even-better-errors",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/json-parse-even-better-errors.git"
  },
  "scripts": {
    "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"",
    "lintfix": "npm run lint -- --fix",
    "postlint": "template-oss-check",
    "posttest": "npm run lint",
    "snap": "tap",
    "template-oss-apply": "template-oss-apply --force",
    "test": "tap"
  },
  "tap": {
    "check-coverage": true,
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.22.0",
    "publish": true
  },
  "version": "3.0.2"
}
PK~\TGG*json-parse-even-better-errors/lib/index.jsnu['use strict'

const INDENT = Symbol.for('indent')
const NEWLINE = Symbol.for('newline')

const DEFAULT_NEWLINE = '\n'
const DEFAULT_INDENT = '  '
const BOM = /^\uFEFF/

// only respect indentation if we got a line break, otherwise squash it
// things other than objects and arrays aren't indented, so ignore those
// Important: in both of these regexps, the $1 capture group is the newline
// or undefined, and the $2 capture group is the indent, or undefined.
const FORMAT = /^\s*[{[]((?:\r?\n)+)([\s\t]*)/
const EMPTY = /^(?:\{\}|\[\])((?:\r?\n)+)?$/

// Node 20 puts single quotes around the token and a comma after it
const UNEXPECTED_TOKEN = /^Unexpected token '?(.)'?(,)? /i

const hexify = (char) => {
  const h = char.charCodeAt(0).toString(16).toUpperCase()
  return `0x${h.length % 2 ? '0' : ''}${h}`
}

// Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
// because the buffer-to-string conversion in `fs.readFileSync()`
// translates it to FEFF, the UTF-16 BOM.
const stripBOM = (txt) => String(txt).replace(BOM, '')

const makeParsedError = (msg, parsing, position = 0) => ({
  message: `${msg} while parsing ${parsing}`,
  position,
})

const parseError = (e, txt, context = 20) => {
  let msg = e.message

  if (!txt) {
    return makeParsedError(msg, 'empty string')
  }

  const badTokenMatch = msg.match(UNEXPECTED_TOKEN)
  const badIndexMatch = msg.match(/ position\s+(\d+)/i)

  if (badTokenMatch) {
    msg = msg.replace(
      UNEXPECTED_TOKEN,
      `Unexpected token ${JSON.stringify(badTokenMatch[1])} (${hexify(badTokenMatch[1])})$2 `
    )
  }

  let errIdx
  if (badIndexMatch) {
    errIdx = +badIndexMatch[1]
  } else /* istanbul ignore next - doesnt happen in Node 22 */ if (
    msg.match(/^Unexpected end of JSON.*/i)
  ) {
    errIdx = txt.length - 1
  }

  if (errIdx == null) {
    return makeParsedError(msg, `'${txt.slice(0, context * 2)}'`)
  }

  const start = errIdx <= context ? 0 : errIdx - context
  const end = errIdx + context >= txt.length ? txt.length : errIdx + context
  const slice = `${start ? '...' : ''}${txt.slice(start, end)}${end === txt.length ? '' : '...'}`

  return makeParsedError(
    msg,
    `${txt === slice ? '' : 'near '}${JSON.stringify(slice)}`,
    errIdx
  )
}

class JSONParseError extends SyntaxError {
  constructor (er, txt, context, caller) {
    const metadata = parseError(er, txt, context)
    super(metadata.message)
    Object.assign(this, metadata)
    this.code = 'EJSONPARSE'
    this.systemError = er
    Error.captureStackTrace(this, caller || this.constructor)
  }

  get name () {
    return this.constructor.name
  }

  set name (n) {}

  get [Symbol.toStringTag] () {
    return this.constructor.name
  }
}

const parseJson = (txt, reviver) => {
  const result = JSON.parse(txt, reviver)
  if (result && typeof result === 'object') {
    // get the indentation so that we can save it back nicely
    // if the file starts with {" then we have an indent of '', ie, none
    // otherwise, pick the indentation of the next line after the first \n If the
    // pattern doesn't match, then it means no indentation. JSON.stringify ignores
    // symbols, so this is reasonably safe. if the string is '{}' or '[]', then
    // use the default 2-space indent.
    const match = txt.match(EMPTY) || txt.match(FORMAT) || [null, '', '']
    result[NEWLINE] = match[1] ?? DEFAULT_NEWLINE
    result[INDENT] = match[2] ?? DEFAULT_INDENT
  }
  return result
}

const parseJsonError = (raw, reviver, context) => {
  const txt = stripBOM(raw)
  try {
    return parseJson(txt, reviver)
  } catch (e) {
    if (typeof raw !== 'string' && !Buffer.isBuffer(raw)) {
      const msg = Array.isArray(raw) && raw.length === 0 ? 'an empty array' : String(raw)
      throw Object.assign(
        new TypeError(`Cannot parse ${msg}`),
        { code: 'EJSONPARSE', systemError: e }
      )
    }
    throw new JSONParseError(e, txt, context, parseJsonError)
  }
}

module.exports = parseJsonError
parseJsonError.JSONParseError = JSONParseError
parseJsonError.noExceptions = (raw, reviver) => {
  try {
    return parseJson(stripBOM(raw), reviver)
  } catch {
    // no exceptions
  }
}
PK~\/}(json-parse-even-better-errors/LICENSE.mdnu[Copyright 2017 Kat Marchán
Copyright npm, Inc.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

---

This library is a fork of 'better-json-errors' by Kat Marchán, extended and
distributed under the terms of the MIT license above.
PK~\c2GGini/package.jsonnu[{
  "_id": "ini@4.1.3",
  "_inBundle": true,
  "_location": "/npm/ini",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm",
    "/npm/@npmcli/config"
  ],
  "author": {
    "name": "GitHub Inc."
  },
  "bugs": {
    "url": "https://github.com/npm/ini/issues"
  },
  "description": "An ini encoder/decoder for node",
  "devDependencies": {
    "@npmcli/eslint-config": "^4.0.0",
    "@npmcli/template-oss": "4.22.0",
    "tap": "^16.0.1"
  },
  "engines": {
    "node": "^14.17.0 || ^16.13.0 || >=18.0.0"
  },
  "files": [
    "bin/",
    "lib/"
  ],
  "homepage": "https://github.com/npm/ini#readme",
  "license": "ISC",
  "main": "lib/ini.js",
  "name": "ini",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/ini.git"
  },
  "scripts": {
    "eslint": "eslint",
    "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"",
    "lintfix": "npm run lint -- --fix",
    "postlint": "template-oss-check",
    "posttest": "npm run lint",
    "snap": "tap",
    "template-oss-apply": "template-oss-apply --force",
    "test": "tap"
  },
  "tap": {
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.22.0",
    "publish": "true"
  },
  "version": "4.1.3"
}
PK~\bWini/lib/ini.jsnu[const { hasOwnProperty } = Object.prototype

const encode = (obj, opt = {}) => {
  if (typeof opt === 'string') {
    opt = { section: opt }
  }
  opt.align = opt.align === true
  opt.newline = opt.newline === true
  opt.sort = opt.sort === true
  opt.whitespace = opt.whitespace === true || opt.align === true
  // The `typeof` check is required because accessing the `process` directly fails on browsers.
  /* istanbul ignore next */
  opt.platform = opt.platform || (typeof process !== 'undefined' && process.platform)
  opt.bracketedArray = opt.bracketedArray !== false

  /* istanbul ignore next */
  const eol = opt.platform === 'win32' ? '\r\n' : '\n'
  const separator = opt.whitespace ? ' = ' : '='
  const children = []

  const keys = opt.sort ? Object.keys(obj).sort() : Object.keys(obj)

  let padToChars = 0
  // If aligning on the separator, then padToChars is determined as follows:
  // 1. Get the keys
  // 2. Exclude keys pointing to objects unless the value is null or an array
  // 3. Add `[]` to array keys
  // 4. Ensure non empty set of keys
  // 5. Reduce the set to the longest `safe` key
  // 6. Get the `safe` length
  if (opt.align) {
    padToChars = safe(
      (
        keys
          .filter(k => obj[k] === null || Array.isArray(obj[k]) || typeof obj[k] !== 'object')
          .map(k => Array.isArray(obj[k]) ? `${k}[]` : k)
      )
        .concat([''])
        .reduce((a, b) => safe(a).length >= safe(b).length ? a : b)
    ).length
  }

  let out = ''
  const arraySuffix = opt.bracketedArray ? '[]' : ''

  for (const k of keys) {
    const val = obj[k]
    if (val && Array.isArray(val)) {
      for (const item of val) {
        out += safe(`${k}${arraySuffix}`).padEnd(padToChars, ' ') + separator + safe(item) + eol
      }
    } else if (val && typeof val === 'object') {
      children.push(k)
    } else {
      out += safe(k).padEnd(padToChars, ' ') + separator + safe(val) + eol
    }
  }

  if (opt.section && out.length) {
    out = '[' + safe(opt.section) + ']' + (opt.newline ? eol + eol : eol) + out
  }

  for (const k of children) {
    const nk = splitSections(k, '.').join('\\.')
    const section = (opt.section ? opt.section + '.' : '') + nk
    const child = encode(obj[k], {
      ...opt,
      section,
    })
    if (out.length && child.length) {
      out += eol
    }

    out += child
  }

  return out
}

function splitSections (str, separator) {
  var lastMatchIndex = 0
  var lastSeparatorIndex = 0
  var nextIndex = 0
  var sections = []

  do {
    nextIndex = str.indexOf(separator, lastMatchIndex)

    if (nextIndex !== -1) {
      lastMatchIndex = nextIndex + separator.length

      if (nextIndex > 0 && str[nextIndex - 1] === '\\') {
        continue
      }

      sections.push(str.slice(lastSeparatorIndex, nextIndex))
      lastSeparatorIndex = nextIndex + separator.length
    }
  } while (nextIndex !== -1)

  sections.push(str.slice(lastSeparatorIndex))

  return sections
}

const decode = (str, opt = {}) => {
  opt.bracketedArray = opt.bracketedArray !== false
  const out = Object.create(null)
  let p = out
  let section = null
  //          section          |key      = value
  const re = /^\[([^\]]*)\]\s*$|^([^=]+)(=(.*))?$/i
  const lines = str.split(/[\r\n]+/g)
  const duplicates = {}

  for (const line of lines) {
    if (!line || line.match(/^\s*[;#]/) || line.match(/^\s*$/)) {
      continue
    }
    const match = line.match(re)
    if (!match) {
      continue
    }
    if (match[1] !== undefined) {
      section = unsafe(match[1])
      if (section === '__proto__') {
        // not allowed
        // keep parsing the section, but don't attach it.
        p = Object.create(null)
        continue
      }
      p = out[section] = out[section] || Object.create(null)
      continue
    }
    const keyRaw = unsafe(match[2])
    let isArray
    if (opt.bracketedArray) {
      isArray = keyRaw.length > 2 && keyRaw.slice(-2) === '[]'
    } else {
      duplicates[keyRaw] = (duplicates?.[keyRaw] || 0) + 1
      isArray = duplicates[keyRaw] > 1
    }
    const key = isArray && keyRaw.endsWith('[]')
      ? keyRaw.slice(0, -2) : keyRaw

    if (key === '__proto__') {
      continue
    }
    const valueRaw = match[3] ? unsafe(match[4]) : true
    const value = valueRaw === 'true' ||
      valueRaw === 'false' ||
      valueRaw === 'null' ? JSON.parse(valueRaw)
      : valueRaw

    // Convert keys with '[]' suffix to an array
    if (isArray) {
      if (!hasOwnProperty.call(p, key)) {
        p[key] = []
      } else if (!Array.isArray(p[key])) {
        p[key] = [p[key]]
      }
    }

    // safeguard against resetting a previously defined
    // array by accidentally forgetting the brackets
    if (Array.isArray(p[key])) {
      p[key].push(value)
    } else {
      p[key] = value
    }
  }

  // {a:{y:1},"a.b":{x:2}} --> {a:{y:1,b:{x:2}}}
  // use a filter to return the keys that have to be deleted.
  const remove = []
  for (const k of Object.keys(out)) {
    if (!hasOwnProperty.call(out, k) ||
      typeof out[k] !== 'object' ||
      Array.isArray(out[k])) {
      continue
    }

    // see if the parent section is also an object.
    // if so, add it to that, and mark this one for deletion
    const parts = splitSections(k, '.')
    p = out
    const l = parts.pop()
    const nl = l.replace(/\\\./g, '.')
    for (const part of parts) {
      if (part === '__proto__') {
        continue
      }
      if (!hasOwnProperty.call(p, part) || typeof p[part] !== 'object') {
        p[part] = Object.create(null)
      }
      p = p[part]
    }
    if (p === out && nl === l) {
      continue
    }

    p[nl] = out[k]
    remove.push(k)
  }
  for (const del of remove) {
    delete out[del]
  }

  return out
}

const isQuoted = val => {
  return (val.startsWith('"') && val.endsWith('"')) ||
    (val.startsWith("'") && val.endsWith("'"))
}

const safe = val => {
  if (
    typeof val !== 'string' ||
    val.match(/[=\r\n]/) ||
    val.match(/^\[/) ||
    (val.length > 1 && isQuoted(val)) ||
    val !== val.trim()
  ) {
    return JSON.stringify(val)
  }
  return val.split(';').join('\\;').split('#').join('\\#')
}

const unsafe = val => {
  val = (val || '').trim()
  if (isQuoted(val)) {
    // remove the single quotes before calling JSON.parse
    if (val.charAt(0) === "'") {
      val = val.slice(1, -1)
    }
    try {
      val = JSON.parse(val)
    } catch {
      // ignore errors
    }
  } else {
    // walk the val to find the first not-escaped ; character
    let esc = false
    let unesc = ''
    for (let i = 0, l = val.length; i < l; i++) {
      const c = val.charAt(i)
      if (esc) {
        if ('\\;#'.indexOf(c) !== -1) {
          unesc += c
        } else {
          unesc += '\\' + c
        }

        esc = false
      } else if (';#'.indexOf(c) !== -1) {
        break
      } else if (c === '\\') {
        esc = true
      } else {
        unesc += c
      }
    }
    if (esc) {
      unesc += '\\'
    }

    return unesc.trim()
  }
  return val
}

module.exports = {
  parse: decode,
  decode,
  stringify: encode,
  encode,
  safe,
  unsafe,
}
PK~\aGWini/LICENSEnu[The ISC License

Copyright (c) Isaac Z. Schlueter and Contributors

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
PK~\IiD#normalize-package-data/package.jsonnu[{
  "_id": "normalize-package-data@6.0.1",
  "_inBundle": true,
  "_location": "/npm/normalize-package-data",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm",
    "/npm/@npmcli/package-json",
    "/npm/libnpmpublish"
  ],
  "author": {
    "name": "GitHub Inc."
  },
  "bugs": {
    "url": "https://github.com/npm/normalize-package-data/issues"
  },
  "dependencies": {
    "hosted-git-info": "^7.0.0",
    "is-core-module": "^2.8.1",
    "semver": "^7.3.5",
    "validate-npm-package-license": "^3.0.4"
  },
  "description": "Normalizes data that can be found in package.json files.",
  "devDependencies": {
    "@npmcli/eslint-config": "^4.0.0",
    "@npmcli/template-oss": "4.22.0",
    "tap": "^16.0.1"
  },
  "engines": {
    "node": "^16.14.0 || >=18.0.0"
  },
  "files": [
    "bin/",
    "lib/"
  ],
  "homepage": "https://github.com/npm/normalize-package-data#readme",
  "license": "BSD-2-Clause",
  "main": "lib/normalize.js",
  "name": "normalize-package-data",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/normalize-package-data.git"
  },
  "scripts": {
    "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"",
    "lintfix": "npm run lint -- --fix",
    "npmclilint": "npmcli-lint",
    "postlint": "template-oss-check",
    "postsnap": "npm run lintfix --",
    "posttest": "npm run lint",
    "snap": "tap",
    "template-oss-apply": "template-oss-apply --force",
    "test": "tap"
  },
  "tap": {
    "branches": 86,
    "functions": 92,
    "lines": 86,
    "statements": 86,
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.22.0",
    "publish": "true"
  },
  "version": "6.0.1"
}
PK~\hUl0normalize-package-data/lib/warning_messages.jsonnu[{
  "repositories": "'repositories' (plural) Not supported. Please pick one as the 'repository' field"
  ,"missingRepository": "No repository field."
  ,"brokenGitUrl": "Probably broken git url: %s"
  ,"nonObjectScripts": "scripts must be an object"
  ,"nonStringScript": "script values must be string commands"
  ,"nonArrayFiles": "Invalid 'files' member"
  ,"invalidFilename": "Invalid filename in 'files' list: %s"
  ,"nonArrayBundleDependencies": "Invalid 'bundleDependencies' list. Must be array of package names"
  ,"nonStringBundleDependency": "Invalid bundleDependencies member: %s"
  ,"nonDependencyBundleDependency": "Non-dependency in bundleDependencies: %s"
  ,"nonObjectDependencies": "%s field must be an object"
  ,"nonStringDependency": "Invalid dependency: %s %s"
  ,"deprecatedArrayDependencies": "specifying %s as array is deprecated"
  ,"deprecatedModules": "modules field is deprecated"
  ,"nonArrayKeywords": "keywords should be an array of strings"
  ,"nonStringKeyword": "keywords should be an array of strings"
  ,"conflictingName": "%s is also the name of a node core module."
  ,"nonStringDescription": "'description' field should be a string"
  ,"missingDescription": "No description"
  ,"missingReadme": "No README data"
  ,"missingLicense": "No license field."
  ,"nonEmailUrlBugsString": "Bug string field must be url, email, or {email,url}"
  ,"nonUrlBugsUrlField": "bugs.url field must be a string url. Deleted."
  ,"nonEmailBugsEmailField": "bugs.email field must be a string email. Deleted."
  ,"emptyNormalizedBugs": "Normalized value of bugs field is an empty object. Deleted."
  ,"nonUrlHomepage": "homepage field must be a string url. Deleted."
  ,"invalidLicense": "license should be a valid SPDX license expression"
  ,"typo": "%s should probably be %s."
}
PK~\}U*normalize-package-data/lib/make_warning.jsnu[var util = require('util')
var messages = require('./warning_messages.json')

module.exports = function () {
  var args = Array.prototype.slice.call(arguments, 0)
  var warningName = args.shift()
  if (warningName === 'typo') {
    return makeTypoWarning.apply(null, args)
  } else {
    var msgTemplate = messages[warningName] ? messages[warningName] : warningName + ": '%s'"
    args.unshift(msgTemplate)
    return util.format.apply(null, args)
  }
}

function makeTypoWarning (providedName, probableName, field) {
  if (field) {
    providedName = field + "['" + providedName + "']"
    probableName = field + "['" + probableName + "']"
  }
  return util.format(messages.typo, providedName, probableName)
}
PK~\اoS%%1normalize-package-data/lib/extract_description.jsnu[module.exports = extractDescription

// Extracts description from contents of a readme file in markdown format
function extractDescription (d) {
  if (!d) {
    return
  }
  if (d === 'ERROR: No README data found!') {
    return
  }
  // the first block of text before the first heading
  // that isn't the first line heading
  d = d.trim().split('\n')
  let s = 0
  while (d[s] && d[s].trim().match(/^(#|$)/)) {
    s++
  }
  const l = d.length
  let e = s + 1
  while (e < l && d[e].trim()) {
    e++
  }
  return d.slice(s, e).join(' ').trim()
}
PK~\Ƨ~)normalize-package-data/lib/safe_format.jsnu[var util = require('util')

module.exports = function () {
  var args = Array.prototype.slice.call(arguments, 0)
  args.forEach(function (arg) {
    if (!arg) {
      throw new TypeError('Bad arguments.')
    }
  })
  return util.format.apply(null, arguments)
}
PK~\QVdd'normalize-package-data/lib/normalize.jsnu[module.exports = normalize

var fixer = require('./fixer')
normalize.fixer = fixer

var makeWarning = require('./make_warning')

var fieldsToFix = ['name', 'version', 'description', 'repository', 'modules', 'scripts',
  'files', 'bin', 'man', 'bugs', 'keywords', 'readme', 'homepage', 'license']
var otherThingsToFix = ['dependencies', 'people', 'typos']

var thingsToFix = fieldsToFix.map(function (fieldName) {
  return ucFirst(fieldName) + 'Field'
})
// two ways to do this in CoffeeScript on only one line, sub-70 chars:
// thingsToFix = fieldsToFix.map (name) -> ucFirst(name) + "Field"
// thingsToFix = (ucFirst(name) + "Field" for name in fieldsToFix)
thingsToFix = thingsToFix.concat(otherThingsToFix)

function normalize (data, warn, strict) {
  if (warn === true) {
    warn = null
    strict = true
  }
  if (!strict) {
    strict = false
  }
  if (!warn || data.private) {
    warn = function () { /* noop */ }
  }

  if (data.scripts &&
      data.scripts.install === 'node-gyp rebuild' &&
      !data.scripts.preinstall) {
    data.gypfile = true
  }
  fixer.warn = function () {
    warn(makeWarning.apply(null, arguments))
  }
  thingsToFix.forEach(function (thingName) {
    fixer['fix' + ucFirst(thingName)](data, strict)
  })
  data._id = data.name + '@' + data.version
}

function ucFirst (string) {
  return string.charAt(0).toUpperCase() + string.slice(1)
}
PK~\6%썔11#normalize-package-data/lib/fixer.jsnu[var isValidSemver = require('semver/functions/valid')
var cleanSemver = require('semver/functions/clean')
var validateLicense = require('validate-npm-package-license')
var hostedGitInfo = require('hosted-git-info')
var isBuiltinModule = require('is-core-module')
var depTypes = ['dependencies', 'devDependencies', 'optionalDependencies']
var extractDescription = require('./extract_description')
var url = require('url')
var typos = require('./typos.json')

var isEmail = str => str.includes('@') && (str.indexOf('@') < str.lastIndexOf('.'))

module.exports = {
  // default warning function
  warn: function () {},

  fixRepositoryField: function (data) {
    if (data.repositories) {
      this.warn('repositories')
      data.repository = data.repositories[0]
    }
    if (!data.repository) {
      return this.warn('missingRepository')
    }
    if (typeof data.repository === 'string') {
      data.repository = {
        type: 'git',
        url: data.repository,
      }
    }
    var r = data.repository.url || ''
    if (r) {
      var hosted = hostedGitInfo.fromUrl(r)
      if (hosted) {
        r = data.repository.url
          = hosted.getDefaultRepresentation() === 'shortcut' ? hosted.https() : hosted.toString()
      }
    }

    if (r.match(/github.com\/[^/]+\/[^/]+\.git\.git$/)) {
      this.warn('brokenGitUrl', r)
    }
  },

  fixTypos: function (data) {
    Object.keys(typos.topLevel).forEach(function (d) {
      if (Object.prototype.hasOwnProperty.call(data, d)) {
        this.warn('typo', d, typos.topLevel[d])
      }
    }, this)
  },

  fixScriptsField: function (data) {
    if (!data.scripts) {
      return
    }
    if (typeof data.scripts !== 'object') {
      this.warn('nonObjectScripts')
      delete data.scripts
      return
    }
    Object.keys(data.scripts).forEach(function (k) {
      if (typeof data.scripts[k] !== 'string') {
        this.warn('nonStringScript')
        delete data.scripts[k]
      } else if (typos.script[k] && !data.scripts[typos.script[k]]) {
        this.warn('typo', k, typos.script[k], 'scripts')
      }
    }, this)
  },

  fixFilesField: function (data) {
    var files = data.files
    if (files && !Array.isArray(files)) {
      this.warn('nonArrayFiles')
      delete data.files
    } else if (data.files) {
      data.files = data.files.filter(function (file) {
        if (!file || typeof file !== 'string') {
          this.warn('invalidFilename', file)
          return false
        } else {
          return true
        }
      }, this)
    }
  },

  fixBinField: function (data) {
    if (!data.bin) {
      return
    }
    if (typeof data.bin === 'string') {
      var b = {}
      var match
      if (match = data.name.match(/^@[^/]+[/](.*)$/)) {
        b[match[1]] = data.bin
      } else {
        b[data.name] = data.bin
      }
      data.bin = b
    }
  },

  fixManField: function (data) {
    if (!data.man) {
      return
    }
    if (typeof data.man === 'string') {
      data.man = [data.man]
    }
  },
  fixBundleDependenciesField: function (data) {
    var bdd = 'bundledDependencies'
    var bd = 'bundleDependencies'
    if (data[bdd] && !data[bd]) {
      data[bd] = data[bdd]
      delete data[bdd]
    }
    if (data[bd] && !Array.isArray(data[bd])) {
      this.warn('nonArrayBundleDependencies')
      delete data[bd]
    } else if (data[bd]) {
      data[bd] = data[bd].filter(function (filtered) {
        if (!filtered || typeof filtered !== 'string') {
          this.warn('nonStringBundleDependency', filtered)
          return false
        } else {
          if (!data.dependencies) {
            data.dependencies = {}
          }
          if (!Object.prototype.hasOwnProperty.call(data.dependencies, filtered)) {
            this.warn('nonDependencyBundleDependency', filtered)
            data.dependencies[filtered] = '*'
          }
          return true
        }
      }, this)
    }
  },

  fixDependencies: function (data) {
    objectifyDeps(data, this.warn)
    addOptionalDepsToDeps(data, this.warn)
    this.fixBundleDependenciesField(data)

    ;['dependencies', 'devDependencies'].forEach(function (deps) {
      if (!(deps in data)) {
        return
      }
      if (!data[deps] || typeof data[deps] !== 'object') {
        this.warn('nonObjectDependencies', deps)
        delete data[deps]
        return
      }
      Object.keys(data[deps]).forEach(function (d) {
        var r = data[deps][d]
        if (typeof r !== 'string') {
          this.warn('nonStringDependency', d, JSON.stringify(r))
          delete data[deps][d]
        }
        var hosted = hostedGitInfo.fromUrl(data[deps][d])
        if (hosted) {
          data[deps][d] = hosted.toString()
        }
      }, this)
    }, this)
  },

  fixModulesField: function (data) {
    if (data.modules) {
      this.warn('deprecatedModules')
      delete data.modules
    }
  },

  fixKeywordsField: function (data) {
    if (typeof data.keywords === 'string') {
      data.keywords = data.keywords.split(/,\s+/)
    }
    if (data.keywords && !Array.isArray(data.keywords)) {
      delete data.keywords
      this.warn('nonArrayKeywords')
    } else if (data.keywords) {
      data.keywords = data.keywords.filter(function (kw) {
        if (typeof kw !== 'string' || !kw) {
          this.warn('nonStringKeyword')
          return false
        } else {
          return true
        }
      }, this)
    }
  },

  fixVersionField: function (data, strict) {
    // allow "loose" semver 1.0 versions in non-strict mode
    // enforce strict semver 2.0 compliance in strict mode
    var loose = !strict
    if (!data.version) {
      data.version = ''
      return true
    }
    if (!isValidSemver(data.version, loose)) {
      throw new Error('Invalid version: "' + data.version + '"')
    }
    data.version = cleanSemver(data.version, loose)
    return true
  },

  fixPeople: function (data) {
    modifyPeople(data, unParsePerson)
    modifyPeople(data, parsePerson)
  },

  fixNameField: function (data, options) {
    if (typeof options === 'boolean') {
      options = { strict: options }
    } else if (typeof options === 'undefined') {
      options = {}
    }
    var strict = options.strict
    if (!data.name && !strict) {
      data.name = ''
      return
    }
    if (typeof data.name !== 'string') {
      throw new Error('name field must be a string.')
    }
    if (!strict) {
      data.name = data.name.trim()
    }
    ensureValidName(data.name, strict, options.allowLegacyCase)
    if (isBuiltinModule(data.name)) {
      this.warn('conflictingName', data.name)
    }
  },

  fixDescriptionField: function (data) {
    if (data.description && typeof data.description !== 'string') {
      this.warn('nonStringDescription')
      delete data.description
    }
    if (data.readme && !data.description) {
      data.description = extractDescription(data.readme)
    }
    if (data.description === undefined) {
      delete data.description
    }
    if (!data.description) {
      this.warn('missingDescription')
    }
  },

  fixReadmeField: function (data) {
    if (!data.readme) {
      this.warn('missingReadme')
      data.readme = 'ERROR: No README data found!'
    }
  },

  fixBugsField: function (data) {
    if (!data.bugs && data.repository && data.repository.url) {
      var hosted = hostedGitInfo.fromUrl(data.repository.url)
      if (hosted && hosted.bugs()) {
        data.bugs = { url: hosted.bugs() }
      }
    } else if (data.bugs) {
      if (typeof data.bugs === 'string') {
        if (isEmail(data.bugs)) {
          data.bugs = { email: data.bugs }
        /* eslint-disable-next-line node/no-deprecated-api */
        } else if (url.parse(data.bugs).protocol) {
          data.bugs = { url: data.bugs }
        } else {
          this.warn('nonEmailUrlBugsString')
        }
      } else {
        bugsTypos(data.bugs, this.warn)
        var oldBugs = data.bugs
        data.bugs = {}
        if (oldBugs.url) {
          /* eslint-disable-next-line node/no-deprecated-api */
          if (typeof (oldBugs.url) === 'string' && url.parse(oldBugs.url).protocol) {
            data.bugs.url = oldBugs.url
          } else {
            this.warn('nonUrlBugsUrlField')
          }
        }
        if (oldBugs.email) {
          if (typeof (oldBugs.email) === 'string' && isEmail(oldBugs.email)) {
            data.bugs.email = oldBugs.email
          } else {
            this.warn('nonEmailBugsEmailField')
          }
        }
      }
      if (!data.bugs.email && !data.bugs.url) {
        delete data.bugs
        this.warn('emptyNormalizedBugs')
      }
    }
  },

  fixHomepageField: function (data) {
    if (!data.homepage && data.repository && data.repository.url) {
      var hosted = hostedGitInfo.fromUrl(data.repository.url)
      if (hosted && hosted.docs()) {
        data.homepage = hosted.docs()
      }
    }
    if (!data.homepage) {
      return
    }

    if (typeof data.homepage !== 'string') {
      this.warn('nonUrlHomepage')
      return delete data.homepage
    }
    /* eslint-disable-next-line node/no-deprecated-api */
    if (!url.parse(data.homepage).protocol) {
      data.homepage = 'http://' + data.homepage
    }
  },

  fixLicenseField: function (data) {
    const license = data.license || data.licence
    if (!license) {
      return this.warn('missingLicense')
    }
    if (
      typeof (license) !== 'string' ||
      license.length < 1 ||
      license.trim() === ''
    ) {
      return this.warn('invalidLicense')
    }
    if (!validateLicense(license).validForNewPackages) {
      return this.warn('invalidLicense')
    }
  },
}

function isValidScopedPackageName (spec) {
  if (spec.charAt(0) !== '@') {
    return false
  }

  var rest = spec.slice(1).split('/')
  if (rest.length !== 2) {
    return false
  }

  return rest[0] && rest[1] &&
    rest[0] === encodeURIComponent(rest[0]) &&
    rest[1] === encodeURIComponent(rest[1])
}

function isCorrectlyEncodedName (spec) {
  return !spec.match(/[/@\s+%:]/) &&
    spec === encodeURIComponent(spec)
}

function ensureValidName (name, strict, allowLegacyCase) {
  if (name.charAt(0) === '.' ||
      !(isValidScopedPackageName(name) || isCorrectlyEncodedName(name)) ||
      (strict && (!allowLegacyCase) && name !== name.toLowerCase()) ||
      name.toLowerCase() === 'node_modules' ||
      name.toLowerCase() === 'favicon.ico') {
    throw new Error('Invalid name: ' + JSON.stringify(name))
  }
}

function modifyPeople (data, fn) {
  if (data.author) {
    data.author = fn(data.author)
  }['maintainers', 'contributors'].forEach(function (set) {
    if (!Array.isArray(data[set])) {
      return
    }
    data[set] = data[set].map(fn)
  })
  return data
}

function unParsePerson (person) {
  if (typeof person === 'string') {
    return person
  }
  var name = person.name || ''
  var u = person.url || person.web
  var wrappedUrl = u ? (' (' + u + ')') : ''
  var e = person.email || person.mail
  var wrappedEmail = e ? (' <' + e + '>') : ''
  return name + wrappedEmail + wrappedUrl
}

function parsePerson (person) {
  if (typeof person !== 'string') {
    return person
  }
  var matchedName = person.match(/^([^(<]+)/)
  var matchedUrl = person.match(/\(([^()]+)\)/)
  var matchedEmail = person.match(/<([^<>]+)>/)
  var obj = {}
  if (matchedName && matchedName[0].trim()) {
    obj.name = matchedName[0].trim()
  }
  if (matchedEmail) {
    obj.email = matchedEmail[1]
  }
  if (matchedUrl) {
    obj.url = matchedUrl[1]
  }
  return obj
}

function addOptionalDepsToDeps (data) {
  var o = data.optionalDependencies
  if (!o) {
    return
  }
  var d = data.dependencies || {}
  Object.keys(o).forEach(function (k) {
    d[k] = o[k]
  })
  data.dependencies = d
}

function depObjectify (deps, type, warn) {
  if (!deps) {
    return {}
  }
  if (typeof deps === 'string') {
    deps = deps.trim().split(/[\n\r\s\t ,]+/)
  }
  if (!Array.isArray(deps)) {
    return deps
  }
  warn('deprecatedArrayDependencies', type)
  var o = {}
  deps.filter(function (d) {
    return typeof d === 'string'
  }).forEach(function (d) {
    d = d.trim().split(/(:?[@\s><=])/)
    var dn = d.shift()
    var dv = d.join('')
    dv = dv.trim()
    dv = dv.replace(/^@/, '')
    o[dn] = dv
  })
  return o
}

function objectifyDeps (data, warn) {
  depTypes.forEach(function (type) {
    if (!data[type]) {
      return
    }
    data[type] = depObjectify(data[type], type, warn)
  })
}

function bugsTypos (bugs, warn) {
  if (!bugs) {
    return
  }
  Object.keys(bugs).forEach(function (k) {
    if (typos.bugs[k]) {
      warn('typo', k, typos.bugs[k], 'bugs')
      bugs[typos.bugs[k]] = bugs[k]
      delete bugs[k]
    }
  })
}
PK~\@ݔQ%normalize-package-data/lib/typos.jsonnu[{
  "topLevel": {
    "dependancies": "dependencies"
   ,"dependecies": "dependencies"
   ,"depdenencies": "dependencies"
   ,"devEependencies": "devDependencies"
   ,"depends": "dependencies"
   ,"dev-dependencies": "devDependencies"
   ,"devDependences": "devDependencies"
   ,"devDepenencies": "devDependencies"
   ,"devdependencies": "devDependencies"
   ,"repostitory": "repository"
   ,"repo": "repository"
   ,"prefereGlobal": "preferGlobal"
   ,"hompage": "homepage"
   ,"hampage": "homepage"
   ,"autohr": "author"
   ,"autor": "author"
   ,"contributers": "contributors"
   ,"publicationConfig": "publishConfig"
   ,"script": "scripts"
  },
  "bugs": { "web": "url", "name": "url" },
  "script": { "server": "start", "tests": "test" }
}
PK~\{{normalize-package-data/LICENSEnu[This package contains code originally written by Isaac Z. Schlueter.
Used with permission.

Copyright (c) Meryn Stol ("Author")
All rights reserved.

The BSD License

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
PK~\–
B22libnpmhook/package.jsonnu[{
  "_id": "libnpmhook@10.0.5",
  "_inBundle": true,
  "_location": "/npm/libnpmhook",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm"
  ],
  "author": {
    "name": "GitHub Inc."
  },
  "bugs": {
    "url": "https://github.com/npm/cli/issues"
  },
  "dependencies": {
    "aproba": "^2.0.0",
    "npm-registry-fetch": "^17.0.1"
  },
  "description": "programmatic API for managing npm registry hooks",
  "devDependencies": {
    "@npmcli/eslint-config": "^4.0.0",
    "@npmcli/template-oss": "4.22.0",
    "nock": "^13.3.3",
    "tap": "^16.3.8"
  },
  "engines": {
    "node": "^16.14.0 || >=18.0.0"
  },
  "files": [
    "bin/",
    "lib/"
  ],
  "homepage": "https://github.com/npm/cli#readme",
  "keywords": [
    "npm",
    "hooks",
    "registry",
    "npm api"
  ],
  "license": "ISC",
  "main": "lib/index.js",
  "name": "libnpmhook",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/cli.git",
    "directory": "workspaces/libnpmhook"
  },
  "scripts": {
    "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"",
    "lintfix": "npm run lint -- --fix",
    "postlint": "template-oss-check",
    "posttest": "npm run lint",
    "snap": "tap",
    "template-oss-apply": "template-oss-apply --force",
    "test": "tap"
  },
  "tap": {
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.22.0",
    "content": "../../scripts/template-oss/index.js"
  },
  "version": "10.0.5"
}
PK~\c<|libnpmhook/lib/index.jsnu['use strict'

const fetch = require('npm-registry-fetch')
const validate = require('aproba')

const eu = encodeURIComponent
const cmd = module.exports = {}
cmd.add = (name, endpoint, secret, opts = {}) => {
  validate('SSSO', [name, endpoint, secret, opts])
  let type = 'package'
  if (name.match(/^@[^/]+$/)) {
    type = 'scope'
  }
  if (name[0] === '~') {
    type = 'owner'
    name = name.slice(1)
  }
  return fetch.json('/-/npm/v1/hooks/hook', {
    ...opts,
    method: 'POST',
    body: { type, name, endpoint, secret },
  })
}

cmd.rm = (id, opts = {}) => {
  validate('SO', [id, opts])
  return fetch.json(`/-/npm/v1/hooks/hook/${eu(id)}`, {
    ...opts,
    method: 'DELETE',
  }).catch(err => {
    if (err.code === 'E404') {
      return null
    } else {
      throw err
    }
  })
}

cmd.update = (id, endpoint, secret, opts = {}) => {
  validate('SSSO', [id, endpoint, secret, opts])
  return fetch.json(`/-/npm/v1/hooks/hook/${eu(id)}`, {
    ...opts,
    method: 'PUT',
    body: { endpoint, secret },
  })
}

cmd.find = (id, opts = {}) => {
  validate('SO', [id, opts])
  return fetch.json(`/-/npm/v1/hooks/hook/${eu(id)}`, opts)
}

cmd.ls = (opts = {}) => {
  return cmd.ls.stream(opts).collect()
}

cmd.ls.stream = (opts = {}) => {
  const { package: pkg, limit, offset } = opts
  validate('S|Z', [pkg])
  validate('N|Z', [limit])
  validate('N|Z', [offset])
  return fetch.json.stream('/-/npm/v1/hooks', 'objects.*', {
    ...opts,
    query: {
      package: pkg,
      limit,
      offset,
    },
  })
}
PK~\g]vvlibnpmhook/README.mdnu[# libnpmhook

[![npm version](https://img.shields.io/npm/v/libnpmhook.svg)](https://npm.im/libnpmhook)
[![license](https://img.shields.io/npm/l/libnpmhook.svg)](https://npm.im/libnpmhook)
[![CI - libnpmhook](https://github.com/npm/cli/actions/workflows/ci-libnpmhook.yml/badge.svg)](https://github.com/npm/cli/actions/workflows/ci-libnpmhook.yml)

[`libnpmhook`](https://github.com/npm/libnpmhook) is a Node.js library for
programmatically managing the npm registry's server-side hooks.

For a more general introduction to managing hooks, see [the introductory blog
post](https://blog.npmjs.org/post/145260155635/introducing-hooks-get-notifications-of-npm).

## Table of Contents

* [Example](#example)
* [Install](#install)
* [Contributing](#contributing)
* [API](#api)
  * [hook opts](#opts)
  * [`add()`](#add)
  * [`rm()`](#rm)
  * [`ls()`](#ls)
  * [`ls.stream()`](#ls-stream)
  * [`update()`](#update)

## Example

```js
const hooks = require('libnpmhook')

console.log(await hooks.ls('mypkg', {token: 'deadbeef'}))
// array of hook objects on `mypkg`.
```

## Install

`$ npm install libnpmhook`

### API

####  `opts` for `libnpmhook` commands

`libnpmhook` uses [`npm-registry-fetch`](https://npm.im/npm-registry-fetch).
All options are passed through directly to that library, so please refer to [its
own `opts`
documentation](https://www.npmjs.com/package/npm-registry-fetch#fetch-options)
for options that can be passed in.

A couple of options of note for those in a hurry:

* `opts.token` - can be passed in and will be used as the authentication token for the registry. For other ways to pass in auth details, see the n-r-f docs.
* `opts.otp` - certain operations will require an OTP token to be passed in. If a `libnpmhook` command fails with `err.code === EOTP`, please retry the request with `{otp: <2fa token>}`

####  `> hooks.add(name, endpoint, secret, [opts]) -> Promise`

`name` is the name of the package, org, or user/org scope to watch. The type is
determined by the name syntax: `'@foo/bar'` and `'foo'` are treated as packages,
`@foo` is treated as a scope, and `~user` is treated as an org name or scope.
Each type will attach to different events.

The `endpoint` should be a fully-qualified http URL for the endpoint the hook
will send its payload to when it fires. `secret` is a shared secret that the
hook will send to that endpoint to verify that it's actually coming from the
registry hook.

The returned Promise resolves to the full hook object that was created,
including its generated `id`.

See also: [`POST
/v1/hooks/hook`](https://github.com/npm/registry/blob/master/docs/hooks/endpoints.md#post-v1hookshook)

##### Example

```javascript
await hooks.add('~zkat', 'https://example.com/api/added', 'supersekrit', {
  token: 'myregistrytoken',
  otp: '694207'
})

=>

{ id: '16f7xoal',
  username: 'zkat',
  name: 'zkat',
  endpoint: 'https://example.com/api/added',
  secret: 'supersekrit',
  type: 'owner',
  created: '2018-08-21T20:05:25.125Z',
  updated: '2018-08-21T20:05:25.125Z',
  deleted: false,
  delivered: false,
  last_delivery: null,
  response_code: 0,
  status: 'active' }
```

####  `> hooks.find(id, [opts]) -> Promise`

Returns the hook identified by `id`.

The returned Promise resolves to the full hook object that was found, or error
with `err.code` of `'E404'` if it didn't exist.

See also: [`GET
/v1/hooks/hook/:id`](https://github.com/npm/registry/blob/master/docs/hooks/endpoints.md#get-v1hookshookid)

##### Example

```javascript
await hooks.find('16f7xoal', {token: 'myregistrytoken'})

=>

{ id: '16f7xoal',
  username: 'zkat',
  name: 'zkat',
  endpoint: 'https://example.com/api/added',
  secret: 'supersekrit',
  type: 'owner',
  created: '2018-08-21T20:05:25.125Z',
  updated: '2018-08-21T20:05:25.125Z',
  deleted: false,
  delivered: false,
  last_delivery: null,
  response_code: 0,
  status: 'active' }
```

####  `> hooks.rm(id, [opts]) -> Promise`

Removes the hook identified by `id`.

The returned Promise resolves to the full hook object that was removed, if it
existed, or `null` if no such hook was there (instead of erroring).

See also: [`DELETE
/v1/hooks/hook/:id`](https://github.com/npm/registry/blob/master/docs/hooks/endpoints.md#delete-v1hookshookid)

##### Example

```javascript
await hooks.rm('16f7xoal', {
  token: 'myregistrytoken',
  otp: '694207'
})

=>

{ id: '16f7xoal',
  username: 'zkat',
  name: 'zkat',
  endpoint: 'https://example.com/api/added',
  secret: 'supersekrit',
  type: 'owner',
  created: '2018-08-21T20:05:25.125Z',
  updated: '2018-08-21T20:05:25.125Z',
  deleted: true,
  delivered: false,
  last_delivery: null,
  response_code: 0,
  status: 'active' }

// Repeat it...
await hooks.rm('16f7xoal', {
  token: 'myregistrytoken',
  otp: '694207'
})

=> null
```

####  `> hooks.update(id, endpoint, secret, [opts]) -> Promise`

The `id` should be a hook ID from a previously-created hook.

The `endpoint` should be a fully-qualified http URL for the endpoint the hook
will send its payload to when it fires. `secret` is a shared secret that the
hook will send to that endpoint to verify that it's actually coming from the
registry hook.

The returned Promise resolves to the full hook object that was updated, if it
existed. Otherwise, it will error with an `'E404'` error code.

See also: [`PUT
/v1/hooks/hook/:id`](https://github.com/npm/registry/blob/master/docs/hooks/endpoints.md#put-v1hookshookid)

##### Example

```javascript
await hooks.update('16fxoal', 'https://example.com/api/other', 'newsekrit', {
  token: 'myregistrytoken',
  otp: '694207'
})

=>

{ id: '16f7xoal',
  username: 'zkat',
  name: 'zkat',
  endpoint: 'https://example.com/api/other',
  secret: 'newsekrit',
  type: 'owner',
  created: '2018-08-21T20:05:25.125Z',
  updated: '2018-08-21T20:14:41.964Z',
  deleted: false,
  delivered: false,
  last_delivery: null,
  response_code: 0,
  status: 'active' }
```

####  `> hooks.ls([opts]) -> Promise`

Resolves to an array of hook objects associated with the account you're
authenticated as.

Results can be further filtered with three values that can be passed in through
`opts`:

* `opts.package` - filter results by package name
* `opts.limit` - maximum number of hooks to return
* `opts.offset` - pagination offset for results (use with `opts.limit`)

See also:
  * [`hooks.ls.stream()`](#ls-stream)
  * [`GET
/v1/hooks`](https://github.com/npm/registry/blob/master/docs/hooks/endpoints.md#get-v1hooks)

##### Example

```javascript
await hooks.ls({token: 'myregistrytoken'})

=>
[
  { id: '16f7xoal', ... },
  { id: 'wnyf98a1', ... },
  ...
]
```

####  `> hooks.ls.stream([opts]) -> Stream`

Returns a stream of hook objects associated with the account you're
authenticated as. The returned stream is a valid `Symbol.asyncIterator` on
`node@>=10`.

Results can be further filtered with three values that can be passed in through
`opts`:

* `opts.package` - filter results by package name
* `opts.limit` - maximum number of hooks to return
* `opts.offset` - pagination offset for results (use with `opts.limit`)

See also:
  * [`hooks.ls()`](#ls)
  * [`GET
/v1/hooks`](https://github.com/npm/registry/blob/master/docs/hooks/endpoints.md#get-v1hooks)

##### Example

```javascript
for await (let hook of hooks.ls.stream({token: 'myregistrytoken'})) {
  console.log('found hook:', hook.id)
}

=>
// outputs:
// found hook: 16f7xoal
// found hook: wnyf98a1
```
PK~\glibnpmhook/LICENSE.mdnu[ISC License

Copyright (c) npm, Inc.

Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE COPYRIGHT HOLDER DISCLAIMS
ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE
USE OR PERFORMANCE OF THIS SOFTWARE.
PK~\Zf	f	foreground-child/package.jsonnu[{
  "_id": "foreground-child@3.1.1",
  "_inBundle": true,
  "_location": "/npm/foreground-child",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm/glob"
  ],
  "author": {
    "name": "Isaac Z. Schlueter",
    "email": "i@izs.me",
    "url": "http://blog.izs.me/"
  },
  "bugs": {
    "url": "https://github.com/tapjs/foreground-child/issues"
  },
  "dependencies": {
    "cross-spawn": "^7.0.0",
    "signal-exit": "^4.0.1"
  },
  "description": "Run a child as if it's the foreground process. Give it stdio. Exit when it exits.",
  "devDependencies": {
    "@types/cross-spawn": "^6.0.2",
    "@types/node": "^18.15.11",
    "@types/tap": "^15.0.8",
    "c8": "^7.13.0",
    "prettier": "^2.8.6",
    "tap": "^16.3.4",
    "ts-node": "^10.9.1",
    "typedoc": "^0.24.2",
    "typescript": "^5.0.2"
  },
  "engines": {
    "node": ">=14"
  },
  "exports": {
    ".": {
      "import": {
        "types": "./dist/mjs/index.d.ts",
        "default": "./dist/mjs/index.js"
      },
      "require": {
        "types": "./dist/cjs/index.d.ts",
        "default": "./dist/cjs/index.js"
      }
    }
  },
  "files": [
    "dist"
  ],
  "funding": {
    "url": "https://github.com/sponsors/isaacs"
  },
  "homepage": "https://github.com/tapjs/foreground-child#readme",
  "license": "ISC",
  "main": "./dist/cjs/index.js",
  "module": "./dist/mjs/index.js",
  "name": "foreground-child",
  "prettier": {
    "semi": false,
    "printWidth": 75,
    "tabWidth": 2,
    "useTabs": false,
    "singleQuote": true,
    "jsxSingleQuote": false,
    "bracketSameLine": true,
    "arrowParens": "avoid",
    "endOfLine": "lf"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/tapjs/foreground-child.git"
  },
  "scripts": {
    "format": "prettier --write . --loglevel warn",
    "postversion": "npm publish",
    "prepare": "tsc -p tsconfig.json && tsc -p tsconfig-esm.json && bash ./scripts/fixup.sh",
    "prepublishOnly": "git push origin --follow-tags",
    "presnap": "npm run prepare",
    "pretest": "npm run prepare",
    "preversion": "npm test",
    "snap": "c8 tap",
    "test": "c8 tap",
    "typedoc": "typedoc --tsconfig tsconfig-esm.json ./src/*.ts"
  },
  "tap": {
    "coverage": false,
    "jobs": 1,
    "node-arg": [
      "--no-warnings",
      "--loader",
      "ts-node/esm"
    ],
    "ts": false
  },
  "types": "./dist/mjs/index.d.ts",
  "version": "3.1.1"
}
PK~\foreground-child/LICENSEnu[The ISC License

Copyright (c) 2015-2023 Isaac Z. Schlueter and Contributors

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
PK~\x&foreground-child/dist/mjs/package.jsonnu[{
  "type": "module"
}
PK~\(foreground-child/dist/mjs/all-signals.jsnu[import constants from 'node:constants';
export const allSignals = 
// this is the full list of signals that Node will let us do anything with
Object.keys(constants).filter(k => k.startsWith('SIG') &&
    // https://github.com/tapjs/signal-exit/issues/21
    k !== 'SIGPROF' &&
    // no sense trying to listen for SIGKILL, it's impossible
    k !== 'SIGKILL');
// These are some obscure signals that are reported by kill -l
// on macOS, Linux, or Windows, but which don't have any mapping
// in Node.js. No sense trying if they're just going to throw
// every time on every platform.
//
// 'SIGEMT',
// 'SIGLOST',
// 'SIGPOLL',
// 'SIGRTMAX',
// 'SIGRTMAX-1',
// 'SIGRTMAX-10',
// 'SIGRTMAX-11',
// 'SIGRTMAX-12',
// 'SIGRTMAX-13',
// 'SIGRTMAX-14',
// 'SIGRTMAX-15',
// 'SIGRTMAX-2',
// 'SIGRTMAX-3',
// 'SIGRTMAX-4',
// 'SIGRTMAX-5',
// 'SIGRTMAX-6',
// 'SIGRTMAX-7',
// 'SIGRTMAX-8',
// 'SIGRTMAX-9',
// 'SIGRTMIN',
// 'SIGRTMIN+1',
// 'SIGRTMIN+10',
// 'SIGRTMIN+11',
// 'SIGRTMIN+12',
// 'SIGRTMIN+13',
// 'SIGRTMIN+14',
// 'SIGRTMIN+15',
// 'SIGRTMIN+16',
// 'SIGRTMIN+2',
// 'SIGRTMIN+3',
// 'SIGRTMIN+4',
// 'SIGRTMIN+5',
// 'SIGRTMIN+6',
// 'SIGRTMIN+7',
// 'SIGRTMIN+8',
// 'SIGRTMIN+9',
// 'SIGSTKFLT',
// 'SIGUNUSED',
//# sourceMappingURL=all-signals.js.mapPK~\Ү*"foreground-child/dist/mjs/index.jsnu[import { spawn as nodeSpawn, } from 'child_process';
import crossSpawn from 'cross-spawn';
import { onExit } from 'signal-exit';
import { allSignals } from './all-signals.js';
import { watchdog } from './watchdog.js';
/* c8 ignore start */
const spawn = process?.platform === 'win32' ? crossSpawn : nodeSpawn;
/**
 * Normalizes the arguments passed to `foregroundChild`.
 *
 * Exposed for testing.
 *
 * @internal
 */
export const normalizeFgArgs = (fgArgs) => {
    let [program, args = [], spawnOpts = {}, cleanup = () => { }] = fgArgs;
    if (typeof args === 'function') {
        cleanup = args;
        spawnOpts = {};
        args = [];
    }
    else if (!!args && typeof args === 'object' && !Array.isArray(args)) {
        if (typeof spawnOpts === 'function')
            cleanup = spawnOpts;
        spawnOpts = args;
        args = [];
    }
    else if (typeof spawnOpts === 'function') {
        cleanup = spawnOpts;
        spawnOpts = {};
    }
    if (Array.isArray(program)) {
        const [pp, ...pa] = program;
        program = pp;
        args = pa;
    }
    return [program, args, { ...spawnOpts }, cleanup];
};
export function foregroundChild(...fgArgs) {
    const [program, args, spawnOpts, cleanup] = normalizeFgArgs(fgArgs);
    spawnOpts.stdio = [0, 1, 2];
    if (process.send) {
        spawnOpts.stdio.push('ipc');
    }
    const child = spawn(program, args, spawnOpts);
    const unproxySignals = proxySignals(child);
    const childHangup = () => {
        try {
            child.kill('SIGHUP');
            /* c8 ignore start */
        }
        catch (_) {
            // SIGHUP is weird on windows
            child.kill('SIGTERM');
        }
        /* c8 ignore stop */
    };
    const removeOnExit = onExit(childHangup);
    const dog = watchdog(child);
    let done = false;
    child.on('close', async (code, signal) => {
        dog.kill('SIGKILL');
        /* c8 ignore start */
        if (done) {
            return;
        }
        /* c8 ignore stop */
        done = true;
        const result = cleanup(code, signal);
        const res = isPromise(result) ? await result : result;
        removeOnExit();
        unproxySignals();
        if (res === false)
            return;
        else if (typeof res === 'string') {
            signal = res;
            code = null;
        }
        else if (typeof res === 'number') {
            code = res;
            signal = null;
        }
        if (signal) {
            // If there is nothing else keeping the event loop alive,
            // then there's a race between a graceful exit and getting
            // the signal to this process.  Put this timeout here to
            // make sure we're still alive to get the signal, and thus
            // exit with the intended signal code.
            /* istanbul ignore next */
            setTimeout(() => { }, 2000);
            try {
                process.kill(process.pid, signal);
                /* c8 ignore start */
            }
            catch (_) {
                process.kill(process.pid, 'SIGTERM');
            }
            /* c8 ignore stop */
        }
        else {
            process.exit(code || 0);
        }
    });
    if (process.send) {
        process.removeAllListeners('message');
        child.on('message', (message, sendHandle) => {
            process.send?.(message, sendHandle);
        });
        process.on('message', (message, sendHandle) => {
            child.send(message, sendHandle);
        });
    }
    return child;
}
/**
 * Starts forwarding signals to `child` through `parent`.
 */
const proxySignals = (child) => {
    const listeners = new Map();
    for (const sig of allSignals) {
        const listener = () => {
            // some signals can only be received, not sent
            try {
                child.kill(sig);
                /* c8 ignore start */
            }
            catch (_) { }
            /* c8 ignore stop */
        };
        try {
            // if it's a signal this system doesn't recognize, skip it
            process.on(sig, listener);
            listeners.set(sig, listener);
            /* c8 ignore start */
        }
        catch (_) { }
        /* c8 ignore stop */
    }
    return () => {
        for (const [sig, listener] of listeners) {
            process.removeListener(sig, listener);
        }
    };
};
const isPromise = (o) => !!o && typeof o === 'object' && typeof o.then === 'function';
//# sourceMappingURL=index.js.mapPK~\5qڂ%foreground-child/dist/mjs/watchdog.jsnu[// this spawns a child process that listens for SIGHUP when the
// parent process exits, and after 200ms, sends a SIGKILL to the
// child, in case it did not terminate.
import { spawn } from 'child_process';
const watchdogCode = String.raw `
const pid = parseInt(process.argv[1], 10)
process.title = 'node (foreground-child watchdog pid=' + pid + ')'
if (!isNaN(pid)) {
  let barked = false
  // keepalive
  const interval = setInterval(() => {}, 60000)
  const bark = () => {
    clearInterval(interval)
    if (barked) return
    barked = true
    process.removeListener('SIGHUP', bark)
    setTimeout(() => {
      try {
        process.kill(pid, 'SIGKILL')
        setTimeout(() => process.exit(), 200)
      } catch (_) {}
    }, 500)
  })
  process.on('SIGHUP', bark)
}
`;
export const watchdog = (child) => {
    let dogExited = false;
    const dog = spawn(process.execPath, ['-e', watchdogCode, String(child.pid)], {
        stdio: 'ignore',
    });
    dog.on('exit', () => (dogExited = true));
    child.on('exit', () => {
        if (!dogExited)
            dog.kill('SIGTERM');
    });
    return dog;
};
//# sourceMappingURL=watchdog.js.mapPK~\>&foreground-child/dist/cjs/package.jsonnu[{
  "type": "commonjs"
}
PK~\(foreground-child/dist/cjs/all-signals.jsnu["use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.allSignals = void 0;
const node_constants_1 = __importDefault(require("node:constants"));
exports.allSignals = 
// this is the full list of signals that Node will let us do anything with
Object.keys(node_constants_1.default).filter(k => k.startsWith('SIG') &&
    // https://github.com/tapjs/signal-exit/issues/21
    k !== 'SIGPROF' &&
    // no sense trying to listen for SIGKILL, it's impossible
    k !== 'SIGKILL');
// These are some obscure signals that are reported by kill -l
// on macOS, Linux, or Windows, but which don't have any mapping
// in Node.js. No sense trying if they're just going to throw
// every time on every platform.
//
// 'SIGEMT',
// 'SIGLOST',
// 'SIGPOLL',
// 'SIGRTMAX',
// 'SIGRTMAX-1',
// 'SIGRTMAX-10',
// 'SIGRTMAX-11',
// 'SIGRTMAX-12',
// 'SIGRTMAX-13',
// 'SIGRTMAX-14',
// 'SIGRTMAX-15',
// 'SIGRTMAX-2',
// 'SIGRTMAX-3',
// 'SIGRTMAX-4',
// 'SIGRTMAX-5',
// 'SIGRTMAX-6',
// 'SIGRTMAX-7',
// 'SIGRTMAX-8',
// 'SIGRTMAX-9',
// 'SIGRTMIN',
// 'SIGRTMIN+1',
// 'SIGRTMIN+10',
// 'SIGRTMIN+11',
// 'SIGRTMIN+12',
// 'SIGRTMIN+13',
// 'SIGRTMIN+14',
// 'SIGRTMIN+15',
// 'SIGRTMIN+16',
// 'SIGRTMIN+2',
// 'SIGRTMIN+3',
// 'SIGRTMIN+4',
// 'SIGRTMIN+5',
// 'SIGRTMIN+6',
// 'SIGRTMIN+7',
// 'SIGRTMIN+8',
// 'SIGRTMIN+9',
// 'SIGSTKFLT',
// 'SIGUNUSED',
//# sourceMappingURL=all-signals.js.mapPK~\Qpp"foreground-child/dist/cjs/index.jsnu["use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.foregroundChild = exports.normalizeFgArgs = void 0;
const child_process_1 = require("child_process");
const cross_spawn_1 = __importDefault(require("cross-spawn"));
const signal_exit_1 = require("signal-exit");
const all_signals_js_1 = require("./all-signals.js");
const watchdog_js_1 = require("./watchdog.js");
/* c8 ignore start */
const spawn = process?.platform === 'win32' ? cross_spawn_1.default : child_process_1.spawn;
/**
 * Normalizes the arguments passed to `foregroundChild`.
 *
 * Exposed for testing.
 *
 * @internal
 */
const normalizeFgArgs = (fgArgs) => {
    let [program, args = [], spawnOpts = {}, cleanup = () => { }] = fgArgs;
    if (typeof args === 'function') {
        cleanup = args;
        spawnOpts = {};
        args = [];
    }
    else if (!!args && typeof args === 'object' && !Array.isArray(args)) {
        if (typeof spawnOpts === 'function')
            cleanup = spawnOpts;
        spawnOpts = args;
        args = [];
    }
    else if (typeof spawnOpts === 'function') {
        cleanup = spawnOpts;
        spawnOpts = {};
    }
    if (Array.isArray(program)) {
        const [pp, ...pa] = program;
        program = pp;
        args = pa;
    }
    return [program, args, { ...spawnOpts }, cleanup];
};
exports.normalizeFgArgs = normalizeFgArgs;
function foregroundChild(...fgArgs) {
    const [program, args, spawnOpts, cleanup] = (0, exports.normalizeFgArgs)(fgArgs);
    spawnOpts.stdio = [0, 1, 2];
    if (process.send) {
        spawnOpts.stdio.push('ipc');
    }
    const child = spawn(program, args, spawnOpts);
    const unproxySignals = proxySignals(child);
    const childHangup = () => {
        try {
            child.kill('SIGHUP');
            /* c8 ignore start */
        }
        catch (_) {
            // SIGHUP is weird on windows
            child.kill('SIGTERM');
        }
        /* c8 ignore stop */
    };
    const removeOnExit = (0, signal_exit_1.onExit)(childHangup);
    const dog = (0, watchdog_js_1.watchdog)(child);
    let done = false;
    child.on('close', async (code, signal) => {
        dog.kill('SIGKILL');
        /* c8 ignore start */
        if (done) {
            return;
        }
        /* c8 ignore stop */
        done = true;
        const result = cleanup(code, signal);
        const res = isPromise(result) ? await result : result;
        removeOnExit();
        unproxySignals();
        if (res === false)
            return;
        else if (typeof res === 'string') {
            signal = res;
            code = null;
        }
        else if (typeof res === 'number') {
            code = res;
            signal = null;
        }
        if (signal) {
            // If there is nothing else keeping the event loop alive,
            // then there's a race between a graceful exit and getting
            // the signal to this process.  Put this timeout here to
            // make sure we're still alive to get the signal, and thus
            // exit with the intended signal code.
            /* istanbul ignore next */
            setTimeout(() => { }, 2000);
            try {
                process.kill(process.pid, signal);
                /* c8 ignore start */
            }
            catch (_) {
                process.kill(process.pid, 'SIGTERM');
            }
            /* c8 ignore stop */
        }
        else {
            process.exit(code || 0);
        }
    });
    if (process.send) {
        process.removeAllListeners('message');
        child.on('message', (message, sendHandle) => {
            process.send?.(message, sendHandle);
        });
        process.on('message', (message, sendHandle) => {
            child.send(message, sendHandle);
        });
    }
    return child;
}
exports.foregroundChild = foregroundChild;
/**
 * Starts forwarding signals to `child` through `parent`.
 */
const proxySignals = (child) => {
    const listeners = new Map();
    for (const sig of all_signals_js_1.allSignals) {
        const listener = () => {
            // some signals can only be received, not sent
            try {
                child.kill(sig);
                /* c8 ignore start */
            }
            catch (_) { }
            /* c8 ignore stop */
        };
        try {
            // if it's a signal this system doesn't recognize, skip it
            process.on(sig, listener);
            listeners.set(sig, listener);
            /* c8 ignore start */
        }
        catch (_) { }
        /* c8 ignore stop */
    }
    return () => {
        for (const [sig, listener] of listeners) {
            process.removeListener(sig, listener);
        }
    };
};
const isPromise = (o) => !!o && typeof o === 'object' && typeof o.then === 'function';
//# sourceMappingURL=index.js.mapPK~\>  %foreground-child/dist/cjs/watchdog.jsnu["use strict";
// this spawns a child process that listens for SIGHUP when the
// parent process exits, and after 200ms, sends a SIGKILL to the
// child, in case it did not terminate.
Object.defineProperty(exports, "__esModule", { value: true });
exports.watchdog = void 0;
const child_process_1 = require("child_process");
const watchdogCode = String.raw `
const pid = parseInt(process.argv[1], 10)
process.title = 'node (foreground-child watchdog pid=' + pid + ')'
if (!isNaN(pid)) {
  let barked = false
  // keepalive
  const interval = setInterval(() => {}, 60000)
  const bark = () => {
    clearInterval(interval)
    if (barked) return
    barked = true
    process.removeListener('SIGHUP', bark)
    setTimeout(() => {
      try {
        process.kill(pid, 'SIGKILL')
        setTimeout(() => process.exit(), 200)
      } catch (_) {}
    }, 500)
  })
  process.on('SIGHUP', bark)
}
`;
const watchdog = (child) => {
    let dogExited = false;
    const dog = (0, child_process_1.spawn)(process.execPath, ['-e', watchdogCode, String(child.pid)], {
        stdio: 'ignore',
    });
    dog.on('exit', () => (dogExited = true));
    child.on('exit', () => {
        if (!dogExited)
            dog.kill('SIGTERM');
    });
    return dog;
};
exports.watchdog = watchdog;
//# sourceMappingURL=watchdog.js.mapPK~\~strip-ansi-cjs/package.jsonnu[{
  "_args": [
    [
      "strip-ansi-cjs@npm:strip-ansi@6.0.1",
      "C:\\xampp\\htdocs\\emeraltd"
    ]
  ],
  "_from": "strip-ansi-cjs@npm:strip-ansi@6.0.1",
  "_id": "strip-ansi-cjs@npm:strip-ansi@6.0.1",
  "_inBundle": true,
  "_location": "/npm/strip-ansi-cjs",
  "_phantomChildren": {},
  "_requested": {
    "type": "alias",
    "registry": true,
    "raw": "strip-ansi-cjs@npm:strip-ansi@6.0.1",
    "name": "strip-ansi-cjs",
    "escapedName": "strip-ansi-cjs",
    "rawSpec": "npm:strip-ansi@6.0.1",
    "saveSpec": null,
    "fetchSpec": null,
    "subSpec": {
      "type": "version",
      "registry": true,
      "raw": "strip-ansi@6.0.1",
      "name": "strip-ansi",
      "escapedName": "strip-ansi",
      "rawSpec": "6.0.1",
      "saveSpec": null,
      "fetchSpec": "6.0.1"
    }
  },
  "_requiredBy": [],
  "_resolved": false,
  "_spec": "npm:strip-ansi@6.0.1",
  "_where": "C:\\xampp\\htdocs\\emeraltd",
  "author": {
    "name": "Sindre Sorhus",
    "email": "sindresorhus@gmail.com",
    "url": "sindresorhus.com"
  },
  "bugs": {
    "url": "https://github.com/chalk/strip-ansi/issues"
  },
  "dependencies": {
    "ansi-regex": "^5.0.1"
  },
  "description": "Strip ANSI escape codes from a string",
  "devDependencies": {
    "ava": "^2.4.0",
    "tsd": "^0.10.0",
    "xo": "^0.25.3"
  },
  "engines": {
    "node": ">=8"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "homepage": "https://github.com/chalk/strip-ansi#readme",
  "keywords": [
    "strip",
    "trim",
    "remove",
    "ansi",
    "styles",
    "color",
    "colour",
    "colors",
    "terminal",
    "console",
    "string",
    "tty",
    "escape",
    "formatting",
    "rgb",
    "256",
    "shell",
    "xterm",
    "log",
    "logging",
    "command-line",
    "text"
  ],
  "license": "MIT",
  "name": "strip-ansi-cjs",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/chalk/strip-ansi.git"
  },
  "scripts": {
    "test": "xo && ava && tsd"
  },
  "version": "6.0.1"
}
PK~\*9strip-ansi-cjs/index.jsnu['use strict';
const ansiRegex = require('ansi-regex');

module.exports = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string;
PK~\E}UUstrip-ansi-cjs/licensenu[MIT License

Copyright (c) Sindre Sorhus  (sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
PK~\;k#%@sigstore/protobuf-specs/package.jsonnu[{
  "_id": "@sigstore/protobuf-specs@0.3.2",
  "_inBundle": true,
  "_location": "/npm/@sigstore/protobuf-specs",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm/@sigstore/bundle",
    "/npm/@sigstore/sign",
    "/npm/@sigstore/tuf",
    "/npm/@sigstore/verify",
    "/npm/sigstore"
  ],
  "author": {
    "name": "bdehamer@github.com"
  },
  "bugs": {
    "url": "https://github.com/sigstore/protobuf-specs/issues"
  },
  "description": "code-signing for npm packages",
  "devDependencies": {
    "@tsconfig/node16": "^16.1.1",
    "@types/node": "^18.14.0",
    "typescript": "^4.9.5"
  },
  "engines": {
    "node": "^16.14.0 || >=18.0.0"
  },
  "files": [
    "dist"
  ],
  "homepage": "https://github.com/sigstore/protobuf-specs#readme",
  "license": "Apache-2.0",
  "main": "dist/index.js",
  "name": "@sigstore/protobuf-specs",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/sigstore/protobuf-specs.git"
  },
  "scripts": {
    "build": "tsc"
  },
  "types": "dist/index.d.ts",
  "version": "0.3.2"
}
PK~\"KW,W, @sigstore/protobuf-specs/LICENSEnu[
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright 2023 The Sigstore Authors

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
PK~\((5@sigstore/protobuf-specs/dist/__generated__/events.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CloudEventBatch = exports.CloudEvent_CloudEventAttributeValue = exports.CloudEvent_AttributesEntry = exports.CloudEvent = void 0;
/* eslint-disable */
const any_1 = require("./google/protobuf/any");
const timestamp_1 = require("./google/protobuf/timestamp");
function createBaseCloudEvent() {
    return { id: "", source: "", specVersion: "", type: "", attributes: {}, data: undefined };
}
exports.CloudEvent = {
    fromJSON(object) {
        return {
            id: isSet(object.id) ? String(object.id) : "",
            source: isSet(object.source) ? String(object.source) : "",
            specVersion: isSet(object.specVersion) ? String(object.specVersion) : "",
            type: isSet(object.type) ? String(object.type) : "",
            attributes: isObject(object.attributes)
                ? Object.entries(object.attributes).reduce((acc, [key, value]) => {
                    acc[key] = exports.CloudEvent_CloudEventAttributeValue.fromJSON(value);
                    return acc;
                }, {})
                : {},
            data: isSet(object.binaryData)
                ? { $case: "binaryData", binaryData: Buffer.from(bytesFromBase64(object.binaryData)) }
                : isSet(object.textData)
                    ? { $case: "textData", textData: String(object.textData) }
                    : isSet(object.protoData)
                        ? { $case: "protoData", protoData: any_1.Any.fromJSON(object.protoData) }
                        : undefined,
        };
    },
    toJSON(message) {
        const obj = {};
        message.id !== undefined && (obj.id = message.id);
        message.source !== undefined && (obj.source = message.source);
        message.specVersion !== undefined && (obj.specVersion = message.specVersion);
        message.type !== undefined && (obj.type = message.type);
        obj.attributes = {};
        if (message.attributes) {
            Object.entries(message.attributes).forEach(([k, v]) => {
                obj.attributes[k] = exports.CloudEvent_CloudEventAttributeValue.toJSON(v);
            });
        }
        message.data?.$case === "binaryData" &&
            (obj.binaryData = message.data?.binaryData !== undefined ? base64FromBytes(message.data?.binaryData) : undefined);
        message.data?.$case === "textData" && (obj.textData = message.data?.textData);
        message.data?.$case === "protoData" &&
            (obj.protoData = message.data?.protoData ? any_1.Any.toJSON(message.data?.protoData) : undefined);
        return obj;
    },
};
function createBaseCloudEvent_AttributesEntry() {
    return { key: "", value: undefined };
}
exports.CloudEvent_AttributesEntry = {
    fromJSON(object) {
        return {
            key: isSet(object.key) ? String(object.key) : "",
            value: isSet(object.value) ? exports.CloudEvent_CloudEventAttributeValue.fromJSON(object.value) : undefined,
        };
    },
    toJSON(message) {
        const obj = {};
        message.key !== undefined && (obj.key = message.key);
        message.value !== undefined &&
            (obj.value = message.value ? exports.CloudEvent_CloudEventAttributeValue.toJSON(message.value) : undefined);
        return obj;
    },
};
function createBaseCloudEvent_CloudEventAttributeValue() {
    return { attr: undefined };
}
exports.CloudEvent_CloudEventAttributeValue = {
    fromJSON(object) {
        return {
            attr: isSet(object.ceBoolean)
                ? { $case: "ceBoolean", ceBoolean: Boolean(object.ceBoolean) }
                : isSet(object.ceInteger)
                    ? { $case: "ceInteger", ceInteger: Number(object.ceInteger) }
                    : isSet(object.ceString)
                        ? { $case: "ceString", ceString: String(object.ceString) }
                        : isSet(object.ceBytes)
                            ? { $case: "ceBytes", ceBytes: Buffer.from(bytesFromBase64(object.ceBytes)) }
                            : isSet(object.ceUri)
                                ? { $case: "ceUri", ceUri: String(object.ceUri) }
                                : isSet(object.ceUriRef)
                                    ? { $case: "ceUriRef", ceUriRef: String(object.ceUriRef) }
                                    : isSet(object.ceTimestamp)
                                        ? { $case: "ceTimestamp", ceTimestamp: fromJsonTimestamp(object.ceTimestamp) }
                                        : undefined,
        };
    },
    toJSON(message) {
        const obj = {};
        message.attr?.$case === "ceBoolean" && (obj.ceBoolean = message.attr?.ceBoolean);
        message.attr?.$case === "ceInteger" && (obj.ceInteger = Math.round(message.attr?.ceInteger));
        message.attr?.$case === "ceString" && (obj.ceString = message.attr?.ceString);
        message.attr?.$case === "ceBytes" &&
            (obj.ceBytes = message.attr?.ceBytes !== undefined ? base64FromBytes(message.attr?.ceBytes) : undefined);
        message.attr?.$case === "ceUri" && (obj.ceUri = message.attr?.ceUri);
        message.attr?.$case === "ceUriRef" && (obj.ceUriRef = message.attr?.ceUriRef);
        message.attr?.$case === "ceTimestamp" && (obj.ceTimestamp = message.attr?.ceTimestamp.toISOString());
        return obj;
    },
};
function createBaseCloudEventBatch() {
    return { events: [] };
}
exports.CloudEventBatch = {
    fromJSON(object) {
        return { events: Array.isArray(object?.events) ? object.events.map((e) => exports.CloudEvent.fromJSON(e)) : [] };
    },
    toJSON(message) {
        const obj = {};
        if (message.events) {
            obj.events = message.events.map((e) => e ? exports.CloudEvent.toJSON(e) : undefined);
        }
        else {
            obj.events = [];
        }
        return obj;
    },
};
var tsProtoGlobalThis = (() => {
    if (typeof globalThis !== "undefined") {
        return globalThis;
    }
    if (typeof self !== "undefined") {
        return self;
    }
    if (typeof window !== "undefined") {
        return window;
    }
    if (typeof global !== "undefined") {
        return global;
    }
    throw "Unable to locate global object";
})();
function bytesFromBase64(b64) {
    if (tsProtoGlobalThis.Buffer) {
        return Uint8Array.from(tsProtoGlobalThis.Buffer.from(b64, "base64"));
    }
    else {
        const bin = tsProtoGlobalThis.atob(b64);
        const arr = new Uint8Array(bin.length);
        for (let i = 0; i < bin.length; ++i) {
            arr[i] = bin.charCodeAt(i);
        }
        return arr;
    }
}
function base64FromBytes(arr) {
    if (tsProtoGlobalThis.Buffer) {
        return tsProtoGlobalThis.Buffer.from(arr).toString("base64");
    }
    else {
        const bin = [];
        arr.forEach((byte) => {
            bin.push(String.fromCharCode(byte));
        });
        return tsProtoGlobalThis.btoa(bin.join(""));
    }
}
function fromTimestamp(t) {
    let millis = Number(t.seconds) * 1000;
    millis += t.nanos / 1000000;
    return new Date(millis);
}
function fromJsonTimestamp(o) {
    if (o instanceof Date) {
        return o;
    }
    else if (typeof o === "string") {
        return new Date(o);
    }
    else {
        return fromTimestamp(timestamp_1.Timestamp.fromJSON(o));
    }
}
function isObject(value) {
    return typeof value === "object" && value !== null;
}
function isSet(value) {
    return value !== null && value !== undefined;
}
PK~\g>@sigstore/protobuf-specs/dist/__generated__/sigstore_bundle.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Bundle = exports.VerificationMaterial = exports.TimestampVerificationData = void 0;
/* eslint-disable */
const envelope_1 = require("./envelope");
const sigstore_common_1 = require("./sigstore_common");
const sigstore_rekor_1 = require("./sigstore_rekor");
function createBaseTimestampVerificationData() {
    return { rfc3161Timestamps: [] };
}
exports.TimestampVerificationData = {
    fromJSON(object) {
        return {
            rfc3161Timestamps: Array.isArray(object?.rfc3161Timestamps)
                ? object.rfc3161Timestamps.map((e) => sigstore_common_1.RFC3161SignedTimestamp.fromJSON(e))
                : [],
        };
    },
    toJSON(message) {
        const obj = {};
        if (message.rfc3161Timestamps) {
            obj.rfc3161Timestamps = message.rfc3161Timestamps.map((e) => e ? sigstore_common_1.RFC3161SignedTimestamp.toJSON(e) : undefined);
        }
        else {
            obj.rfc3161Timestamps = [];
        }
        return obj;
    },
};
function createBaseVerificationMaterial() {
    return { content: undefined, tlogEntries: [], timestampVerificationData: undefined };
}
exports.VerificationMaterial = {
    fromJSON(object) {
        return {
            content: isSet(object.publicKey)
                ? { $case: "publicKey", publicKey: sigstore_common_1.PublicKeyIdentifier.fromJSON(object.publicKey) }
                : isSet(object.x509CertificateChain)
                    ? {
                        $case: "x509CertificateChain",
                        x509CertificateChain: sigstore_common_1.X509CertificateChain.fromJSON(object.x509CertificateChain),
                    }
                    : isSet(object.certificate)
                        ? { $case: "certificate", certificate: sigstore_common_1.X509Certificate.fromJSON(object.certificate) }
                        : undefined,
            tlogEntries: Array.isArray(object?.tlogEntries)
                ? object.tlogEntries.map((e) => sigstore_rekor_1.TransparencyLogEntry.fromJSON(e))
                : [],
            timestampVerificationData: isSet(object.timestampVerificationData)
                ? exports.TimestampVerificationData.fromJSON(object.timestampVerificationData)
                : undefined,
        };
    },
    toJSON(message) {
        const obj = {};
        message.content?.$case === "publicKey" &&
            (obj.publicKey = message.content?.publicKey ? sigstore_common_1.PublicKeyIdentifier.toJSON(message.content?.publicKey) : undefined);
        message.content?.$case === "x509CertificateChain" &&
            (obj.x509CertificateChain = message.content?.x509CertificateChain
                ? sigstore_common_1.X509CertificateChain.toJSON(message.content?.x509CertificateChain)
                : undefined);
        message.content?.$case === "certificate" &&
            (obj.certificate = message.content?.certificate
                ? sigstore_common_1.X509Certificate.toJSON(message.content?.certificate)
                : undefined);
        if (message.tlogEntries) {
            obj.tlogEntries = message.tlogEntries.map((e) => e ? sigstore_rekor_1.TransparencyLogEntry.toJSON(e) : undefined);
        }
        else {
            obj.tlogEntries = [];
        }
        message.timestampVerificationData !== undefined &&
            (obj.timestampVerificationData = message.timestampVerificationData
                ? exports.TimestampVerificationData.toJSON(message.timestampVerificationData)
                : undefined);
        return obj;
    },
};
function createBaseBundle() {
    return { mediaType: "", verificationMaterial: undefined, content: undefined };
}
exports.Bundle = {
    fromJSON(object) {
        return {
            mediaType: isSet(object.mediaType) ? String(object.mediaType) : "",
            verificationMaterial: isSet(object.verificationMaterial)
                ? exports.VerificationMaterial.fromJSON(object.verificationMaterial)
                : undefined,
            content: isSet(object.messageSignature)
                ? { $case: "messageSignature", messageSignature: sigstore_common_1.MessageSignature.fromJSON(object.messageSignature) }
                : isSet(object.dsseEnvelope)
                    ? { $case: "dsseEnvelope", dsseEnvelope: envelope_1.Envelope.fromJSON(object.dsseEnvelope) }
                    : undefined,
        };
    },
    toJSON(message) {
        const obj = {};
        message.mediaType !== undefined && (obj.mediaType = message.mediaType);
        message.verificationMaterial !== undefined && (obj.verificationMaterial = message.verificationMaterial
            ? exports.VerificationMaterial.toJSON(message.verificationMaterial)
            : undefined);
        message.content?.$case === "messageSignature" && (obj.messageSignature = message.content?.messageSignature
            ? sigstore_common_1.MessageSignature.toJSON(message.content?.messageSignature)
            : undefined);
        message.content?.$case === "dsseEnvelope" &&
            (obj.dsseEnvelope = message.content?.dsseEnvelope ? envelope_1.Envelope.toJSON(message.content?.dsseEnvelope) : undefined);
        return obj;
    },
};
function isSet(value) {
    return value !== null && value !== undefined;
}
PK~\RLCA@sigstore/protobuf-specs/dist/__generated__/sigstore_trustroot.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ClientTrustConfig = exports.SigningConfig = exports.TrustedRoot = exports.CertificateAuthority = exports.TransparencyLogInstance = void 0;
/* eslint-disable */
const sigstore_common_1 = require("./sigstore_common");
function createBaseTransparencyLogInstance() {
    return { baseUrl: "", hashAlgorithm: 0, publicKey: undefined, logId: undefined, checkpointKeyId: undefined };
}
exports.TransparencyLogInstance = {
    fromJSON(object) {
        return {
            baseUrl: isSet(object.baseUrl) ? String(object.baseUrl) : "",
            hashAlgorithm: isSet(object.hashAlgorithm) ? (0, sigstore_common_1.hashAlgorithmFromJSON)(object.hashAlgorithm) : 0,
            publicKey: isSet(object.publicKey) ? sigstore_common_1.PublicKey.fromJSON(object.publicKey) : undefined,
            logId: isSet(object.logId) ? sigstore_common_1.LogId.fromJSON(object.logId) : undefined,
            checkpointKeyId: isSet(object.checkpointKeyId) ? sigstore_common_1.LogId.fromJSON(object.checkpointKeyId) : undefined,
        };
    },
    toJSON(message) {
        const obj = {};
        message.baseUrl !== undefined && (obj.baseUrl = message.baseUrl);
        message.hashAlgorithm !== undefined && (obj.hashAlgorithm = (0, sigstore_common_1.hashAlgorithmToJSON)(message.hashAlgorithm));
        message.publicKey !== undefined &&
            (obj.publicKey = message.publicKey ? sigstore_common_1.PublicKey.toJSON(message.publicKey) : undefined);
        message.logId !== undefined && (obj.logId = message.logId ? sigstore_common_1.LogId.toJSON(message.logId) : undefined);
        message.checkpointKeyId !== undefined &&
            (obj.checkpointKeyId = message.checkpointKeyId ? sigstore_common_1.LogId.toJSON(message.checkpointKeyId) : undefined);
        return obj;
    },
};
function createBaseCertificateAuthority() {
    return { subject: undefined, uri: "", certChain: undefined, validFor: undefined };
}
exports.CertificateAuthority = {
    fromJSON(object) {
        return {
            subject: isSet(object.subject) ? sigstore_common_1.DistinguishedName.fromJSON(object.subject) : undefined,
            uri: isSet(object.uri) ? String(object.uri) : "",
            certChain: isSet(object.certChain) ? sigstore_common_1.X509CertificateChain.fromJSON(object.certChain) : undefined,
            validFor: isSet(object.validFor) ? sigstore_common_1.TimeRange.fromJSON(object.validFor) : undefined,
        };
    },
    toJSON(message) {
        const obj = {};
        message.subject !== undefined &&
            (obj.subject = message.subject ? sigstore_common_1.DistinguishedName.toJSON(message.subject) : undefined);
        message.uri !== undefined && (obj.uri = message.uri);
        message.certChain !== undefined &&
            (obj.certChain = message.certChain ? sigstore_common_1.X509CertificateChain.toJSON(message.certChain) : undefined);
        message.validFor !== undefined &&
            (obj.validFor = message.validFor ? sigstore_common_1.TimeRange.toJSON(message.validFor) : undefined);
        return obj;
    },
};
function createBaseTrustedRoot() {
    return { mediaType: "", tlogs: [], certificateAuthorities: [], ctlogs: [], timestampAuthorities: [] };
}
exports.TrustedRoot = {
    fromJSON(object) {
        return {
            mediaType: isSet(object.mediaType) ? String(object.mediaType) : "",
            tlogs: Array.isArray(object?.tlogs) ? object.tlogs.map((e) => exports.TransparencyLogInstance.fromJSON(e)) : [],
            certificateAuthorities: Array.isArray(object?.certificateAuthorities)
                ? object.certificateAuthorities.map((e) => exports.CertificateAuthority.fromJSON(e))
                : [],
            ctlogs: Array.isArray(object?.ctlogs)
                ? object.ctlogs.map((e) => exports.TransparencyLogInstance.fromJSON(e))
                : [],
            timestampAuthorities: Array.isArray(object?.timestampAuthorities)
                ? object.timestampAuthorities.map((e) => exports.CertificateAuthority.fromJSON(e))
                : [],
        };
    },
    toJSON(message) {
        const obj = {};
        message.mediaType !== undefined && (obj.mediaType = message.mediaType);
        if (message.tlogs) {
            obj.tlogs = message.tlogs.map((e) => e ? exports.TransparencyLogInstance.toJSON(e) : undefined);
        }
        else {
            obj.tlogs = [];
        }
        if (message.certificateAuthorities) {
            obj.certificateAuthorities = message.certificateAuthorities.map((e) => e ? exports.CertificateAuthority.toJSON(e) : undefined);
        }
        else {
            obj.certificateAuthorities = [];
        }
        if (message.ctlogs) {
            obj.ctlogs = message.ctlogs.map((e) => e ? exports.TransparencyLogInstance.toJSON(e) : undefined);
        }
        else {
            obj.ctlogs = [];
        }
        if (message.timestampAuthorities) {
            obj.timestampAuthorities = message.timestampAuthorities.map((e) => e ? exports.CertificateAuthority.toJSON(e) : undefined);
        }
        else {
            obj.timestampAuthorities = [];
        }
        return obj;
    },
};
function createBaseSigningConfig() {
    return { caUrl: "", oidcUrl: "", tlogUrls: [], tsaUrls: [] };
}
exports.SigningConfig = {
    fromJSON(object) {
        return {
            caUrl: isSet(object.caUrl) ? String(object.caUrl) : "",
            oidcUrl: isSet(object.oidcUrl) ? String(object.oidcUrl) : "",
            tlogUrls: Array.isArray(object?.tlogUrls) ? object.tlogUrls.map((e) => String(e)) : [],
            tsaUrls: Array.isArray(object?.tsaUrls) ? object.tsaUrls.map((e) => String(e)) : [],
        };
    },
    toJSON(message) {
        const obj = {};
        message.caUrl !== undefined && (obj.caUrl = message.caUrl);
        message.oidcUrl !== undefined && (obj.oidcUrl = message.oidcUrl);
        if (message.tlogUrls) {
            obj.tlogUrls = message.tlogUrls.map((e) => e);
        }
        else {
            obj.tlogUrls = [];
        }
        if (message.tsaUrls) {
            obj.tsaUrls = message.tsaUrls.map((e) => e);
        }
        else {
            obj.tsaUrls = [];
        }
        return obj;
    },
};
function createBaseClientTrustConfig() {
    return { mediaType: "", trustedRoot: undefined, signingConfig: undefined };
}
exports.ClientTrustConfig = {
    fromJSON(object) {
        return {
            mediaType: isSet(object.mediaType) ? String(object.mediaType) : "",
            trustedRoot: isSet(object.trustedRoot) ? exports.TrustedRoot.fromJSON(object.trustedRoot) : undefined,
            signingConfig: isSet(object.signingConfig) ? exports.SigningConfig.fromJSON(object.signingConfig) : undefined,
        };
    },
    toJSON(message) {
        const obj = {};
        message.mediaType !== undefined && (obj.mediaType = message.mediaType);
        message.trustedRoot !== undefined &&
            (obj.trustedRoot = message.trustedRoot ? exports.TrustedRoot.toJSON(message.trustedRoot) : undefined);
        message.signingConfig !== undefined &&
            (obj.signingConfig = message.signingConfig ? exports.SigningConfig.toJSON(message.signingConfig) : undefined);
        return obj;
    },
};
function isSet(value) {
    return value !== null && value !== undefined;
}
PK~\nx\\>@sigstore/protobuf-specs/dist/__generated__/sigstore_common.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TimeRange = exports.X509CertificateChain = exports.SubjectAlternativeName = exports.X509Certificate = exports.DistinguishedName = exports.ObjectIdentifierValuePair = exports.ObjectIdentifier = exports.PublicKeyIdentifier = exports.PublicKey = exports.RFC3161SignedTimestamp = exports.LogId = exports.MessageSignature = exports.HashOutput = exports.subjectAlternativeNameTypeToJSON = exports.subjectAlternativeNameTypeFromJSON = exports.SubjectAlternativeNameType = exports.publicKeyDetailsToJSON = exports.publicKeyDetailsFromJSON = exports.PublicKeyDetails = exports.hashAlgorithmToJSON = exports.hashAlgorithmFromJSON = exports.HashAlgorithm = void 0;
/* eslint-disable */
const timestamp_1 = require("./google/protobuf/timestamp");
/**
 * Only a subset of the secure hash standard algorithms are supported.
 * See  for more
 * details.
 * UNSPECIFIED SHOULD not be used, primary reason for inclusion is to force
 * any proto JSON serialization to emit the used hash algorithm, as default
 * option is to *omit* the default value of an enum (which is the first
 * value, represented by '0'.
 */
var HashAlgorithm;
(function (HashAlgorithm) {
    HashAlgorithm[HashAlgorithm["HASH_ALGORITHM_UNSPECIFIED"] = 0] = "HASH_ALGORITHM_UNSPECIFIED";
    HashAlgorithm[HashAlgorithm["SHA2_256"] = 1] = "SHA2_256";
    HashAlgorithm[HashAlgorithm["SHA2_384"] = 2] = "SHA2_384";
    HashAlgorithm[HashAlgorithm["SHA2_512"] = 3] = "SHA2_512";
    HashAlgorithm[HashAlgorithm["SHA3_256"] = 4] = "SHA3_256";
    HashAlgorithm[HashAlgorithm["SHA3_384"] = 5] = "SHA3_384";
})(HashAlgorithm = exports.HashAlgorithm || (exports.HashAlgorithm = {}));
function hashAlgorithmFromJSON(object) {
    switch (object) {
        case 0:
        case "HASH_ALGORITHM_UNSPECIFIED":
            return HashAlgorithm.HASH_ALGORITHM_UNSPECIFIED;
        case 1:
        case "SHA2_256":
            return HashAlgorithm.SHA2_256;
        case 2:
        case "SHA2_384":
            return HashAlgorithm.SHA2_384;
        case 3:
        case "SHA2_512":
            return HashAlgorithm.SHA2_512;
        case 4:
        case "SHA3_256":
            return HashAlgorithm.SHA3_256;
        case 5:
        case "SHA3_384":
            return HashAlgorithm.SHA3_384;
        default:
            throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum HashAlgorithm");
    }
}
exports.hashAlgorithmFromJSON = hashAlgorithmFromJSON;
function hashAlgorithmToJSON(object) {
    switch (object) {
        case HashAlgorithm.HASH_ALGORITHM_UNSPECIFIED:
            return "HASH_ALGORITHM_UNSPECIFIED";
        case HashAlgorithm.SHA2_256:
            return "SHA2_256";
        case HashAlgorithm.SHA2_384:
            return "SHA2_384";
        case HashAlgorithm.SHA2_512:
            return "SHA2_512";
        case HashAlgorithm.SHA3_256:
            return "SHA3_256";
        case HashAlgorithm.SHA3_384:
            return "SHA3_384";
        default:
            throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum HashAlgorithm");
    }
}
exports.hashAlgorithmToJSON = hashAlgorithmToJSON;
/**
 * Details of a specific public key, capturing the the key encoding method,
 * and signature algorithm.
 *
 * PublicKeyDetails captures the public key/hash algorithm combinations
 * recommended in the Sigstore ecosystem.
 *
 * This is modelled as a linear set as we want to provide a small number of
 * opinionated options instead of allowing every possible permutation.
 *
 * Any changes to this enum MUST be reflected in the algorithm registry.
 * See: docs/algorithm-registry.md
 *
 * To avoid the possibility of contradicting formats such as PKCS1 with
 * ED25519 the valid permutations are listed as a linear set instead of a
 * cartesian set (i.e one combined variable instead of two, one for encoding
 * and one for the signature algorithm).
 */
var PublicKeyDetails;
(function (PublicKeyDetails) {
    PublicKeyDetails[PublicKeyDetails["PUBLIC_KEY_DETAILS_UNSPECIFIED"] = 0] = "PUBLIC_KEY_DETAILS_UNSPECIFIED";
    /**
     * PKCS1_RSA_PKCS1V5 - RSA
     *
     * @deprecated
     */
    PublicKeyDetails[PublicKeyDetails["PKCS1_RSA_PKCS1V5"] = 1] = "PKCS1_RSA_PKCS1V5";
    /**
     * PKCS1_RSA_PSS - See RFC8017
     *
     * @deprecated
     */
    PublicKeyDetails[PublicKeyDetails["PKCS1_RSA_PSS"] = 2] = "PKCS1_RSA_PSS";
    /** @deprecated */
    PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PKCS1V5"] = 3] = "PKIX_RSA_PKCS1V5";
    /** @deprecated */
    PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PSS"] = 4] = "PKIX_RSA_PSS";
    /** PKIX_RSA_PKCS1V15_2048_SHA256 - RSA public key in PKIX format, PKCS#1v1.5 signature */
    PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PKCS1V15_2048_SHA256"] = 9] = "PKIX_RSA_PKCS1V15_2048_SHA256";
    PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PKCS1V15_3072_SHA256"] = 10] = "PKIX_RSA_PKCS1V15_3072_SHA256";
    PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PKCS1V15_4096_SHA256"] = 11] = "PKIX_RSA_PKCS1V15_4096_SHA256";
    /** PKIX_RSA_PSS_2048_SHA256 - RSA public key in PKIX format, RSASSA-PSS signature */
    PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PSS_2048_SHA256"] = 16] = "PKIX_RSA_PSS_2048_SHA256";
    PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PSS_3072_SHA256"] = 17] = "PKIX_RSA_PSS_3072_SHA256";
    PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PSS_4096_SHA256"] = 18] = "PKIX_RSA_PSS_4096_SHA256";
    /**
     * PKIX_ECDSA_P256_HMAC_SHA_256 - ECDSA
     *
     * @deprecated
     */
    PublicKeyDetails[PublicKeyDetails["PKIX_ECDSA_P256_HMAC_SHA_256"] = 6] = "PKIX_ECDSA_P256_HMAC_SHA_256";
    /** PKIX_ECDSA_P256_SHA_256 - See NIST FIPS 186-4 */
    PublicKeyDetails[PublicKeyDetails["PKIX_ECDSA_P256_SHA_256"] = 5] = "PKIX_ECDSA_P256_SHA_256";
    PublicKeyDetails[PublicKeyDetails["PKIX_ECDSA_P384_SHA_384"] = 12] = "PKIX_ECDSA_P384_SHA_384";
    PublicKeyDetails[PublicKeyDetails["PKIX_ECDSA_P521_SHA_512"] = 13] = "PKIX_ECDSA_P521_SHA_512";
    /** PKIX_ED25519 - Ed 25519 */
    PublicKeyDetails[PublicKeyDetails["PKIX_ED25519"] = 7] = "PKIX_ED25519";
    PublicKeyDetails[PublicKeyDetails["PKIX_ED25519_PH"] = 8] = "PKIX_ED25519_PH";
    /**
     * LMS_SHA256 - LMS and LM-OTS
     *
     * These keys and signatures may be used by private Sigstore
     * deployments, but are not currently supported by the public
     * good instance.
     *
     * USER WARNING: LMS and LM-OTS are both stateful signature schemes.
     * Using them correctly requires discretion and careful consideration
     * to ensure that individual secret keys are not used more than once.
     * In addition, LM-OTS is a single-use scheme, meaning that it
     * MUST NOT be used for more than one signature per LM-OTS key.
     * If you cannot maintain these invariants, you MUST NOT use these
     * schemes.
     */
    PublicKeyDetails[PublicKeyDetails["LMS_SHA256"] = 14] = "LMS_SHA256";
    PublicKeyDetails[PublicKeyDetails["LMOTS_SHA256"] = 15] = "LMOTS_SHA256";
})(PublicKeyDetails = exports.PublicKeyDetails || (exports.PublicKeyDetails = {}));
function publicKeyDetailsFromJSON(object) {
    switch (object) {
        case 0:
        case "PUBLIC_KEY_DETAILS_UNSPECIFIED":
            return PublicKeyDetails.PUBLIC_KEY_DETAILS_UNSPECIFIED;
        case 1:
        case "PKCS1_RSA_PKCS1V5":
            return PublicKeyDetails.PKCS1_RSA_PKCS1V5;
        case 2:
        case "PKCS1_RSA_PSS":
            return PublicKeyDetails.PKCS1_RSA_PSS;
        case 3:
        case "PKIX_RSA_PKCS1V5":
            return PublicKeyDetails.PKIX_RSA_PKCS1V5;
        case 4:
        case "PKIX_RSA_PSS":
            return PublicKeyDetails.PKIX_RSA_PSS;
        case 9:
        case "PKIX_RSA_PKCS1V15_2048_SHA256":
            return PublicKeyDetails.PKIX_RSA_PKCS1V15_2048_SHA256;
        case 10:
        case "PKIX_RSA_PKCS1V15_3072_SHA256":
            return PublicKeyDetails.PKIX_RSA_PKCS1V15_3072_SHA256;
        case 11:
        case "PKIX_RSA_PKCS1V15_4096_SHA256":
            return PublicKeyDetails.PKIX_RSA_PKCS1V15_4096_SHA256;
        case 16:
        case "PKIX_RSA_PSS_2048_SHA256":
            return PublicKeyDetails.PKIX_RSA_PSS_2048_SHA256;
        case 17:
        case "PKIX_RSA_PSS_3072_SHA256":
            return PublicKeyDetails.PKIX_RSA_PSS_3072_SHA256;
        case 18:
        case "PKIX_RSA_PSS_4096_SHA256":
            return PublicKeyDetails.PKIX_RSA_PSS_4096_SHA256;
        case 6:
        case "PKIX_ECDSA_P256_HMAC_SHA_256":
            return PublicKeyDetails.PKIX_ECDSA_P256_HMAC_SHA_256;
        case 5:
        case "PKIX_ECDSA_P256_SHA_256":
            return PublicKeyDetails.PKIX_ECDSA_P256_SHA_256;
        case 12:
        case "PKIX_ECDSA_P384_SHA_384":
            return PublicKeyDetails.PKIX_ECDSA_P384_SHA_384;
        case 13:
        case "PKIX_ECDSA_P521_SHA_512":
            return PublicKeyDetails.PKIX_ECDSA_P521_SHA_512;
        case 7:
        case "PKIX_ED25519":
            return PublicKeyDetails.PKIX_ED25519;
        case 8:
        case "PKIX_ED25519_PH":
            return PublicKeyDetails.PKIX_ED25519_PH;
        case 14:
        case "LMS_SHA256":
            return PublicKeyDetails.LMS_SHA256;
        case 15:
        case "LMOTS_SHA256":
            return PublicKeyDetails.LMOTS_SHA256;
        default:
            throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum PublicKeyDetails");
    }
}
exports.publicKeyDetailsFromJSON = publicKeyDetailsFromJSON;
function publicKeyDetailsToJSON(object) {
    switch (object) {
        case PublicKeyDetails.PUBLIC_KEY_DETAILS_UNSPECIFIED:
            return "PUBLIC_KEY_DETAILS_UNSPECIFIED";
        case PublicKeyDetails.PKCS1_RSA_PKCS1V5:
            return "PKCS1_RSA_PKCS1V5";
        case PublicKeyDetails.PKCS1_RSA_PSS:
            return "PKCS1_RSA_PSS";
        case PublicKeyDetails.PKIX_RSA_PKCS1V5:
            return "PKIX_RSA_PKCS1V5";
        case PublicKeyDetails.PKIX_RSA_PSS:
            return "PKIX_RSA_PSS";
        case PublicKeyDetails.PKIX_RSA_PKCS1V15_2048_SHA256:
            return "PKIX_RSA_PKCS1V15_2048_SHA256";
        case PublicKeyDetails.PKIX_RSA_PKCS1V15_3072_SHA256:
            return "PKIX_RSA_PKCS1V15_3072_SHA256";
        case PublicKeyDetails.PKIX_RSA_PKCS1V15_4096_SHA256:
            return "PKIX_RSA_PKCS1V15_4096_SHA256";
        case PublicKeyDetails.PKIX_RSA_PSS_2048_SHA256:
            return "PKIX_RSA_PSS_2048_SHA256";
        case PublicKeyDetails.PKIX_RSA_PSS_3072_SHA256:
            return "PKIX_RSA_PSS_3072_SHA256";
        case PublicKeyDetails.PKIX_RSA_PSS_4096_SHA256:
            return "PKIX_RSA_PSS_4096_SHA256";
        case PublicKeyDetails.PKIX_ECDSA_P256_HMAC_SHA_256:
            return "PKIX_ECDSA_P256_HMAC_SHA_256";
        case PublicKeyDetails.PKIX_ECDSA_P256_SHA_256:
            return "PKIX_ECDSA_P256_SHA_256";
        case PublicKeyDetails.PKIX_ECDSA_P384_SHA_384:
            return "PKIX_ECDSA_P384_SHA_384";
        case PublicKeyDetails.PKIX_ECDSA_P521_SHA_512:
            return "PKIX_ECDSA_P521_SHA_512";
        case PublicKeyDetails.PKIX_ED25519:
            return "PKIX_ED25519";
        case PublicKeyDetails.PKIX_ED25519_PH:
            return "PKIX_ED25519_PH";
        case PublicKeyDetails.LMS_SHA256:
            return "LMS_SHA256";
        case PublicKeyDetails.LMOTS_SHA256:
            return "LMOTS_SHA256";
        default:
            throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum PublicKeyDetails");
    }
}
exports.publicKeyDetailsToJSON = publicKeyDetailsToJSON;
var SubjectAlternativeNameType;
(function (SubjectAlternativeNameType) {
    SubjectAlternativeNameType[SubjectAlternativeNameType["SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED"] = 0] = "SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED";
    SubjectAlternativeNameType[SubjectAlternativeNameType["EMAIL"] = 1] = "EMAIL";
    SubjectAlternativeNameType[SubjectAlternativeNameType["URI"] = 2] = "URI";
    /**
     * OTHER_NAME - OID 1.3.6.1.4.1.57264.1.7
     * See https://github.com/sigstore/fulcio/blob/main/docs/oid-info.md#1361415726417--othername-san
     * for more details.
     */
    SubjectAlternativeNameType[SubjectAlternativeNameType["OTHER_NAME"] = 3] = "OTHER_NAME";
})(SubjectAlternativeNameType = exports.SubjectAlternativeNameType || (exports.SubjectAlternativeNameType = {}));
function subjectAlternativeNameTypeFromJSON(object) {
    switch (object) {
        case 0:
        case "SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED":
            return SubjectAlternativeNameType.SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED;
        case 1:
        case "EMAIL":
            return SubjectAlternativeNameType.EMAIL;
        case 2:
        case "URI":
            return SubjectAlternativeNameType.URI;
        case 3:
        case "OTHER_NAME":
            return SubjectAlternativeNameType.OTHER_NAME;
        default:
            throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum SubjectAlternativeNameType");
    }
}
exports.subjectAlternativeNameTypeFromJSON = subjectAlternativeNameTypeFromJSON;
function subjectAlternativeNameTypeToJSON(object) {
    switch (object) {
        case SubjectAlternativeNameType.SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED:
            return "SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED";
        case SubjectAlternativeNameType.EMAIL:
            return "EMAIL";
        case SubjectAlternativeNameType.URI:
            return "URI";
        case SubjectAlternativeNameType.OTHER_NAME:
            return "OTHER_NAME";
        default:
            throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum SubjectAlternativeNameType");
    }
}
exports.subjectAlternativeNameTypeToJSON = subjectAlternativeNameTypeToJSON;
function createBaseHashOutput() {
    return { algorithm: 0, digest: Buffer.alloc(0) };
}
exports.HashOutput = {
    fromJSON(object) {
        return {
            algorithm: isSet(object.algorithm) ? hashAlgorithmFromJSON(object.algorithm) : 0,
            digest: isSet(object.digest) ? Buffer.from(bytesFromBase64(object.digest)) : Buffer.alloc(0),
        };
    },
    toJSON(message) {
        const obj = {};
        message.algorithm !== undefined && (obj.algorithm = hashAlgorithmToJSON(message.algorithm));
        message.digest !== undefined &&
            (obj.digest = base64FromBytes(message.digest !== undefined ? message.digest : Buffer.alloc(0)));
        return obj;
    },
};
function createBaseMessageSignature() {
    return { messageDigest: undefined, signature: Buffer.alloc(0) };
}
exports.MessageSignature = {
    fromJSON(object) {
        return {
            messageDigest: isSet(object.messageDigest) ? exports.HashOutput.fromJSON(object.messageDigest) : undefined,
            signature: isSet(object.signature) ? Buffer.from(bytesFromBase64(object.signature)) : Buffer.alloc(0),
        };
    },
    toJSON(message) {
        const obj = {};
        message.messageDigest !== undefined &&
            (obj.messageDigest = message.messageDigest ? exports.HashOutput.toJSON(message.messageDigest) : undefined);
        message.signature !== undefined &&
            (obj.signature = base64FromBytes(message.signature !== undefined ? message.signature : Buffer.alloc(0)));
        return obj;
    },
};
function createBaseLogId() {
    return { keyId: Buffer.alloc(0) };
}
exports.LogId = {
    fromJSON(object) {
        return { keyId: isSet(object.keyId) ? Buffer.from(bytesFromBase64(object.keyId)) : Buffer.alloc(0) };
    },
    toJSON(message) {
        const obj = {};
        message.keyId !== undefined &&
            (obj.keyId = base64FromBytes(message.keyId !== undefined ? message.keyId : Buffer.alloc(0)));
        return obj;
    },
};
function createBaseRFC3161SignedTimestamp() {
    return { signedTimestamp: Buffer.alloc(0) };
}
exports.RFC3161SignedTimestamp = {
    fromJSON(object) {
        return {
            signedTimestamp: isSet(object.signedTimestamp)
                ? Buffer.from(bytesFromBase64(object.signedTimestamp))
                : Buffer.alloc(0),
        };
    },
    toJSON(message) {
        const obj = {};
        message.signedTimestamp !== undefined &&
            (obj.signedTimestamp = base64FromBytes(message.signedTimestamp !== undefined ? message.signedTimestamp : Buffer.alloc(0)));
        return obj;
    },
};
function createBasePublicKey() {
    return { rawBytes: undefined, keyDetails: 0, validFor: undefined };
}
exports.PublicKey = {
    fromJSON(object) {
        return {
            rawBytes: isSet(object.rawBytes) ? Buffer.from(bytesFromBase64(object.rawBytes)) : undefined,
            keyDetails: isSet(object.keyDetails) ? publicKeyDetailsFromJSON(object.keyDetails) : 0,
            validFor: isSet(object.validFor) ? exports.TimeRange.fromJSON(object.validFor) : undefined,
        };
    },
    toJSON(message) {
        const obj = {};
        message.rawBytes !== undefined &&
            (obj.rawBytes = message.rawBytes !== undefined ? base64FromBytes(message.rawBytes) : undefined);
        message.keyDetails !== undefined && (obj.keyDetails = publicKeyDetailsToJSON(message.keyDetails));
        message.validFor !== undefined &&
            (obj.validFor = message.validFor ? exports.TimeRange.toJSON(message.validFor) : undefined);
        return obj;
    },
};
function createBasePublicKeyIdentifier() {
    return { hint: "" };
}
exports.PublicKeyIdentifier = {
    fromJSON(object) {
        return { hint: isSet(object.hint) ? String(object.hint) : "" };
    },
    toJSON(message) {
        const obj = {};
        message.hint !== undefined && (obj.hint = message.hint);
        return obj;
    },
};
function createBaseObjectIdentifier() {
    return { id: [] };
}
exports.ObjectIdentifier = {
    fromJSON(object) {
        return { id: Array.isArray(object?.id) ? object.id.map((e) => Number(e)) : [] };
    },
    toJSON(message) {
        const obj = {};
        if (message.id) {
            obj.id = message.id.map((e) => Math.round(e));
        }
        else {
            obj.id = [];
        }
        return obj;
    },
};
function createBaseObjectIdentifierValuePair() {
    return { oid: undefined, value: Buffer.alloc(0) };
}
exports.ObjectIdentifierValuePair = {
    fromJSON(object) {
        return {
            oid: isSet(object.oid) ? exports.ObjectIdentifier.fromJSON(object.oid) : undefined,
            value: isSet(object.value) ? Buffer.from(bytesFromBase64(object.value)) : Buffer.alloc(0),
        };
    },
    toJSON(message) {
        const obj = {};
        message.oid !== undefined && (obj.oid = message.oid ? exports.ObjectIdentifier.toJSON(message.oid) : undefined);
        message.value !== undefined &&
            (obj.value = base64FromBytes(message.value !== undefined ? message.value : Buffer.alloc(0)));
        return obj;
    },
};
function createBaseDistinguishedName() {
    return { organization: "", commonName: "" };
}
exports.DistinguishedName = {
    fromJSON(object) {
        return {
            organization: isSet(object.organization) ? String(object.organization) : "",
            commonName: isSet(object.commonName) ? String(object.commonName) : "",
        };
    },
    toJSON(message) {
        const obj = {};
        message.organization !== undefined && (obj.organization = message.organization);
        message.commonName !== undefined && (obj.commonName = message.commonName);
        return obj;
    },
};
function createBaseX509Certificate() {
    return { rawBytes: Buffer.alloc(0) };
}
exports.X509Certificate = {
    fromJSON(object) {
        return { rawBytes: isSet(object.rawBytes) ? Buffer.from(bytesFromBase64(object.rawBytes)) : Buffer.alloc(0) };
    },
    toJSON(message) {
        const obj = {};
        message.rawBytes !== undefined &&
            (obj.rawBytes = base64FromBytes(message.rawBytes !== undefined ? message.rawBytes : Buffer.alloc(0)));
        return obj;
    },
};
function createBaseSubjectAlternativeName() {
    return { type: 0, identity: undefined };
}
exports.SubjectAlternativeName = {
    fromJSON(object) {
        return {
            type: isSet(object.type) ? subjectAlternativeNameTypeFromJSON(object.type) : 0,
            identity: isSet(object.regexp)
                ? { $case: "regexp", regexp: String(object.regexp) }
                : isSet(object.value)
                    ? { $case: "value", value: String(object.value) }
                    : undefined,
        };
    },
    toJSON(message) {
        const obj = {};
        message.type !== undefined && (obj.type = subjectAlternativeNameTypeToJSON(message.type));
        message.identity?.$case === "regexp" && (obj.regexp = message.identity?.regexp);
        message.identity?.$case === "value" && (obj.value = message.identity?.value);
        return obj;
    },
};
function createBaseX509CertificateChain() {
    return { certificates: [] };
}
exports.X509CertificateChain = {
    fromJSON(object) {
        return {
            certificates: Array.isArray(object?.certificates)
                ? object.certificates.map((e) => exports.X509Certificate.fromJSON(e))
                : [],
        };
    },
    toJSON(message) {
        const obj = {};
        if (message.certificates) {
            obj.certificates = message.certificates.map((e) => e ? exports.X509Certificate.toJSON(e) : undefined);
        }
        else {
            obj.certificates = [];
        }
        return obj;
    },
};
function createBaseTimeRange() {
    return { start: undefined, end: undefined };
}
exports.TimeRange = {
    fromJSON(object) {
        return {
            start: isSet(object.start) ? fromJsonTimestamp(object.start) : undefined,
            end: isSet(object.end) ? fromJsonTimestamp(object.end) : undefined,
        };
    },
    toJSON(message) {
        const obj = {};
        message.start !== undefined && (obj.start = message.start.toISOString());
        message.end !== undefined && (obj.end = message.end.toISOString());
        return obj;
    },
};
var tsProtoGlobalThis = (() => {
    if (typeof globalThis !== "undefined") {
        return globalThis;
    }
    if (typeof self !== "undefined") {
        return self;
    }
    if (typeof window !== "undefined") {
        return window;
    }
    if (typeof global !== "undefined") {
        return global;
    }
    throw "Unable to locate global object";
})();
function bytesFromBase64(b64) {
    if (tsProtoGlobalThis.Buffer) {
        return Uint8Array.from(tsProtoGlobalThis.Buffer.from(b64, "base64"));
    }
    else {
        const bin = tsProtoGlobalThis.atob(b64);
        const arr = new Uint8Array(bin.length);
        for (let i = 0; i < bin.length; ++i) {
            arr[i] = bin.charCodeAt(i);
        }
        return arr;
    }
}
function base64FromBytes(arr) {
    if (tsProtoGlobalThis.Buffer) {
        return tsProtoGlobalThis.Buffer.from(arr).toString("base64");
    }
    else {
        const bin = [];
        arr.forEach((byte) => {
            bin.push(String.fromCharCode(byte));
        });
        return tsProtoGlobalThis.btoa(bin.join(""));
    }
}
function fromTimestamp(t) {
    let millis = Number(t.seconds) * 1000;
    millis += t.nanos / 1000000;
    return new Date(millis);
}
function fromJsonTimestamp(o) {
    if (o instanceof Date) {
        return o;
    }
    else if (typeof o === "string") {
        return new Date(o);
    }
    else {
        return fromTimestamp(timestamp_1.Timestamp.fromJSON(o));
    }
}
function isSet(value) {
    return value !== null && value !== undefined;
}
PK~\7ްEE=@sigstore/protobuf-specs/dist/__generated__/sigstore_rekor.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TransparencyLogEntry = exports.InclusionPromise = exports.InclusionProof = exports.Checkpoint = exports.KindVersion = void 0;
/* eslint-disable */
const sigstore_common_1 = require("./sigstore_common");
function createBaseKindVersion() {
    return { kind: "", version: "" };
}
exports.KindVersion = {
    fromJSON(object) {
        return {
            kind: isSet(object.kind) ? String(object.kind) : "",
            version: isSet(object.version) ? String(object.version) : "",
        };
    },
    toJSON(message) {
        const obj = {};
        message.kind !== undefined && (obj.kind = message.kind);
        message.version !== undefined && (obj.version = message.version);
        return obj;
    },
};
function createBaseCheckpoint() {
    return { envelope: "" };
}
exports.Checkpoint = {
    fromJSON(object) {
        return { envelope: isSet(object.envelope) ? String(object.envelope) : "" };
    },
    toJSON(message) {
        const obj = {};
        message.envelope !== undefined && (obj.envelope = message.envelope);
        return obj;
    },
};
function createBaseInclusionProof() {
    return { logIndex: "0", rootHash: Buffer.alloc(0), treeSize: "0", hashes: [], checkpoint: undefined };
}
exports.InclusionProof = {
    fromJSON(object) {
        return {
            logIndex: isSet(object.logIndex) ? String(object.logIndex) : "0",
            rootHash: isSet(object.rootHash) ? Buffer.from(bytesFromBase64(object.rootHash)) : Buffer.alloc(0),
            treeSize: isSet(object.treeSize) ? String(object.treeSize) : "0",
            hashes: Array.isArray(object?.hashes) ? object.hashes.map((e) => Buffer.from(bytesFromBase64(e))) : [],
            checkpoint: isSet(object.checkpoint) ? exports.Checkpoint.fromJSON(object.checkpoint) : undefined,
        };
    },
    toJSON(message) {
        const obj = {};
        message.logIndex !== undefined && (obj.logIndex = message.logIndex);
        message.rootHash !== undefined &&
            (obj.rootHash = base64FromBytes(message.rootHash !== undefined ? message.rootHash : Buffer.alloc(0)));
        message.treeSize !== undefined && (obj.treeSize = message.treeSize);
        if (message.hashes) {
            obj.hashes = message.hashes.map((e) => base64FromBytes(e !== undefined ? e : Buffer.alloc(0)));
        }
        else {
            obj.hashes = [];
        }
        message.checkpoint !== undefined &&
            (obj.checkpoint = message.checkpoint ? exports.Checkpoint.toJSON(message.checkpoint) : undefined);
        return obj;
    },
};
function createBaseInclusionPromise() {
    return { signedEntryTimestamp: Buffer.alloc(0) };
}
exports.InclusionPromise = {
    fromJSON(object) {
        return {
            signedEntryTimestamp: isSet(object.signedEntryTimestamp)
                ? Buffer.from(bytesFromBase64(object.signedEntryTimestamp))
                : Buffer.alloc(0),
        };
    },
    toJSON(message) {
        const obj = {};
        message.signedEntryTimestamp !== undefined &&
            (obj.signedEntryTimestamp = base64FromBytes(message.signedEntryTimestamp !== undefined ? message.signedEntryTimestamp : Buffer.alloc(0)));
        return obj;
    },
};
function createBaseTransparencyLogEntry() {
    return {
        logIndex: "0",
        logId: undefined,
        kindVersion: undefined,
        integratedTime: "0",
        inclusionPromise: undefined,
        inclusionProof: undefined,
        canonicalizedBody: Buffer.alloc(0),
    };
}
exports.TransparencyLogEntry = {
    fromJSON(object) {
        return {
            logIndex: isSet(object.logIndex) ? String(object.logIndex) : "0",
            logId: isSet(object.logId) ? sigstore_common_1.LogId.fromJSON(object.logId) : undefined,
            kindVersion: isSet(object.kindVersion) ? exports.KindVersion.fromJSON(object.kindVersion) : undefined,
            integratedTime: isSet(object.integratedTime) ? String(object.integratedTime) : "0",
            inclusionPromise: isSet(object.inclusionPromise) ? exports.InclusionPromise.fromJSON(object.inclusionPromise) : undefined,
            inclusionProof: isSet(object.inclusionProof) ? exports.InclusionProof.fromJSON(object.inclusionProof) : undefined,
            canonicalizedBody: isSet(object.canonicalizedBody)
                ? Buffer.from(bytesFromBase64(object.canonicalizedBody))
                : Buffer.alloc(0),
        };
    },
    toJSON(message) {
        const obj = {};
        message.logIndex !== undefined && (obj.logIndex = message.logIndex);
        message.logId !== undefined && (obj.logId = message.logId ? sigstore_common_1.LogId.toJSON(message.logId) : undefined);
        message.kindVersion !== undefined &&
            (obj.kindVersion = message.kindVersion ? exports.KindVersion.toJSON(message.kindVersion) : undefined);
        message.integratedTime !== undefined && (obj.integratedTime = message.integratedTime);
        message.inclusionPromise !== undefined &&
            (obj.inclusionPromise = message.inclusionPromise ? exports.InclusionPromise.toJSON(message.inclusionPromise) : undefined);
        message.inclusionProof !== undefined &&
            (obj.inclusionProof = message.inclusionProof ? exports.InclusionProof.toJSON(message.inclusionProof) : undefined);
        message.canonicalizedBody !== undefined &&
            (obj.canonicalizedBody = base64FromBytes(message.canonicalizedBody !== undefined ? message.canonicalizedBody : Buffer.alloc(0)));
        return obj;
    },
};
var tsProtoGlobalThis = (() => {
    if (typeof globalThis !== "undefined") {
        return globalThis;
    }
    if (typeof self !== "undefined") {
        return self;
    }
    if (typeof window !== "undefined") {
        return window;
    }
    if (typeof global !== "undefined") {
        return global;
    }
    throw "Unable to locate global object";
})();
function bytesFromBase64(b64) {
    if (tsProtoGlobalThis.Buffer) {
        return Uint8Array.from(tsProtoGlobalThis.Buffer.from(b64, "base64"));
    }
    else {
        const bin = tsProtoGlobalThis.atob(b64);
        const arr = new Uint8Array(bin.length);
        for (let i = 0; i < bin.length; ++i) {
            arr[i] = bin.charCodeAt(i);
        }
        return arr;
    }
}
function base64FromBytes(arr) {
    if (tsProtoGlobalThis.Buffer) {
        return tsProtoGlobalThis.Buffer.from(arr).toString("base64");
    }
    else {
        const bin = [];
        arr.forEach((byte) => {
            bin.push(String.fromCharCode(byte));
        });
        return tsProtoGlobalThis.btoa(bin.join(""));
    }
}
function isSet(value) {
    return value !== null && value !== undefined;
}
PK~\|44D@sigstore/protobuf-specs/dist/__generated__/sigstore_verification.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Input = exports.Artifact = exports.ArtifactVerificationOptions_ObserverTimestampOptions = exports.ArtifactVerificationOptions_TlogIntegratedTimestampOptions = exports.ArtifactVerificationOptions_TimestampAuthorityOptions = exports.ArtifactVerificationOptions_CtlogOptions = exports.ArtifactVerificationOptions_TlogOptions = exports.ArtifactVerificationOptions = exports.PublicKeyIdentities = exports.CertificateIdentities = exports.CertificateIdentity = void 0;
/* eslint-disable */
const sigstore_bundle_1 = require("./sigstore_bundle");
const sigstore_common_1 = require("./sigstore_common");
const sigstore_trustroot_1 = require("./sigstore_trustroot");
function createBaseCertificateIdentity() {
    return { issuer: "", san: undefined, oids: [] };
}
exports.CertificateIdentity = {
    fromJSON(object) {
        return {
            issuer: isSet(object.issuer) ? String(object.issuer) : "",
            san: isSet(object.san) ? sigstore_common_1.SubjectAlternativeName.fromJSON(object.san) : undefined,
            oids: Array.isArray(object?.oids) ? object.oids.map((e) => sigstore_common_1.ObjectIdentifierValuePair.fromJSON(e)) : [],
        };
    },
    toJSON(message) {
        const obj = {};
        message.issuer !== undefined && (obj.issuer = message.issuer);
        message.san !== undefined && (obj.san = message.san ? sigstore_common_1.SubjectAlternativeName.toJSON(message.san) : undefined);
        if (message.oids) {
            obj.oids = message.oids.map((e) => e ? sigstore_common_1.ObjectIdentifierValuePair.toJSON(e) : undefined);
        }
        else {
            obj.oids = [];
        }
        return obj;
    },
};
function createBaseCertificateIdentities() {
    return { identities: [] };
}
exports.CertificateIdentities = {
    fromJSON(object) {
        return {
            identities: Array.isArray(object?.identities)
                ? object.identities.map((e) => exports.CertificateIdentity.fromJSON(e))
                : [],
        };
    },
    toJSON(message) {
        const obj = {};
        if (message.identities) {
            obj.identities = message.identities.map((e) => e ? exports.CertificateIdentity.toJSON(e) : undefined);
        }
        else {
            obj.identities = [];
        }
        return obj;
    },
};
function createBasePublicKeyIdentities() {
    return { publicKeys: [] };
}
exports.PublicKeyIdentities = {
    fromJSON(object) {
        return {
            publicKeys: Array.isArray(object?.publicKeys) ? object.publicKeys.map((e) => sigstore_common_1.PublicKey.fromJSON(e)) : [],
        };
    },
    toJSON(message) {
        const obj = {};
        if (message.publicKeys) {
            obj.publicKeys = message.publicKeys.map((e) => e ? sigstore_common_1.PublicKey.toJSON(e) : undefined);
        }
        else {
            obj.publicKeys = [];
        }
        return obj;
    },
};
function createBaseArtifactVerificationOptions() {
    return {
        signers: undefined,
        tlogOptions: undefined,
        ctlogOptions: undefined,
        tsaOptions: undefined,
        integratedTsOptions: undefined,
        observerOptions: undefined,
    };
}
exports.ArtifactVerificationOptions = {
    fromJSON(object) {
        return {
            signers: isSet(object.certificateIdentities)
                ? {
                    $case: "certificateIdentities",
                    certificateIdentities: exports.CertificateIdentities.fromJSON(object.certificateIdentities),
                }
                : isSet(object.publicKeys)
                    ? { $case: "publicKeys", publicKeys: exports.PublicKeyIdentities.fromJSON(object.publicKeys) }
                    : undefined,
            tlogOptions: isSet(object.tlogOptions)
                ? exports.ArtifactVerificationOptions_TlogOptions.fromJSON(object.tlogOptions)
                : undefined,
            ctlogOptions: isSet(object.ctlogOptions)
                ? exports.ArtifactVerificationOptions_CtlogOptions.fromJSON(object.ctlogOptions)
                : undefined,
            tsaOptions: isSet(object.tsaOptions)
                ? exports.ArtifactVerificationOptions_TimestampAuthorityOptions.fromJSON(object.tsaOptions)
                : undefined,
            integratedTsOptions: isSet(object.integratedTsOptions)
                ? exports.ArtifactVerificationOptions_TlogIntegratedTimestampOptions.fromJSON(object.integratedTsOptions)
                : undefined,
            observerOptions: isSet(object.observerOptions)
                ? exports.ArtifactVerificationOptions_ObserverTimestampOptions.fromJSON(object.observerOptions)
                : undefined,
        };
    },
    toJSON(message) {
        const obj = {};
        message.signers?.$case === "certificateIdentities" &&
            (obj.certificateIdentities = message.signers?.certificateIdentities
                ? exports.CertificateIdentities.toJSON(message.signers?.certificateIdentities)
                : undefined);
        message.signers?.$case === "publicKeys" && (obj.publicKeys = message.signers?.publicKeys
            ? exports.PublicKeyIdentities.toJSON(message.signers?.publicKeys)
            : undefined);
        message.tlogOptions !== undefined && (obj.tlogOptions = message.tlogOptions
            ? exports.ArtifactVerificationOptions_TlogOptions.toJSON(message.tlogOptions)
            : undefined);
        message.ctlogOptions !== undefined && (obj.ctlogOptions = message.ctlogOptions
            ? exports.ArtifactVerificationOptions_CtlogOptions.toJSON(message.ctlogOptions)
            : undefined);
        message.tsaOptions !== undefined && (obj.tsaOptions = message.tsaOptions
            ? exports.ArtifactVerificationOptions_TimestampAuthorityOptions.toJSON(message.tsaOptions)
            : undefined);
        message.integratedTsOptions !== undefined && (obj.integratedTsOptions = message.integratedTsOptions
            ? exports.ArtifactVerificationOptions_TlogIntegratedTimestampOptions.toJSON(message.integratedTsOptions)
            : undefined);
        message.observerOptions !== undefined && (obj.observerOptions = message.observerOptions
            ? exports.ArtifactVerificationOptions_ObserverTimestampOptions.toJSON(message.observerOptions)
            : undefined);
        return obj;
    },
};
function createBaseArtifactVerificationOptions_TlogOptions() {
    return { threshold: 0, performOnlineVerification: false, disable: false };
}
exports.ArtifactVerificationOptions_TlogOptions = {
    fromJSON(object) {
        return {
            threshold: isSet(object.threshold) ? Number(object.threshold) : 0,
            performOnlineVerification: isSet(object.performOnlineVerification)
                ? Boolean(object.performOnlineVerification)
                : false,
            disable: isSet(object.disable) ? Boolean(object.disable) : false,
        };
    },
    toJSON(message) {
        const obj = {};
        message.threshold !== undefined && (obj.threshold = Math.round(message.threshold));
        message.performOnlineVerification !== undefined &&
            (obj.performOnlineVerification = message.performOnlineVerification);
        message.disable !== undefined && (obj.disable = message.disable);
        return obj;
    },
};
function createBaseArtifactVerificationOptions_CtlogOptions() {
    return { threshold: 0, disable: false };
}
exports.ArtifactVerificationOptions_CtlogOptions = {
    fromJSON(object) {
        return {
            threshold: isSet(object.threshold) ? Number(object.threshold) : 0,
            disable: isSet(object.disable) ? Boolean(object.disable) : false,
        };
    },
    toJSON(message) {
        const obj = {};
        message.threshold !== undefined && (obj.threshold = Math.round(message.threshold));
        message.disable !== undefined && (obj.disable = message.disable);
        return obj;
    },
};
function createBaseArtifactVerificationOptions_TimestampAuthorityOptions() {
    return { threshold: 0, disable: false };
}
exports.ArtifactVerificationOptions_TimestampAuthorityOptions = {
    fromJSON(object) {
        return {
            threshold: isSet(object.threshold) ? Number(object.threshold) : 0,
            disable: isSet(object.disable) ? Boolean(object.disable) : false,
        };
    },
    toJSON(message) {
        const obj = {};
        message.threshold !== undefined && (obj.threshold = Math.round(message.threshold));
        message.disable !== undefined && (obj.disable = message.disable);
        return obj;
    },
};
function createBaseArtifactVerificationOptions_TlogIntegratedTimestampOptions() {
    return { threshold: 0, disable: false };
}
exports.ArtifactVerificationOptions_TlogIntegratedTimestampOptions = {
    fromJSON(object) {
        return {
            threshold: isSet(object.threshold) ? Number(object.threshold) : 0,
            disable: isSet(object.disable) ? Boolean(object.disable) : false,
        };
    },
    toJSON(message) {
        const obj = {};
        message.threshold !== undefined && (obj.threshold = Math.round(message.threshold));
        message.disable !== undefined && (obj.disable = message.disable);
        return obj;
    },
};
function createBaseArtifactVerificationOptions_ObserverTimestampOptions() {
    return { threshold: 0, disable: false };
}
exports.ArtifactVerificationOptions_ObserverTimestampOptions = {
    fromJSON(object) {
        return {
            threshold: isSet(object.threshold) ? Number(object.threshold) : 0,
            disable: isSet(object.disable) ? Boolean(object.disable) : false,
        };
    },
    toJSON(message) {
        const obj = {};
        message.threshold !== undefined && (obj.threshold = Math.round(message.threshold));
        message.disable !== undefined && (obj.disable = message.disable);
        return obj;
    },
};
function createBaseArtifact() {
    return { data: undefined };
}
exports.Artifact = {
    fromJSON(object) {
        return {
            data: isSet(object.artifactUri)
                ? { $case: "artifactUri", artifactUri: String(object.artifactUri) }
                : isSet(object.artifact)
                    ? { $case: "artifact", artifact: Buffer.from(bytesFromBase64(object.artifact)) }
                    : undefined,
        };
    },
    toJSON(message) {
        const obj = {};
        message.data?.$case === "artifactUri" && (obj.artifactUri = message.data?.artifactUri);
        message.data?.$case === "artifact" &&
            (obj.artifact = message.data?.artifact !== undefined ? base64FromBytes(message.data?.artifact) : undefined);
        return obj;
    },
};
function createBaseInput() {
    return {
        artifactTrustRoot: undefined,
        artifactVerificationOptions: undefined,
        bundle: undefined,
        artifact: undefined,
    };
}
exports.Input = {
    fromJSON(object) {
        return {
            artifactTrustRoot: isSet(object.artifactTrustRoot) ? sigstore_trustroot_1.TrustedRoot.fromJSON(object.artifactTrustRoot) : undefined,
            artifactVerificationOptions: isSet(object.artifactVerificationOptions)
                ? exports.ArtifactVerificationOptions.fromJSON(object.artifactVerificationOptions)
                : undefined,
            bundle: isSet(object.bundle) ? sigstore_bundle_1.Bundle.fromJSON(object.bundle) : undefined,
            artifact: isSet(object.artifact) ? exports.Artifact.fromJSON(object.artifact) : undefined,
        };
    },
    toJSON(message) {
        const obj = {};
        message.artifactTrustRoot !== undefined &&
            (obj.artifactTrustRoot = message.artifactTrustRoot ? sigstore_trustroot_1.TrustedRoot.toJSON(message.artifactTrustRoot) : undefined);
        message.artifactVerificationOptions !== undefined &&
            (obj.artifactVerificationOptions = message.artifactVerificationOptions
                ? exports.ArtifactVerificationOptions.toJSON(message.artifactVerificationOptions)
                : undefined);
        message.bundle !== undefined && (obj.bundle = message.bundle ? sigstore_bundle_1.Bundle.toJSON(message.bundle) : undefined);
        message.artifact !== undefined && (obj.artifact = message.artifact ? exports.Artifact.toJSON(message.artifact) : undefined);
        return obj;
    },
};
var tsProtoGlobalThis = (() => {
    if (typeof globalThis !== "undefined") {
        return globalThis;
    }
    if (typeof self !== "undefined") {
        return self;
    }
    if (typeof window !== "undefined") {
        return window;
    }
    if (typeof global !== "undefined") {
        return global;
    }
    throw "Unable to locate global object";
})();
function bytesFromBase64(b64) {
    if (tsProtoGlobalThis.Buffer) {
        return Uint8Array.from(tsProtoGlobalThis.Buffer.from(b64, "base64"));
    }
    else {
        const bin = tsProtoGlobalThis.atob(b64);
        const arr = new Uint8Array(bin.length);
        for (let i = 0; i < bin.length; ++i) {
            arr[i] = bin.charCodeAt(i);
        }
        return arr;
    }
}
function base64FromBytes(arr) {
    if (tsProtoGlobalThis.Buffer) {
        return tsProtoGlobalThis.Buffer.from(arr).toString("base64");
    }
    else {
        const bin = [];
        arr.forEach((byte) => {
            bin.push(String.fromCharCode(byte));
        });
        return tsProtoGlobalThis.btoa(bin.join(""));
    }
}
function isSet(value) {
    return value !== null && value !== undefined;
}
PK~\}e ݃H@sigstore/protobuf-specs/dist/__generated__/google/api/field_behavior.jsnu["use strict";
/* eslint-disable */
Object.defineProperty(exports, "__esModule", { value: true });
exports.fieldBehaviorToJSON = exports.fieldBehaviorFromJSON = exports.FieldBehavior = void 0;
/**
 * An indicator of the behavior of a given field (for example, that a field
 * is required in requests, or given as output but ignored as input).
 * This **does not** change the behavior in protocol buffers itself; it only
 * denotes the behavior and may affect how API tooling handles the field.
 *
 * Note: This enum **may** receive new values in the future.
 */
var FieldBehavior;
(function (FieldBehavior) {
    /** FIELD_BEHAVIOR_UNSPECIFIED - Conventional default for enums. Do not use this. */
    FieldBehavior[FieldBehavior["FIELD_BEHAVIOR_UNSPECIFIED"] = 0] = "FIELD_BEHAVIOR_UNSPECIFIED";
    /**
     * OPTIONAL - Specifically denotes a field as optional.
     * While all fields in protocol buffers are optional, this may be specified
     * for emphasis if appropriate.
     */
    FieldBehavior[FieldBehavior["OPTIONAL"] = 1] = "OPTIONAL";
    /**
     * REQUIRED - Denotes a field as required.
     * This indicates that the field **must** be provided as part of the request,
     * and failure to do so will cause an error (usually `INVALID_ARGUMENT`).
     */
    FieldBehavior[FieldBehavior["REQUIRED"] = 2] = "REQUIRED";
    /**
     * OUTPUT_ONLY - Denotes a field as output only.
     * This indicates that the field is provided in responses, but including the
     * field in a request does nothing (the server *must* ignore it and
     * *must not* throw an error as a result of the field's presence).
     */
    FieldBehavior[FieldBehavior["OUTPUT_ONLY"] = 3] = "OUTPUT_ONLY";
    /**
     * INPUT_ONLY - Denotes a field as input only.
     * This indicates that the field is provided in requests, and the
     * corresponding field is not included in output.
     */
    FieldBehavior[FieldBehavior["INPUT_ONLY"] = 4] = "INPUT_ONLY";
    /**
     * IMMUTABLE - Denotes a field as immutable.
     * This indicates that the field may be set once in a request to create a
     * resource, but may not be changed thereafter.
     */
    FieldBehavior[FieldBehavior["IMMUTABLE"] = 5] = "IMMUTABLE";
    /**
     * UNORDERED_LIST - Denotes that a (repeated) field is an unordered list.
     * This indicates that the service may provide the elements of the list
     * in any arbitrary order, rather than the order the user originally
     * provided. Additionally, the list's order may or may not be stable.
     */
    FieldBehavior[FieldBehavior["UNORDERED_LIST"] = 6] = "UNORDERED_LIST";
})(FieldBehavior = exports.FieldBehavior || (exports.FieldBehavior = {}));
function fieldBehaviorFromJSON(object) {
    switch (object) {
        case 0:
        case "FIELD_BEHAVIOR_UNSPECIFIED":
            return FieldBehavior.FIELD_BEHAVIOR_UNSPECIFIED;
        case 1:
        case "OPTIONAL":
            return FieldBehavior.OPTIONAL;
        case 2:
        case "REQUIRED":
            return FieldBehavior.REQUIRED;
        case 3:
        case "OUTPUT_ONLY":
            return FieldBehavior.OUTPUT_ONLY;
        case 4:
        case "INPUT_ONLY":
            return FieldBehavior.INPUT_ONLY;
        case 5:
        case "IMMUTABLE":
            return FieldBehavior.IMMUTABLE;
        case 6:
        case "UNORDERED_LIST":
            return FieldBehavior.UNORDERED_LIST;
        default:
            throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FieldBehavior");
    }
}
exports.fieldBehaviorFromJSON = fieldBehaviorFromJSON;
function fieldBehaviorToJSON(object) {
    switch (object) {
        case FieldBehavior.FIELD_BEHAVIOR_UNSPECIFIED:
            return "FIELD_BEHAVIOR_UNSPECIFIED";
        case FieldBehavior.OPTIONAL:
            return "OPTIONAL";
        case FieldBehavior.REQUIRED:
            return "REQUIRED";
        case FieldBehavior.OUTPUT_ONLY:
            return "OUTPUT_ONLY";
        case FieldBehavior.INPUT_ONLY:
            return "INPUT_ONLY";
        case FieldBehavior.IMMUTABLE:
            return "IMMUTABLE";
        case FieldBehavior.UNORDERED_LIST:
            return "UNORDERED_LIST";
        default:
            throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FieldBehavior");
    }
}
exports.fieldBehaviorToJSON = fieldBehaviorToJSON;
var tsProtoGlobalThis = (() => {
    if (typeof globalThis !== "undefined") {
        return globalThis;
    }
    if (typeof self !== "undefined") {
        return self;
    }
    if (typeof window !== "undefined") {
        return window;
    }
    if (typeof global !== "undefined") {
        return global;
    }
    throw "Unable to locate global object";
})();
PK~\AH@sigstore/protobuf-specs/dist/__generated__/google/protobuf/timestamp.jsnu["use strict";
/* eslint-disable */
Object.defineProperty(exports, "__esModule", { value: true });
exports.Timestamp = void 0;
function createBaseTimestamp() {
    return { seconds: "0", nanos: 0 };
}
exports.Timestamp = {
    fromJSON(object) {
        return {
            seconds: isSet(object.seconds) ? String(object.seconds) : "0",
            nanos: isSet(object.nanos) ? Number(object.nanos) : 0,
        };
    },
    toJSON(message) {
        const obj = {};
        message.seconds !== undefined && (obj.seconds = message.seconds);
        message.nanos !== undefined && (obj.nanos = Math.round(message.nanos));
        return obj;
    },
};
function isSet(value) {
    return value !== null && value !== undefined;
}
PK~\;ttB@sigstore/protobuf-specs/dist/__generated__/google/protobuf/any.jsnu["use strict";
/* eslint-disable */
Object.defineProperty(exports, "__esModule", { value: true });
exports.Any = void 0;
function createBaseAny() {
    return { typeUrl: "", value: Buffer.alloc(0) };
}
exports.Any = {
    fromJSON(object) {
        return {
            typeUrl: isSet(object.typeUrl) ? String(object.typeUrl) : "",
            value: isSet(object.value) ? Buffer.from(bytesFromBase64(object.value)) : Buffer.alloc(0),
        };
    },
    toJSON(message) {
        const obj = {};
        message.typeUrl !== undefined && (obj.typeUrl = message.typeUrl);
        message.value !== undefined &&
            (obj.value = base64FromBytes(message.value !== undefined ? message.value : Buffer.alloc(0)));
        return obj;
    },
};
var tsProtoGlobalThis = (() => {
    if (typeof globalThis !== "undefined") {
        return globalThis;
    }
    if (typeof self !== "undefined") {
        return self;
    }
    if (typeof window !== "undefined") {
        return window;
    }
    if (typeof global !== "undefined") {
        return global;
    }
    throw "Unable to locate global object";
})();
function bytesFromBase64(b64) {
    if (tsProtoGlobalThis.Buffer) {
        return Uint8Array.from(tsProtoGlobalThis.Buffer.from(b64, "base64"));
    }
    else {
        const bin = tsProtoGlobalThis.atob(b64);
        const arr = new Uint8Array(bin.length);
        for (let i = 0; i < bin.length; ++i) {
            arr[i] = bin.charCodeAt(i);
        }
        return arr;
    }
}
function base64FromBytes(arr) {
    if (tsProtoGlobalThis.Buffer) {
        return tsProtoGlobalThis.Buffer.from(arr).toString("base64");
    }
    else {
        const bin = [];
        arr.forEach((byte) => {
            bin.push(String.fromCharCode(byte));
        });
        return tsProtoGlobalThis.btoa(bin.join(""));
    }
}
function isSet(value) {
    return value !== null && value !== undefined;
}
PK~\I@sigstore/protobuf-specs/dist/__generated__/google/protobuf/descriptor.jsnu["use strict";
/* eslint-disable */
Object.defineProperty(exports, "__esModule", { value: true });
exports.GeneratedCodeInfo_Annotation = exports.GeneratedCodeInfo = exports.SourceCodeInfo_Location = exports.SourceCodeInfo = exports.UninterpretedOption_NamePart = exports.UninterpretedOption = exports.MethodOptions = exports.ServiceOptions = exports.EnumValueOptions = exports.EnumOptions = exports.OneofOptions = exports.FieldOptions = exports.MessageOptions = exports.FileOptions = exports.MethodDescriptorProto = exports.ServiceDescriptorProto = exports.EnumValueDescriptorProto = exports.EnumDescriptorProto_EnumReservedRange = exports.EnumDescriptorProto = exports.OneofDescriptorProto = exports.FieldDescriptorProto = exports.ExtensionRangeOptions = exports.DescriptorProto_ReservedRange = exports.DescriptorProto_ExtensionRange = exports.DescriptorProto = exports.FileDescriptorProto = exports.FileDescriptorSet = exports.methodOptions_IdempotencyLevelToJSON = exports.methodOptions_IdempotencyLevelFromJSON = exports.MethodOptions_IdempotencyLevel = exports.fieldOptions_JSTypeToJSON = exports.fieldOptions_JSTypeFromJSON = exports.FieldOptions_JSType = exports.fieldOptions_CTypeToJSON = exports.fieldOptions_CTypeFromJSON = exports.FieldOptions_CType = exports.fileOptions_OptimizeModeToJSON = exports.fileOptions_OptimizeModeFromJSON = exports.FileOptions_OptimizeMode = exports.fieldDescriptorProto_LabelToJSON = exports.fieldDescriptorProto_LabelFromJSON = exports.FieldDescriptorProto_Label = exports.fieldDescriptorProto_TypeToJSON = exports.fieldDescriptorProto_TypeFromJSON = exports.FieldDescriptorProto_Type = void 0;
var FieldDescriptorProto_Type;
(function (FieldDescriptorProto_Type) {
    /**
     * TYPE_DOUBLE - 0 is reserved for errors.
     * Order is weird for historical reasons.
     */
    FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_DOUBLE"] = 1] = "TYPE_DOUBLE";
    FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_FLOAT"] = 2] = "TYPE_FLOAT";
    /**
     * TYPE_INT64 - Not ZigZag encoded.  Negative numbers take 10 bytes.  Use TYPE_SINT64 if
     * negative values are likely.
     */
    FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_INT64"] = 3] = "TYPE_INT64";
    FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_UINT64"] = 4] = "TYPE_UINT64";
    /**
     * TYPE_INT32 - Not ZigZag encoded.  Negative numbers take 10 bytes.  Use TYPE_SINT32 if
     * negative values are likely.
     */
    FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_INT32"] = 5] = "TYPE_INT32";
    FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_FIXED64"] = 6] = "TYPE_FIXED64";
    FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_FIXED32"] = 7] = "TYPE_FIXED32";
    FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_BOOL"] = 8] = "TYPE_BOOL";
    FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_STRING"] = 9] = "TYPE_STRING";
    /**
     * TYPE_GROUP - Tag-delimited aggregate.
     * Group type is deprecated and not supported in proto3. However, Proto3
     * implementations should still be able to parse the group wire format and
     * treat group fields as unknown fields.
     */
    FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_GROUP"] = 10] = "TYPE_GROUP";
    /** TYPE_MESSAGE - Length-delimited aggregate. */
    FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_MESSAGE"] = 11] = "TYPE_MESSAGE";
    /** TYPE_BYTES - New in version 2. */
    FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_BYTES"] = 12] = "TYPE_BYTES";
    FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_UINT32"] = 13] = "TYPE_UINT32";
    FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_ENUM"] = 14] = "TYPE_ENUM";
    FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_SFIXED32"] = 15] = "TYPE_SFIXED32";
    FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_SFIXED64"] = 16] = "TYPE_SFIXED64";
    /** TYPE_SINT32 - Uses ZigZag encoding. */
    FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_SINT32"] = 17] = "TYPE_SINT32";
    /** TYPE_SINT64 - Uses ZigZag encoding. */
    FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_SINT64"] = 18] = "TYPE_SINT64";
})(FieldDescriptorProto_Type = exports.FieldDescriptorProto_Type || (exports.FieldDescriptorProto_Type = {}));
function fieldDescriptorProto_TypeFromJSON(object) {
    switch (object) {
        case 1:
        case "TYPE_DOUBLE":
            return FieldDescriptorProto_Type.TYPE_DOUBLE;
        case 2:
        case "TYPE_FLOAT":
            return FieldDescriptorProto_Type.TYPE_FLOAT;
        case 3:
        case "TYPE_INT64":
            return FieldDescriptorProto_Type.TYPE_INT64;
        case 4:
        case "TYPE_UINT64":
            return FieldDescriptorProto_Type.TYPE_UINT64;
        case 5:
        case "TYPE_INT32":
            return FieldDescriptorProto_Type.TYPE_INT32;
        case 6:
        case "TYPE_FIXED64":
            return FieldDescriptorProto_Type.TYPE_FIXED64;
        case 7:
        case "TYPE_FIXED32":
            return FieldDescriptorProto_Type.TYPE_FIXED32;
        case 8:
        case "TYPE_BOOL":
            return FieldDescriptorProto_Type.TYPE_BOOL;
        case 9:
        case "TYPE_STRING":
            return FieldDescriptorProto_Type.TYPE_STRING;
        case 10:
        case "TYPE_GROUP":
            return FieldDescriptorProto_Type.TYPE_GROUP;
        case 11:
        case "TYPE_MESSAGE":
            return FieldDescriptorProto_Type.TYPE_MESSAGE;
        case 12:
        case "TYPE_BYTES":
            return FieldDescriptorProto_Type.TYPE_BYTES;
        case 13:
        case "TYPE_UINT32":
            return FieldDescriptorProto_Type.TYPE_UINT32;
        case 14:
        case "TYPE_ENUM":
            return FieldDescriptorProto_Type.TYPE_ENUM;
        case 15:
        case "TYPE_SFIXED32":
            return FieldDescriptorProto_Type.TYPE_SFIXED32;
        case 16:
        case "TYPE_SFIXED64":
            return FieldDescriptorProto_Type.TYPE_SFIXED64;
        case 17:
        case "TYPE_SINT32":
            return FieldDescriptorProto_Type.TYPE_SINT32;
        case 18:
        case "TYPE_SINT64":
            return FieldDescriptorProto_Type.TYPE_SINT64;
        default:
            throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FieldDescriptorProto_Type");
    }
}
exports.fieldDescriptorProto_TypeFromJSON = fieldDescriptorProto_TypeFromJSON;
function fieldDescriptorProto_TypeToJSON(object) {
    switch (object) {
        case FieldDescriptorProto_Type.TYPE_DOUBLE:
            return "TYPE_DOUBLE";
        case FieldDescriptorProto_Type.TYPE_FLOAT:
            return "TYPE_FLOAT";
        case FieldDescriptorProto_Type.TYPE_INT64:
            return "TYPE_INT64";
        case FieldDescriptorProto_Type.TYPE_UINT64:
            return "TYPE_UINT64";
        case FieldDescriptorProto_Type.TYPE_INT32:
            return "TYPE_INT32";
        case FieldDescriptorProto_Type.TYPE_FIXED64:
            return "TYPE_FIXED64";
        case FieldDescriptorProto_Type.TYPE_FIXED32:
            return "TYPE_FIXED32";
        case FieldDescriptorProto_Type.TYPE_BOOL:
            return "TYPE_BOOL";
        case FieldDescriptorProto_Type.TYPE_STRING:
            return "TYPE_STRING";
        case FieldDescriptorProto_Type.TYPE_GROUP:
            return "TYPE_GROUP";
        case FieldDescriptorProto_Type.TYPE_MESSAGE:
            return "TYPE_MESSAGE";
        case FieldDescriptorProto_Type.TYPE_BYTES:
            return "TYPE_BYTES";
        case FieldDescriptorProto_Type.TYPE_UINT32:
            return "TYPE_UINT32";
        case FieldDescriptorProto_Type.TYPE_ENUM:
            return "TYPE_ENUM";
        case FieldDescriptorProto_Type.TYPE_SFIXED32:
            return "TYPE_SFIXED32";
        case FieldDescriptorProto_Type.TYPE_SFIXED64:
            return "TYPE_SFIXED64";
        case FieldDescriptorProto_Type.TYPE_SINT32:
            return "TYPE_SINT32";
        case FieldDescriptorProto_Type.TYPE_SINT64:
            return "TYPE_SINT64";
        default:
            throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FieldDescriptorProto_Type");
    }
}
exports.fieldDescriptorProto_TypeToJSON = fieldDescriptorProto_TypeToJSON;
var FieldDescriptorProto_Label;
(function (FieldDescriptorProto_Label) {
    /** LABEL_OPTIONAL - 0 is reserved for errors */
    FieldDescriptorProto_Label[FieldDescriptorProto_Label["LABEL_OPTIONAL"] = 1] = "LABEL_OPTIONAL";
    FieldDescriptorProto_Label[FieldDescriptorProto_Label["LABEL_REQUIRED"] = 2] = "LABEL_REQUIRED";
    FieldDescriptorProto_Label[FieldDescriptorProto_Label["LABEL_REPEATED"] = 3] = "LABEL_REPEATED";
})(FieldDescriptorProto_Label = exports.FieldDescriptorProto_Label || (exports.FieldDescriptorProto_Label = {}));
function fieldDescriptorProto_LabelFromJSON(object) {
    switch (object) {
        case 1:
        case "LABEL_OPTIONAL":
            return FieldDescriptorProto_Label.LABEL_OPTIONAL;
        case 2:
        case "LABEL_REQUIRED":
            return FieldDescriptorProto_Label.LABEL_REQUIRED;
        case 3:
        case "LABEL_REPEATED":
            return FieldDescriptorProto_Label.LABEL_REPEATED;
        default:
            throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FieldDescriptorProto_Label");
    }
}
exports.fieldDescriptorProto_LabelFromJSON = fieldDescriptorProto_LabelFromJSON;
function fieldDescriptorProto_LabelToJSON(object) {
    switch (object) {
        case FieldDescriptorProto_Label.LABEL_OPTIONAL:
            return "LABEL_OPTIONAL";
        case FieldDescriptorProto_Label.LABEL_REQUIRED:
            return "LABEL_REQUIRED";
        case FieldDescriptorProto_Label.LABEL_REPEATED:
            return "LABEL_REPEATED";
        default:
            throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FieldDescriptorProto_Label");
    }
}
exports.fieldDescriptorProto_LabelToJSON = fieldDescriptorProto_LabelToJSON;
/** Generated classes can be optimized for speed or code size. */
var FileOptions_OptimizeMode;
(function (FileOptions_OptimizeMode) {
    /** SPEED - Generate complete code for parsing, serialization, */
    FileOptions_OptimizeMode[FileOptions_OptimizeMode["SPEED"] = 1] = "SPEED";
    /** CODE_SIZE - etc. */
    FileOptions_OptimizeMode[FileOptions_OptimizeMode["CODE_SIZE"] = 2] = "CODE_SIZE";
    /** LITE_RUNTIME - Generate code using MessageLite and the lite runtime. */
    FileOptions_OptimizeMode[FileOptions_OptimizeMode["LITE_RUNTIME"] = 3] = "LITE_RUNTIME";
})(FileOptions_OptimizeMode = exports.FileOptions_OptimizeMode || (exports.FileOptions_OptimizeMode = {}));
function fileOptions_OptimizeModeFromJSON(object) {
    switch (object) {
        case 1:
        case "SPEED":
            return FileOptions_OptimizeMode.SPEED;
        case 2:
        case "CODE_SIZE":
            return FileOptions_OptimizeMode.CODE_SIZE;
        case 3:
        case "LITE_RUNTIME":
            return FileOptions_OptimizeMode.LITE_RUNTIME;
        default:
            throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FileOptions_OptimizeMode");
    }
}
exports.fileOptions_OptimizeModeFromJSON = fileOptions_OptimizeModeFromJSON;
function fileOptions_OptimizeModeToJSON(object) {
    switch (object) {
        case FileOptions_OptimizeMode.SPEED:
            return "SPEED";
        case FileOptions_OptimizeMode.CODE_SIZE:
            return "CODE_SIZE";
        case FileOptions_OptimizeMode.LITE_RUNTIME:
            return "LITE_RUNTIME";
        default:
            throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FileOptions_OptimizeMode");
    }
}
exports.fileOptions_OptimizeModeToJSON = fileOptions_OptimizeModeToJSON;
var FieldOptions_CType;
(function (FieldOptions_CType) {
    /** STRING - Default mode. */
    FieldOptions_CType[FieldOptions_CType["STRING"] = 0] = "STRING";
    FieldOptions_CType[FieldOptions_CType["CORD"] = 1] = "CORD";
    FieldOptions_CType[FieldOptions_CType["STRING_PIECE"] = 2] = "STRING_PIECE";
})(FieldOptions_CType = exports.FieldOptions_CType || (exports.FieldOptions_CType = {}));
function fieldOptions_CTypeFromJSON(object) {
    switch (object) {
        case 0:
        case "STRING":
            return FieldOptions_CType.STRING;
        case 1:
        case "CORD":
            return FieldOptions_CType.CORD;
        case 2:
        case "STRING_PIECE":
            return FieldOptions_CType.STRING_PIECE;
        default:
            throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FieldOptions_CType");
    }
}
exports.fieldOptions_CTypeFromJSON = fieldOptions_CTypeFromJSON;
function fieldOptions_CTypeToJSON(object) {
    switch (object) {
        case FieldOptions_CType.STRING:
            return "STRING";
        case FieldOptions_CType.CORD:
            return "CORD";
        case FieldOptions_CType.STRING_PIECE:
            return "STRING_PIECE";
        default:
            throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FieldOptions_CType");
    }
}
exports.fieldOptions_CTypeToJSON = fieldOptions_CTypeToJSON;
var FieldOptions_JSType;
(function (FieldOptions_JSType) {
    /** JS_NORMAL - Use the default type. */
    FieldOptions_JSType[FieldOptions_JSType["JS_NORMAL"] = 0] = "JS_NORMAL";
    /** JS_STRING - Use JavaScript strings. */
    FieldOptions_JSType[FieldOptions_JSType["JS_STRING"] = 1] = "JS_STRING";
    /** JS_NUMBER - Use JavaScript numbers. */
    FieldOptions_JSType[FieldOptions_JSType["JS_NUMBER"] = 2] = "JS_NUMBER";
})(FieldOptions_JSType = exports.FieldOptions_JSType || (exports.FieldOptions_JSType = {}));
function fieldOptions_JSTypeFromJSON(object) {
    switch (object) {
        case 0:
        case "JS_NORMAL":
            return FieldOptions_JSType.JS_NORMAL;
        case 1:
        case "JS_STRING":
            return FieldOptions_JSType.JS_STRING;
        case 2:
        case "JS_NUMBER":
            return FieldOptions_JSType.JS_NUMBER;
        default:
            throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FieldOptions_JSType");
    }
}
exports.fieldOptions_JSTypeFromJSON = fieldOptions_JSTypeFromJSON;
function fieldOptions_JSTypeToJSON(object) {
    switch (object) {
        case FieldOptions_JSType.JS_NORMAL:
            return "JS_NORMAL";
        case FieldOptions_JSType.JS_STRING:
            return "JS_STRING";
        case FieldOptions_JSType.JS_NUMBER:
            return "JS_NUMBER";
        default:
            throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum FieldOptions_JSType");
    }
}
exports.fieldOptions_JSTypeToJSON = fieldOptions_JSTypeToJSON;
/**
 * Is this method side-effect-free (or safe in HTTP parlance), or idempotent,
 * or neither? HTTP based RPC implementation may choose GET verb for safe
 * methods, and PUT verb for idempotent methods instead of the default POST.
 */
var MethodOptions_IdempotencyLevel;
(function (MethodOptions_IdempotencyLevel) {
    MethodOptions_IdempotencyLevel[MethodOptions_IdempotencyLevel["IDEMPOTENCY_UNKNOWN"] = 0] = "IDEMPOTENCY_UNKNOWN";
    /** NO_SIDE_EFFECTS - implies idempotent */
    MethodOptions_IdempotencyLevel[MethodOptions_IdempotencyLevel["NO_SIDE_EFFECTS"] = 1] = "NO_SIDE_EFFECTS";
    /** IDEMPOTENT - idempotent, but may have side effects */
    MethodOptions_IdempotencyLevel[MethodOptions_IdempotencyLevel["IDEMPOTENT"] = 2] = "IDEMPOTENT";
})(MethodOptions_IdempotencyLevel = exports.MethodOptions_IdempotencyLevel || (exports.MethodOptions_IdempotencyLevel = {}));
function methodOptions_IdempotencyLevelFromJSON(object) {
    switch (object) {
        case 0:
        case "IDEMPOTENCY_UNKNOWN":
            return MethodOptions_IdempotencyLevel.IDEMPOTENCY_UNKNOWN;
        case 1:
        case "NO_SIDE_EFFECTS":
            return MethodOptions_IdempotencyLevel.NO_SIDE_EFFECTS;
        case 2:
        case "IDEMPOTENT":
            return MethodOptions_IdempotencyLevel.IDEMPOTENT;
        default:
            throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum MethodOptions_IdempotencyLevel");
    }
}
exports.methodOptions_IdempotencyLevelFromJSON = methodOptions_IdempotencyLevelFromJSON;
function methodOptions_IdempotencyLevelToJSON(object) {
    switch (object) {
        case MethodOptions_IdempotencyLevel.IDEMPOTENCY_UNKNOWN:
            return "IDEMPOTENCY_UNKNOWN";
        case MethodOptions_IdempotencyLevel.NO_SIDE_EFFECTS:
            return "NO_SIDE_EFFECTS";
        case MethodOptions_IdempotencyLevel.IDEMPOTENT:
            return "IDEMPOTENT";
        default:
            throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum MethodOptions_IdempotencyLevel");
    }
}
exports.methodOptions_IdempotencyLevelToJSON = methodOptions_IdempotencyLevelToJSON;
function createBaseFileDescriptorSet() {
    return { file: [] };
}
exports.FileDescriptorSet = {
    fromJSON(object) {
        return { file: Array.isArray(object?.file) ? object.file.map((e) => exports.FileDescriptorProto.fromJSON(e)) : [] };
    },
    toJSON(message) {
        const obj = {};
        if (message.file) {
            obj.file = message.file.map((e) => e ? exports.FileDescriptorProto.toJSON(e) : undefined);
        }
        else {
            obj.file = [];
        }
        return obj;
    },
};
function createBaseFileDescriptorProto() {
    return {
        name: "",
        package: "",
        dependency: [],
        publicDependency: [],
        weakDependency: [],
        messageType: [],
        enumType: [],
        service: [],
        extension: [],
        options: undefined,
        sourceCodeInfo: undefined,
        syntax: "",
    };
}
exports.FileDescriptorProto = {
    fromJSON(object) {
        return {
            name: isSet(object.name) ? String(object.name) : "",
            package: isSet(object.package) ? String(object.package) : "",
            dependency: Array.isArray(object?.dependency) ? object.dependency.map((e) => String(e)) : [],
            publicDependency: Array.isArray(object?.publicDependency)
                ? object.publicDependency.map((e) => Number(e))
                : [],
            weakDependency: Array.isArray(object?.weakDependency) ? object.weakDependency.map((e) => Number(e)) : [],
            messageType: Array.isArray(object?.messageType)
                ? object.messageType.map((e) => exports.DescriptorProto.fromJSON(e))
                : [],
            enumType: Array.isArray(object?.enumType) ? object.enumType.map((e) => exports.EnumDescriptorProto.fromJSON(e)) : [],
            service: Array.isArray(object?.service) ? object.service.map((e) => exports.ServiceDescriptorProto.fromJSON(e)) : [],
            extension: Array.isArray(object?.extension)
                ? object.extension.map((e) => exports.FieldDescriptorProto.fromJSON(e))
                : [],
            options: isSet(object.options) ? exports.FileOptions.fromJSON(object.options) : undefined,
            sourceCodeInfo: isSet(object.sourceCodeInfo) ? exports.SourceCodeInfo.fromJSON(object.sourceCodeInfo) : undefined,
            syntax: isSet(object.syntax) ? String(object.syntax) : "",
        };
    },
    toJSON(message) {
        const obj = {};
        message.name !== undefined && (obj.name = message.name);
        message.package !== undefined && (obj.package = message.package);
        if (message.dependency) {
            obj.dependency = message.dependency.map((e) => e);
        }
        else {
            obj.dependency = [];
        }
        if (message.publicDependency) {
            obj.publicDependency = message.publicDependency.map((e) => Math.round(e));
        }
        else {
            obj.publicDependency = [];
        }
        if (message.weakDependency) {
            obj.weakDependency = message.weakDependency.map((e) => Math.round(e));
        }
        else {
            obj.weakDependency = [];
        }
        if (message.messageType) {
            obj.messageType = message.messageType.map((e) => e ? exports.DescriptorProto.toJSON(e) : undefined);
        }
        else {
            obj.messageType = [];
        }
        if (message.enumType) {
            obj.enumType = message.enumType.map((e) => e ? exports.EnumDescriptorProto.toJSON(e) : undefined);
        }
        else {
            obj.enumType = [];
        }
        if (message.service) {
            obj.service = message.service.map((e) => e ? exports.ServiceDescriptorProto.toJSON(e) : undefined);
        }
        else {
            obj.service = [];
        }
        if (message.extension) {
            obj.extension = message.extension.map((e) => e ? exports.FieldDescriptorProto.toJSON(e) : undefined);
        }
        else {
            obj.extension = [];
        }
        message.options !== undefined && (obj.options = message.options ? exports.FileOptions.toJSON(message.options) : undefined);
        message.sourceCodeInfo !== undefined &&
            (obj.sourceCodeInfo = message.sourceCodeInfo ? exports.SourceCodeInfo.toJSON(message.sourceCodeInfo) : undefined);
        message.syntax !== undefined && (obj.syntax = message.syntax);
        return obj;
    },
};
function createBaseDescriptorProto() {
    return {
        name: "",
        field: [],
        extension: [],
        nestedType: [],
        enumType: [],
        extensionRange: [],
        oneofDecl: [],
        options: undefined,
        reservedRange: [],
        reservedName: [],
    };
}
exports.DescriptorProto = {
    fromJSON(object) {
        return {
            name: isSet(object.name) ? String(object.name) : "",
            field: Array.isArray(object?.field) ? object.field.map((e) => exports.FieldDescriptorProto.fromJSON(e)) : [],
            extension: Array.isArray(object?.extension)
                ? object.extension.map((e) => exports.FieldDescriptorProto.fromJSON(e))
                : [],
            nestedType: Array.isArray(object?.nestedType)
                ? object.nestedType.map((e) => exports.DescriptorProto.fromJSON(e))
                : [],
            enumType: Array.isArray(object?.enumType) ? object.enumType.map((e) => exports.EnumDescriptorProto.fromJSON(e)) : [],
            extensionRange: Array.isArray(object?.extensionRange)
                ? object.extensionRange.map((e) => exports.DescriptorProto_ExtensionRange.fromJSON(e))
                : [],
            oneofDecl: Array.isArray(object?.oneofDecl)
                ? object.oneofDecl.map((e) => exports.OneofDescriptorProto.fromJSON(e))
                : [],
            options: isSet(object.options) ? exports.MessageOptions.fromJSON(object.options) : undefined,
            reservedRange: Array.isArray(object?.reservedRange)
                ? object.reservedRange.map((e) => exports.DescriptorProto_ReservedRange.fromJSON(e))
                : [],
            reservedName: Array.isArray(object?.reservedName) ? object.reservedName.map((e) => String(e)) : [],
        };
    },
    toJSON(message) {
        const obj = {};
        message.name !== undefined && (obj.name = message.name);
        if (message.field) {
            obj.field = message.field.map((e) => e ? exports.FieldDescriptorProto.toJSON(e) : undefined);
        }
        else {
            obj.field = [];
        }
        if (message.extension) {
            obj.extension = message.extension.map((e) => e ? exports.FieldDescriptorProto.toJSON(e) : undefined);
        }
        else {
            obj.extension = [];
        }
        if (message.nestedType) {
            obj.nestedType = message.nestedType.map((e) => e ? exports.DescriptorProto.toJSON(e) : undefined);
        }
        else {
            obj.nestedType = [];
        }
        if (message.enumType) {
            obj.enumType = message.enumType.map((e) => e ? exports.EnumDescriptorProto.toJSON(e) : undefined);
        }
        else {
            obj.enumType = [];
        }
        if (message.extensionRange) {
            obj.extensionRange = message.extensionRange.map((e) => e ? exports.DescriptorProto_ExtensionRange.toJSON(e) : undefined);
        }
        else {
            obj.extensionRange = [];
        }
        if (message.oneofDecl) {
            obj.oneofDecl = message.oneofDecl.map((e) => e ? exports.OneofDescriptorProto.toJSON(e) : undefined);
        }
        else {
            obj.oneofDecl = [];
        }
        message.options !== undefined &&
            (obj.options = message.options ? exports.MessageOptions.toJSON(message.options) : undefined);
        if (message.reservedRange) {
            obj.reservedRange = message.reservedRange.map((e) => e ? exports.DescriptorProto_ReservedRange.toJSON(e) : undefined);
        }
        else {
            obj.reservedRange = [];
        }
        if (message.reservedName) {
            obj.reservedName = message.reservedName.map((e) => e);
        }
        else {
            obj.reservedName = [];
        }
        return obj;
    },
};
function createBaseDescriptorProto_ExtensionRange() {
    return { start: 0, end: 0, options: undefined };
}
exports.DescriptorProto_ExtensionRange = {
    fromJSON(object) {
        return {
            start: isSet(object.start) ? Number(object.start) : 0,
            end: isSet(object.end) ? Number(object.end) : 0,
            options: isSet(object.options) ? exports.ExtensionRangeOptions.fromJSON(object.options) : undefined,
        };
    },
    toJSON(message) {
        const obj = {};
        message.start !== undefined && (obj.start = Math.round(message.start));
        message.end !== undefined && (obj.end = Math.round(message.end));
        message.options !== undefined &&
            (obj.options = message.options ? exports.ExtensionRangeOptions.toJSON(message.options) : undefined);
        return obj;
    },
};
function createBaseDescriptorProto_ReservedRange() {
    return { start: 0, end: 0 };
}
exports.DescriptorProto_ReservedRange = {
    fromJSON(object) {
        return { start: isSet(object.start) ? Number(object.start) : 0, end: isSet(object.end) ? Number(object.end) : 0 };
    },
    toJSON(message) {
        const obj = {};
        message.start !== undefined && (obj.start = Math.round(message.start));
        message.end !== undefined && (obj.end = Math.round(message.end));
        return obj;
    },
};
function createBaseExtensionRangeOptions() {
    return { uninterpretedOption: [] };
}
exports.ExtensionRangeOptions = {
    fromJSON(object) {
        return {
            uninterpretedOption: Array.isArray(object?.uninterpretedOption)
                ? object.uninterpretedOption.map((e) => exports.UninterpretedOption.fromJSON(e))
                : [],
        };
    },
    toJSON(message) {
        const obj = {};
        if (message.uninterpretedOption) {
            obj.uninterpretedOption = message.uninterpretedOption.map((e) => e ? exports.UninterpretedOption.toJSON(e) : undefined);
        }
        else {
            obj.uninterpretedOption = [];
        }
        return obj;
    },
};
function createBaseFieldDescriptorProto() {
    return {
        name: "",
        number: 0,
        label: 1,
        type: 1,
        typeName: "",
        extendee: "",
        defaultValue: "",
        oneofIndex: 0,
        jsonName: "",
        options: undefined,
        proto3Optional: false,
    };
}
exports.FieldDescriptorProto = {
    fromJSON(object) {
        return {
            name: isSet(object.name) ? String(object.name) : "",
            number: isSet(object.number) ? Number(object.number) : 0,
            label: isSet(object.label) ? fieldDescriptorProto_LabelFromJSON(object.label) : 1,
            type: isSet(object.type) ? fieldDescriptorProto_TypeFromJSON(object.type) : 1,
            typeName: isSet(object.typeName) ? String(object.typeName) : "",
            extendee: isSet(object.extendee) ? String(object.extendee) : "",
            defaultValue: isSet(object.defaultValue) ? String(object.defaultValue) : "",
            oneofIndex: isSet(object.oneofIndex) ? Number(object.oneofIndex) : 0,
            jsonName: isSet(object.jsonName) ? String(object.jsonName) : "",
            options: isSet(object.options) ? exports.FieldOptions.fromJSON(object.options) : undefined,
            proto3Optional: isSet(object.proto3Optional) ? Boolean(object.proto3Optional) : false,
        };
    },
    toJSON(message) {
        const obj = {};
        message.name !== undefined && (obj.name = message.name);
        message.number !== undefined && (obj.number = Math.round(message.number));
        message.label !== undefined && (obj.label = fieldDescriptorProto_LabelToJSON(message.label));
        message.type !== undefined && (obj.type = fieldDescriptorProto_TypeToJSON(message.type));
        message.typeName !== undefined && (obj.typeName = message.typeName);
        message.extendee !== undefined && (obj.extendee = message.extendee);
        message.defaultValue !== undefined && (obj.defaultValue = message.defaultValue);
        message.oneofIndex !== undefined && (obj.oneofIndex = Math.round(message.oneofIndex));
        message.jsonName !== undefined && (obj.jsonName = message.jsonName);
        message.options !== undefined && (obj.options = message.options ? exports.FieldOptions.toJSON(message.options) : undefined);
        message.proto3Optional !== undefined && (obj.proto3Optional = message.proto3Optional);
        return obj;
    },
};
function createBaseOneofDescriptorProto() {
    return { name: "", options: undefined };
}
exports.OneofDescriptorProto = {
    fromJSON(object) {
        return {
            name: isSet(object.name) ? String(object.name) : "",
            options: isSet(object.options) ? exports.OneofOptions.fromJSON(object.options) : undefined,
        };
    },
    toJSON(message) {
        const obj = {};
        message.name !== undefined && (obj.name = message.name);
        message.options !== undefined && (obj.options = message.options ? exports.OneofOptions.toJSON(message.options) : undefined);
        return obj;
    },
};
function createBaseEnumDescriptorProto() {
    return { name: "", value: [], options: undefined, reservedRange: [], reservedName: [] };
}
exports.EnumDescriptorProto = {
    fromJSON(object) {
        return {
            name: isSet(object.name) ? String(object.name) : "",
            value: Array.isArray(object?.value) ? object.value.map((e) => exports.EnumValueDescriptorProto.fromJSON(e)) : [],
            options: isSet(object.options) ? exports.EnumOptions.fromJSON(object.options) : undefined,
            reservedRange: Array.isArray(object?.reservedRange)
                ? object.reservedRange.map((e) => exports.EnumDescriptorProto_EnumReservedRange.fromJSON(e))
                : [],
            reservedName: Array.isArray(object?.reservedName)
                ? object.reservedName.map((e) => String(e))
                : [],
        };
    },
    toJSON(message) {
        const obj = {};
        message.name !== undefined && (obj.name = message.name);
        if (message.value) {
            obj.value = message.value.map((e) => e ? exports.EnumValueDescriptorProto.toJSON(e) : undefined);
        }
        else {
            obj.value = [];
        }
        message.options !== undefined && (obj.options = message.options ? exports.EnumOptions.toJSON(message.options) : undefined);
        if (message.reservedRange) {
            obj.reservedRange = message.reservedRange.map((e) => e ? exports.EnumDescriptorProto_EnumReservedRange.toJSON(e) : undefined);
        }
        else {
            obj.reservedRange = [];
        }
        if (message.reservedName) {
            obj.reservedName = message.reservedName.map((e) => e);
        }
        else {
            obj.reservedName = [];
        }
        return obj;
    },
};
function createBaseEnumDescriptorProto_EnumReservedRange() {
    return { start: 0, end: 0 };
}
exports.EnumDescriptorProto_EnumReservedRange = {
    fromJSON(object) {
        return { start: isSet(object.start) ? Number(object.start) : 0, end: isSet(object.end) ? Number(object.end) : 0 };
    },
    toJSON(message) {
        const obj = {};
        message.start !== undefined && (obj.start = Math.round(message.start));
        message.end !== undefined && (obj.end = Math.round(message.end));
        return obj;
    },
};
function createBaseEnumValueDescriptorProto() {
    return { name: "", number: 0, options: undefined };
}
exports.EnumValueDescriptorProto = {
    fromJSON(object) {
        return {
            name: isSet(object.name) ? String(object.name) : "",
            number: isSet(object.number) ? Number(object.number) : 0,
            options: isSet(object.options) ? exports.EnumValueOptions.fromJSON(object.options) : undefined,
        };
    },
    toJSON(message) {
        const obj = {};
        message.name !== undefined && (obj.name = message.name);
        message.number !== undefined && (obj.number = Math.round(message.number));
        message.options !== undefined &&
            (obj.options = message.options ? exports.EnumValueOptions.toJSON(message.options) : undefined);
        return obj;
    },
};
function createBaseServiceDescriptorProto() {
    return { name: "", method: [], options: undefined };
}
exports.ServiceDescriptorProto = {
    fromJSON(object) {
        return {
            name: isSet(object.name) ? String(object.name) : "",
            method: Array.isArray(object?.method) ? object.method.map((e) => exports.MethodDescriptorProto.fromJSON(e)) : [],
            options: isSet(object.options) ? exports.ServiceOptions.fromJSON(object.options) : undefined,
        };
    },
    toJSON(message) {
        const obj = {};
        message.name !== undefined && (obj.name = message.name);
        if (message.method) {
            obj.method = message.method.map((e) => e ? exports.MethodDescriptorProto.toJSON(e) : undefined);
        }
        else {
            obj.method = [];
        }
        message.options !== undefined &&
            (obj.options = message.options ? exports.ServiceOptions.toJSON(message.options) : undefined);
        return obj;
    },
};
function createBaseMethodDescriptorProto() {
    return {
        name: "",
        inputType: "",
        outputType: "",
        options: undefined,
        clientStreaming: false,
        serverStreaming: false,
    };
}
exports.MethodDescriptorProto = {
    fromJSON(object) {
        return {
            name: isSet(object.name) ? String(object.name) : "",
            inputType: isSet(object.inputType) ? String(object.inputType) : "",
            outputType: isSet(object.outputType) ? String(object.outputType) : "",
            options: isSet(object.options) ? exports.MethodOptions.fromJSON(object.options) : undefined,
            clientStreaming: isSet(object.clientStreaming) ? Boolean(object.clientStreaming) : false,
            serverStreaming: isSet(object.serverStreaming) ? Boolean(object.serverStreaming) : false,
        };
    },
    toJSON(message) {
        const obj = {};
        message.name !== undefined && (obj.name = message.name);
        message.inputType !== undefined && (obj.inputType = message.inputType);
        message.outputType !== undefined && (obj.outputType = message.outputType);
        message.options !== undefined &&
            (obj.options = message.options ? exports.MethodOptions.toJSON(message.options) : undefined);
        message.clientStreaming !== undefined && (obj.clientStreaming = message.clientStreaming);
        message.serverStreaming !== undefined && (obj.serverStreaming = message.serverStreaming);
        return obj;
    },
};
function createBaseFileOptions() {
    return {
        javaPackage: "",
        javaOuterClassname: "",
        javaMultipleFiles: false,
        javaGenerateEqualsAndHash: false,
        javaStringCheckUtf8: false,
        optimizeFor: 1,
        goPackage: "",
        ccGenericServices: false,
        javaGenericServices: false,
        pyGenericServices: false,
        phpGenericServices: false,
        deprecated: false,
        ccEnableArenas: false,
        objcClassPrefix: "",
        csharpNamespace: "",
        swiftPrefix: "",
        phpClassPrefix: "",
        phpNamespace: "",
        phpMetadataNamespace: "",
        rubyPackage: "",
        uninterpretedOption: [],
    };
}
exports.FileOptions = {
    fromJSON(object) {
        return {
            javaPackage: isSet(object.javaPackage) ? String(object.javaPackage) : "",
            javaOuterClassname: isSet(object.javaOuterClassname) ? String(object.javaOuterClassname) : "",
            javaMultipleFiles: isSet(object.javaMultipleFiles) ? Boolean(object.javaMultipleFiles) : false,
            javaGenerateEqualsAndHash: isSet(object.javaGenerateEqualsAndHash)
                ? Boolean(object.javaGenerateEqualsAndHash)
                : false,
            javaStringCheckUtf8: isSet(object.javaStringCheckUtf8) ? Boolean(object.javaStringCheckUtf8) : false,
            optimizeFor: isSet(object.optimizeFor) ? fileOptions_OptimizeModeFromJSON(object.optimizeFor) : 1,
            goPackage: isSet(object.goPackage) ? String(object.goPackage) : "",
            ccGenericServices: isSet(object.ccGenericServices) ? Boolean(object.ccGenericServices) : false,
            javaGenericServices: isSet(object.javaGenericServices) ? Boolean(object.javaGenericServices) : false,
            pyGenericServices: isSet(object.pyGenericServices) ? Boolean(object.pyGenericServices) : false,
            phpGenericServices: isSet(object.phpGenericServices) ? Boolean(object.phpGenericServices) : false,
            deprecated: isSet(object.deprecated) ? Boolean(object.deprecated) : false,
            ccEnableArenas: isSet(object.ccEnableArenas) ? Boolean(object.ccEnableArenas) : false,
            objcClassPrefix: isSet(object.objcClassPrefix) ? String(object.objcClassPrefix) : "",
            csharpNamespace: isSet(object.csharpNamespace) ? String(object.csharpNamespace) : "",
            swiftPrefix: isSet(object.swiftPrefix) ? String(object.swiftPrefix) : "",
            phpClassPrefix: isSet(object.phpClassPrefix) ? String(object.phpClassPrefix) : "",
            phpNamespace: isSet(object.phpNamespace) ? String(object.phpNamespace) : "",
            phpMetadataNamespace: isSet(object.phpMetadataNamespace) ? String(object.phpMetadataNamespace) : "",
            rubyPackage: isSet(object.rubyPackage) ? String(object.rubyPackage) : "",
            uninterpretedOption: Array.isArray(object?.uninterpretedOption)
                ? object.uninterpretedOption.map((e) => exports.UninterpretedOption.fromJSON(e))
                : [],
        };
    },
    toJSON(message) {
        const obj = {};
        message.javaPackage !== undefined && (obj.javaPackage = message.javaPackage);
        message.javaOuterClassname !== undefined && (obj.javaOuterClassname = message.javaOuterClassname);
        message.javaMultipleFiles !== undefined && (obj.javaMultipleFiles = message.javaMultipleFiles);
        message.javaGenerateEqualsAndHash !== undefined &&
            (obj.javaGenerateEqualsAndHash = message.javaGenerateEqualsAndHash);
        message.javaStringCheckUtf8 !== undefined && (obj.javaStringCheckUtf8 = message.javaStringCheckUtf8);
        message.optimizeFor !== undefined && (obj.optimizeFor = fileOptions_OptimizeModeToJSON(message.optimizeFor));
        message.goPackage !== undefined && (obj.goPackage = message.goPackage);
        message.ccGenericServices !== undefined && (obj.ccGenericServices = message.ccGenericServices);
        message.javaGenericServices !== undefined && (obj.javaGenericServices = message.javaGenericServices);
        message.pyGenericServices !== undefined && (obj.pyGenericServices = message.pyGenericServices);
        message.phpGenericServices !== undefined && (obj.phpGenericServices = message.phpGenericServices);
        message.deprecated !== undefined && (obj.deprecated = message.deprecated);
        message.ccEnableArenas !== undefined && (obj.ccEnableArenas = message.ccEnableArenas);
        message.objcClassPrefix !== undefined && (obj.objcClassPrefix = message.objcClassPrefix);
        message.csharpNamespace !== undefined && (obj.csharpNamespace = message.csharpNamespace);
        message.swiftPrefix !== undefined && (obj.swiftPrefix = message.swiftPrefix);
        message.phpClassPrefix !== undefined && (obj.phpClassPrefix = message.phpClassPrefix);
        message.phpNamespace !== undefined && (obj.phpNamespace = message.phpNamespace);
        message.phpMetadataNamespace !== undefined && (obj.phpMetadataNamespace = message.phpMetadataNamespace);
        message.rubyPackage !== undefined && (obj.rubyPackage = message.rubyPackage);
        if (message.uninterpretedOption) {
            obj.uninterpretedOption = message.uninterpretedOption.map((e) => e ? exports.UninterpretedOption.toJSON(e) : undefined);
        }
        else {
            obj.uninterpretedOption = [];
        }
        return obj;
    },
};
function createBaseMessageOptions() {
    return {
        messageSetWireFormat: false,
        noStandardDescriptorAccessor: false,
        deprecated: false,
        mapEntry: false,
        uninterpretedOption: [],
    };
}
exports.MessageOptions = {
    fromJSON(object) {
        return {
            messageSetWireFormat: isSet(object.messageSetWireFormat) ? Boolean(object.messageSetWireFormat) : false,
            noStandardDescriptorAccessor: isSet(object.noStandardDescriptorAccessor)
                ? Boolean(object.noStandardDescriptorAccessor)
                : false,
            deprecated: isSet(object.deprecated) ? Boolean(object.deprecated) : false,
            mapEntry: isSet(object.mapEntry) ? Boolean(object.mapEntry) : false,
            uninterpretedOption: Array.isArray(object?.uninterpretedOption)
                ? object.uninterpretedOption.map((e) => exports.UninterpretedOption.fromJSON(e))
                : [],
        };
    },
    toJSON(message) {
        const obj = {};
        message.messageSetWireFormat !== undefined && (obj.messageSetWireFormat = message.messageSetWireFormat);
        message.noStandardDescriptorAccessor !== undefined &&
            (obj.noStandardDescriptorAccessor = message.noStandardDescriptorAccessor);
        message.deprecated !== undefined && (obj.deprecated = message.deprecated);
        message.mapEntry !== undefined && (obj.mapEntry = message.mapEntry);
        if (message.uninterpretedOption) {
            obj.uninterpretedOption = message.uninterpretedOption.map((e) => e ? exports.UninterpretedOption.toJSON(e) : undefined);
        }
        else {
            obj.uninterpretedOption = [];
        }
        return obj;
    },
};
function createBaseFieldOptions() {
    return {
        ctype: 0,
        packed: false,
        jstype: 0,
        lazy: false,
        unverifiedLazy: false,
        deprecated: false,
        weak: false,
        uninterpretedOption: [],
    };
}
exports.FieldOptions = {
    fromJSON(object) {
        return {
            ctype: isSet(object.ctype) ? fieldOptions_CTypeFromJSON(object.ctype) : 0,
            packed: isSet(object.packed) ? Boolean(object.packed) : false,
            jstype: isSet(object.jstype) ? fieldOptions_JSTypeFromJSON(object.jstype) : 0,
            lazy: isSet(object.lazy) ? Boolean(object.lazy) : false,
            unverifiedLazy: isSet(object.unverifiedLazy) ? Boolean(object.unverifiedLazy) : false,
            deprecated: isSet(object.deprecated) ? Boolean(object.deprecated) : false,
            weak: isSet(object.weak) ? Boolean(object.weak) : false,
            uninterpretedOption: Array.isArray(object?.uninterpretedOption)
                ? object.uninterpretedOption.map((e) => exports.UninterpretedOption.fromJSON(e))
                : [],
        };
    },
    toJSON(message) {
        const obj = {};
        message.ctype !== undefined && (obj.ctype = fieldOptions_CTypeToJSON(message.ctype));
        message.packed !== undefined && (obj.packed = message.packed);
        message.jstype !== undefined && (obj.jstype = fieldOptions_JSTypeToJSON(message.jstype));
        message.lazy !== undefined && (obj.lazy = message.lazy);
        message.unverifiedLazy !== undefined && (obj.unverifiedLazy = message.unverifiedLazy);
        message.deprecated !== undefined && (obj.deprecated = message.deprecated);
        message.weak !== undefined && (obj.weak = message.weak);
        if (message.uninterpretedOption) {
            obj.uninterpretedOption = message.uninterpretedOption.map((e) => e ? exports.UninterpretedOption.toJSON(e) : undefined);
        }
        else {
            obj.uninterpretedOption = [];
        }
        return obj;
    },
};
function createBaseOneofOptions() {
    return { uninterpretedOption: [] };
}
exports.OneofOptions = {
    fromJSON(object) {
        return {
            uninterpretedOption: Array.isArray(object?.uninterpretedOption)
                ? object.uninterpretedOption.map((e) => exports.UninterpretedOption.fromJSON(e))
                : [],
        };
    },
    toJSON(message) {
        const obj = {};
        if (message.uninterpretedOption) {
            obj.uninterpretedOption = message.uninterpretedOption.map((e) => e ? exports.UninterpretedOption.toJSON(e) : undefined);
        }
        else {
            obj.uninterpretedOption = [];
        }
        return obj;
    },
};
function createBaseEnumOptions() {
    return { allowAlias: false, deprecated: false, uninterpretedOption: [] };
}
exports.EnumOptions = {
    fromJSON(object) {
        return {
            allowAlias: isSet(object.allowAlias) ? Boolean(object.allowAlias) : false,
            deprecated: isSet(object.deprecated) ? Boolean(object.deprecated) : false,
            uninterpretedOption: Array.isArray(object?.uninterpretedOption)
                ? object.uninterpretedOption.map((e) => exports.UninterpretedOption.fromJSON(e))
                : [],
        };
    },
    toJSON(message) {
        const obj = {};
        message.allowAlias !== undefined && (obj.allowAlias = message.allowAlias);
        message.deprecated !== undefined && (obj.deprecated = message.deprecated);
        if (message.uninterpretedOption) {
            obj.uninterpretedOption = message.uninterpretedOption.map((e) => e ? exports.UninterpretedOption.toJSON(e) : undefined);
        }
        else {
            obj.uninterpretedOption = [];
        }
        return obj;
    },
};
function createBaseEnumValueOptions() {
    return { deprecated: false, uninterpretedOption: [] };
}
exports.EnumValueOptions = {
    fromJSON(object) {
        return {
            deprecated: isSet(object.deprecated) ? Boolean(object.deprecated) : false,
            uninterpretedOption: Array.isArray(object?.uninterpretedOption)
                ? object.uninterpretedOption.map((e) => exports.UninterpretedOption.fromJSON(e))
                : [],
        };
    },
    toJSON(message) {
        const obj = {};
        message.deprecated !== undefined && (obj.deprecated = message.deprecated);
        if (message.uninterpretedOption) {
            obj.uninterpretedOption = message.uninterpretedOption.map((e) => e ? exports.UninterpretedOption.toJSON(e) : undefined);
        }
        else {
            obj.uninterpretedOption = [];
        }
        return obj;
    },
};
function createBaseServiceOptions() {
    return { deprecated: false, uninterpretedOption: [] };
}
exports.ServiceOptions = {
    fromJSON(object) {
        return {
            deprecated: isSet(object.deprecated) ? Boolean(object.deprecated) : false,
            uninterpretedOption: Array.isArray(object?.uninterpretedOption)
                ? object.uninterpretedOption.map((e) => exports.UninterpretedOption.fromJSON(e))
                : [],
        };
    },
    toJSON(message) {
        const obj = {};
        message.deprecated !== undefined && (obj.deprecated = message.deprecated);
        if (message.uninterpretedOption) {
            obj.uninterpretedOption = message.uninterpretedOption.map((e) => e ? exports.UninterpretedOption.toJSON(e) : undefined);
        }
        else {
            obj.uninterpretedOption = [];
        }
        return obj;
    },
};
function createBaseMethodOptions() {
    return { deprecated: false, idempotencyLevel: 0, uninterpretedOption: [] };
}
exports.MethodOptions = {
    fromJSON(object) {
        return {
            deprecated: isSet(object.deprecated) ? Boolean(object.deprecated) : false,
            idempotencyLevel: isSet(object.idempotencyLevel)
                ? methodOptions_IdempotencyLevelFromJSON(object.idempotencyLevel)
                : 0,
            uninterpretedOption: Array.isArray(object?.uninterpretedOption)
                ? object.uninterpretedOption.map((e) => exports.UninterpretedOption.fromJSON(e))
                : [],
        };
    },
    toJSON(message) {
        const obj = {};
        message.deprecated !== undefined && (obj.deprecated = message.deprecated);
        message.idempotencyLevel !== undefined &&
            (obj.idempotencyLevel = methodOptions_IdempotencyLevelToJSON(message.idempotencyLevel));
        if (message.uninterpretedOption) {
            obj.uninterpretedOption = message.uninterpretedOption.map((e) => e ? exports.UninterpretedOption.toJSON(e) : undefined);
        }
        else {
            obj.uninterpretedOption = [];
        }
        return obj;
    },
};
function createBaseUninterpretedOption() {
    return {
        name: [],
        identifierValue: "",
        positiveIntValue: "0",
        negativeIntValue: "0",
        doubleValue: 0,
        stringValue: Buffer.alloc(0),
        aggregateValue: "",
    };
}
exports.UninterpretedOption = {
    fromJSON(object) {
        return {
            name: Array.isArray(object?.name) ? object.name.map((e) => exports.UninterpretedOption_NamePart.fromJSON(e)) : [],
            identifierValue: isSet(object.identifierValue) ? String(object.identifierValue) : "",
            positiveIntValue: isSet(object.positiveIntValue) ? String(object.positiveIntValue) : "0",
            negativeIntValue: isSet(object.negativeIntValue) ? String(object.negativeIntValue) : "0",
            doubleValue: isSet(object.doubleValue) ? Number(object.doubleValue) : 0,
            stringValue: isSet(object.stringValue) ? Buffer.from(bytesFromBase64(object.stringValue)) : Buffer.alloc(0),
            aggregateValue: isSet(object.aggregateValue) ? String(object.aggregateValue) : "",
        };
    },
    toJSON(message) {
        const obj = {};
        if (message.name) {
            obj.name = message.name.map((e) => e ? exports.UninterpretedOption_NamePart.toJSON(e) : undefined);
        }
        else {
            obj.name = [];
        }
        message.identifierValue !== undefined && (obj.identifierValue = message.identifierValue);
        message.positiveIntValue !== undefined && (obj.positiveIntValue = message.positiveIntValue);
        message.negativeIntValue !== undefined && (obj.negativeIntValue = message.negativeIntValue);
        message.doubleValue !== undefined && (obj.doubleValue = message.doubleValue);
        message.stringValue !== undefined &&
            (obj.stringValue = base64FromBytes(message.stringValue !== undefined ? message.stringValue : Buffer.alloc(0)));
        message.aggregateValue !== undefined && (obj.aggregateValue = message.aggregateValue);
        return obj;
    },
};
function createBaseUninterpretedOption_NamePart() {
    return { namePart: "", isExtension: false };
}
exports.UninterpretedOption_NamePart = {
    fromJSON(object) {
        return {
            namePart: isSet(object.namePart) ? String(object.namePart) : "",
            isExtension: isSet(object.isExtension) ? Boolean(object.isExtension) : false,
        };
    },
    toJSON(message) {
        const obj = {};
        message.namePart !== undefined && (obj.namePart = message.namePart);
        message.isExtension !== undefined && (obj.isExtension = message.isExtension);
        return obj;
    },
};
function createBaseSourceCodeInfo() {
    return { location: [] };
}
exports.SourceCodeInfo = {
    fromJSON(object) {
        return {
            location: Array.isArray(object?.location)
                ? object.location.map((e) => exports.SourceCodeInfo_Location.fromJSON(e))
                : [],
        };
    },
    toJSON(message) {
        const obj = {};
        if (message.location) {
            obj.location = message.location.map((e) => e ? exports.SourceCodeInfo_Location.toJSON(e) : undefined);
        }
        else {
            obj.location = [];
        }
        return obj;
    },
};
function createBaseSourceCodeInfo_Location() {
    return { path: [], span: [], leadingComments: "", trailingComments: "", leadingDetachedComments: [] };
}
exports.SourceCodeInfo_Location = {
    fromJSON(object) {
        return {
            path: Array.isArray(object?.path) ? object.path.map((e) => Number(e)) : [],
            span: Array.isArray(object?.span) ? object.span.map((e) => Number(e)) : [],
            leadingComments: isSet(object.leadingComments) ? String(object.leadingComments) : "",
            trailingComments: isSet(object.trailingComments) ? String(object.trailingComments) : "",
            leadingDetachedComments: Array.isArray(object?.leadingDetachedComments)
                ? object.leadingDetachedComments.map((e) => String(e))
                : [],
        };
    },
    toJSON(message) {
        const obj = {};
        if (message.path) {
            obj.path = message.path.map((e) => Math.round(e));
        }
        else {
            obj.path = [];
        }
        if (message.span) {
            obj.span = message.span.map((e) => Math.round(e));
        }
        else {
            obj.span = [];
        }
        message.leadingComments !== undefined && (obj.leadingComments = message.leadingComments);
        message.trailingComments !== undefined && (obj.trailingComments = message.trailingComments);
        if (message.leadingDetachedComments) {
            obj.leadingDetachedComments = message.leadingDetachedComments.map((e) => e);
        }
        else {
            obj.leadingDetachedComments = [];
        }
        return obj;
    },
};
function createBaseGeneratedCodeInfo() {
    return { annotation: [] };
}
exports.GeneratedCodeInfo = {
    fromJSON(object) {
        return {
            annotation: Array.isArray(object?.annotation)
                ? object.annotation.map((e) => exports.GeneratedCodeInfo_Annotation.fromJSON(e))
                : [],
        };
    },
    toJSON(message) {
        const obj = {};
        if (message.annotation) {
            obj.annotation = message.annotation.map((e) => e ? exports.GeneratedCodeInfo_Annotation.toJSON(e) : undefined);
        }
        else {
            obj.annotation = [];
        }
        return obj;
    },
};
function createBaseGeneratedCodeInfo_Annotation() {
    return { path: [], sourceFile: "", begin: 0, end: 0 };
}
exports.GeneratedCodeInfo_Annotation = {
    fromJSON(object) {
        return {
            path: Array.isArray(object?.path) ? object.path.map((e) => Number(e)) : [],
            sourceFile: isSet(object.sourceFile) ? String(object.sourceFile) : "",
            begin: isSet(object.begin) ? Number(object.begin) : 0,
            end: isSet(object.end) ? Number(object.end) : 0,
        };
    },
    toJSON(message) {
        const obj = {};
        if (message.path) {
            obj.path = message.path.map((e) => Math.round(e));
        }
        else {
            obj.path = [];
        }
        message.sourceFile !== undefined && (obj.sourceFile = message.sourceFile);
        message.begin !== undefined && (obj.begin = Math.round(message.begin));
        message.end !== undefined && (obj.end = Math.round(message.end));
        return obj;
    },
};
var tsProtoGlobalThis = (() => {
    if (typeof globalThis !== "undefined") {
        return globalThis;
    }
    if (typeof self !== "undefined") {
        return self;
    }
    if (typeof window !== "undefined") {
        return window;
    }
    if (typeof global !== "undefined") {
        return global;
    }
    throw "Unable to locate global object";
})();
function bytesFromBase64(b64) {
    if (tsProtoGlobalThis.Buffer) {
        return Uint8Array.from(tsProtoGlobalThis.Buffer.from(b64, "base64"));
    }
    else {
        const bin = tsProtoGlobalThis.atob(b64);
        const arr = new Uint8Array(bin.length);
        for (let i = 0; i < bin.length; ++i) {
            arr[i] = bin.charCodeAt(i);
        }
        return arr;
    }
}
function base64FromBytes(arr) {
    if (tsProtoGlobalThis.Buffer) {
        return tsProtoGlobalThis.Buffer.from(arr).toString("base64");
    }
    else {
        const bin = [];
        arr.forEach((byte) => {
            bin.push(String.fromCharCode(byte));
        });
        return tsProtoGlobalThis.btoa(bin.join(""));
    }
}
function isSet(value) {
    return value !== null && value !== undefined;
}
PK~\(q@uu7@sigstore/protobuf-specs/dist/__generated__/envelope.jsnu["use strict";
/* eslint-disable */
Object.defineProperty(exports, "__esModule", { value: true });
exports.Signature = exports.Envelope = void 0;
function createBaseEnvelope() {
    return { payload: Buffer.alloc(0), payloadType: "", signatures: [] };
}
exports.Envelope = {
    fromJSON(object) {
        return {
            payload: isSet(object.payload) ? Buffer.from(bytesFromBase64(object.payload)) : Buffer.alloc(0),
            payloadType: isSet(object.payloadType) ? String(object.payloadType) : "",
            signatures: Array.isArray(object?.signatures) ? object.signatures.map((e) => exports.Signature.fromJSON(e)) : [],
        };
    },
    toJSON(message) {
        const obj = {};
        message.payload !== undefined &&
            (obj.payload = base64FromBytes(message.payload !== undefined ? message.payload : Buffer.alloc(0)));
        message.payloadType !== undefined && (obj.payloadType = message.payloadType);
        if (message.signatures) {
            obj.signatures = message.signatures.map((e) => e ? exports.Signature.toJSON(e) : undefined);
        }
        else {
            obj.signatures = [];
        }
        return obj;
    },
};
function createBaseSignature() {
    return { sig: Buffer.alloc(0), keyid: "" };
}
exports.Signature = {
    fromJSON(object) {
        return {
            sig: isSet(object.sig) ? Buffer.from(bytesFromBase64(object.sig)) : Buffer.alloc(0),
            keyid: isSet(object.keyid) ? String(object.keyid) : "",
        };
    },
    toJSON(message) {
        const obj = {};
        message.sig !== undefined && (obj.sig = base64FromBytes(message.sig !== undefined ? message.sig : Buffer.alloc(0)));
        message.keyid !== undefined && (obj.keyid = message.keyid);
        return obj;
    },
};
var tsProtoGlobalThis = (() => {
    if (typeof globalThis !== "undefined") {
        return globalThis;
    }
    if (typeof self !== "undefined") {
        return self;
    }
    if (typeof window !== "undefined") {
        return window;
    }
    if (typeof global !== "undefined") {
        return global;
    }
    throw "Unable to locate global object";
})();
function bytesFromBase64(b64) {
    if (tsProtoGlobalThis.Buffer) {
        return Uint8Array.from(tsProtoGlobalThis.Buffer.from(b64, "base64"));
    }
    else {
        const bin = tsProtoGlobalThis.atob(b64);
        const arr = new Uint8Array(bin.length);
        for (let i = 0; i < bin.length; ++i) {
            arr[i] = bin.charCodeAt(i);
        }
        return arr;
    }
}
function base64FromBytes(arr) {
    if (tsProtoGlobalThis.Buffer) {
        return tsProtoGlobalThis.Buffer.from(arr).toString("base64");
    }
    else {
        const bin = [];
        arr.forEach((byte) => {
            bin.push(String.fromCharCode(byte));
        });
        return tsProtoGlobalThis.btoa(bin.join(""));
    }
}
function isSet(value) {
    return value !== null && value !== undefined;
}
PK~\w,&@sigstore/protobuf-specs/dist/index.jsnu["use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
__exportStar(require("./__generated__/envelope"), exports);
__exportStar(require("./__generated__/sigstore_bundle"), exports);
__exportStar(require("./__generated__/sigstore_common"), exports);
__exportStar(require("./__generated__/sigstore_rekor"), exports);
__exportStar(require("./__generated__/sigstore_trustroot"), exports);
__exportStar(require("./__generated__/sigstore_verification"), exports);
PK~\j@CC@sigstore/sign/package.jsonnu[{
  "_id": "@sigstore/sign@2.3.2",
  "_inBundle": true,
  "_location": "/npm/@sigstore/sign",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm/sigstore"
  ],
  "author": {
    "name": "bdehamer@github.com"
  },
  "bugs": {
    "url": "https://github.com/sigstore/sigstore-js/issues"
  },
  "dependencies": {
    "@sigstore/bundle": "^2.3.2",
    "@sigstore/core": "^1.0.0",
    "@sigstore/protobuf-specs": "^0.3.2",
    "make-fetch-happen": "^13.0.1",
    "proc-log": "^4.2.0",
    "promise-retry": "^2.0.1"
  },
  "description": "Sigstore signing library",
  "devDependencies": {
    "@sigstore/jest": "^0.0.0",
    "@sigstore/mock": "^0.7.4",
    "@sigstore/rekor-types": "^2.0.0",
    "@types/make-fetch-happen": "^10.0.4",
    "@types/promise-retry": "^1.1.6"
  },
  "engines": {
    "node": "^16.14.0 || >=18.0.0"
  },
  "files": [
    "dist"
  ],
  "homepage": "https://github.com/sigstore/sigstore-js/tree/main/packages/sign#readme",
  "license": "Apache-2.0",
  "main": "dist/index.js",
  "name": "@sigstore/sign",
  "publishConfig": {
    "provenance": true
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/sigstore/sigstore-js.git"
  },
  "scripts": {
    "build": "tsc --build",
    "clean": "shx rm -rf dist *.tsbuildinfo",
    "test": "jest"
  },
  "types": "dist/index.d.ts",
  "version": "2.3.2"
}
PK~\"KW,W,@sigstore/sign/LICENSEnu[
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright 2023 The Sigstore Authors

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
PK~\#~,ss%@sigstore/sign/dist/external/fetch.jsnu["use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.fetchWithRetry = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const http2_1 = require("http2");
const make_fetch_happen_1 = __importDefault(require("make-fetch-happen"));
const proc_log_1 = require("proc-log");
const promise_retry_1 = __importDefault(require("promise-retry"));
const util_1 = require("../util");
const error_1 = require("./error");
const { HTTP2_HEADER_LOCATION, HTTP2_HEADER_CONTENT_TYPE, HTTP2_HEADER_USER_AGENT, HTTP_STATUS_INTERNAL_SERVER_ERROR, HTTP_STATUS_TOO_MANY_REQUESTS, HTTP_STATUS_REQUEST_TIMEOUT, } = http2_1.constants;
async function fetchWithRetry(url, options) {
    return (0, promise_retry_1.default)(async (retry, attemptNum) => {
        const method = options.method || 'POST';
        const headers = {
            [HTTP2_HEADER_USER_AGENT]: util_1.ua.getUserAgent(),
            ...options.headers,
        };
        const response = await (0, make_fetch_happen_1.default)(url, {
            method,
            headers,
            body: options.body,
            timeout: options.timeout,
            retry: false, // We're handling retries ourselves
        }).catch((reason) => {
            proc_log_1.log.http('fetch', `${method} ${url} attempt ${attemptNum} failed with ${reason}`);
            return retry(reason);
        });
        if (response.ok) {
            return response;
        }
        else {
            const error = await errorFromResponse(response);
            proc_log_1.log.http('fetch', `${method} ${url} attempt ${attemptNum} failed with ${response.status}`);
            if (retryable(response.status)) {
                return retry(error);
            }
            else {
                throw error;
            }
        }
    }, retryOpts(options.retry));
}
exports.fetchWithRetry = fetchWithRetry;
// Translate a Response into an HTTPError instance. This will attempt to parse
// the response body for a message, but will default to the statusText if none
// is found.
const errorFromResponse = async (response) => {
    let message = response.statusText;
    const location = response.headers?.get(HTTP2_HEADER_LOCATION) || undefined;
    const contentType = response.headers?.get(HTTP2_HEADER_CONTENT_TYPE);
    // If response type is JSON, try to parse the body for a message
    if (contentType?.includes('application/json')) {
        try {
            const body = await response.json();
            message = body.message || message;
        }
        catch (e) {
            // ignore
        }
    }
    return new error_1.HTTPError({
        status: response.status,
        message: message,
        location: location,
    });
};
// Determine if a status code is retryable. This includes 5xx errors, 408, and
// 429.
const retryable = (status) => [HTTP_STATUS_REQUEST_TIMEOUT, HTTP_STATUS_TOO_MANY_REQUESTS].includes(status) || status >= HTTP_STATUS_INTERNAL_SERVER_ERROR;
// Normalize the retry options to the format expected by promise-retry
const retryOpts = (retry) => {
    if (typeof retry === 'boolean') {
        return { retries: retry ? 1 : 0 };
    }
    else if (typeof retry === 'number') {
        return { retries: retry };
    }
    else {
        return { retries: 0, ...retry };
    }
};
PK~\Vl		&@sigstore/sign/dist/external/fulcio.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Fulcio = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const fetch_1 = require("./fetch");
/**
 * Fulcio API client.
 */
class Fulcio {
    constructor(options) {
        this.options = options;
    }
    async createSigningCertificate(request) {
        const { baseURL, retry, timeout } = this.options;
        const url = `${baseURL}/api/v2/signingCert`;
        const response = await (0, fetch_1.fetchWithRetry)(url, {
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(request),
            timeout,
            retry,
        });
        return response.json();
    }
}
exports.Fulcio = Fulcio;
PK~\P!
!
%@sigstore/sign/dist/external/rekor.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Rekor = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const fetch_1 = require("./fetch");
/**
 * Rekor API client.
 */
class Rekor {
    constructor(options) {
        this.options = options;
    }
    /**
     * Create a new entry in the Rekor log.
     * @param propsedEntry {ProposedEntry} Data to create a new entry
     * @returns {Promise} The created entry
     */
    async createEntry(propsedEntry) {
        const { baseURL, timeout, retry } = this.options;
        const url = `${baseURL}/api/v1/log/entries`;
        const response = await (0, fetch_1.fetchWithRetry)(url, {
            headers: {
                'Content-Type': 'application/json',
                Accept: 'application/json',
            },
            body: JSON.stringify(propsedEntry),
            timeout,
            retry,
        });
        const data = await response.json();
        return entryFromResponse(data);
    }
    /**
     * Get an entry from the Rekor log.
     * @param uuid {string} The UUID of the entry to retrieve
     * @returns {Promise} The retrieved entry
     */
    async getEntry(uuid) {
        const { baseURL, timeout, retry } = this.options;
        const url = `${baseURL}/api/v1/log/entries/${uuid}`;
        const response = await (0, fetch_1.fetchWithRetry)(url, {
            method: 'GET',
            headers: {
                Accept: 'application/json',
            },
            timeout,
            retry,
        });
        const data = await response.json();
        return entryFromResponse(data);
    }
}
exports.Rekor = Rekor;
// Unpack the response from the Rekor API into a more convenient format.
function entryFromResponse(data) {
    const entries = Object.entries(data);
    if (entries.length != 1) {
        throw new Error('Received multiple entries in Rekor response');
    }
    // Grab UUID and entry data from the response
    const [uuid, entry] = entries[0];
    return {
        ...entry,
        uuid,
    };
}
PK~\_KU%@sigstore/sign/dist/external/error.jsnu["use strict";
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.HTTPError = void 0;
class HTTPError extends Error {
    constructor({ status, message, location, }) {
        super(`(${status}) ${message}`);
        this.statusCode = status;
        this.location = location;
    }
}
exports.HTTPError = HTTPError;
PK~\;J#@sigstore/sign/dist/external/tsa.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TimestampAuthority = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const fetch_1 = require("./fetch");
class TimestampAuthority {
    constructor(options) {
        this.options = options;
    }
    async createTimestamp(request) {
        const { baseURL, timeout, retry } = this.options;
        const url = `${baseURL}/api/v1/timestamp`;
        const response = await (0, fetch_1.fetchWithRetry)(url, {
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(request),
            timeout,
            retry,
        });
        return response.buffer();
    }
}
exports.TimestampAuthority = TimestampAuthority;
PK~\da@sigstore/sign/dist/index.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TSAWitness = exports.RekorWitness = exports.DEFAULT_REKOR_URL = exports.FulcioSigner = exports.DEFAULT_FULCIO_URL = exports.CIContextProvider = exports.InternalError = exports.MessageSignatureBundleBuilder = exports.DSSEBundleBuilder = void 0;
var bundler_1 = require("./bundler");
Object.defineProperty(exports, "DSSEBundleBuilder", { enumerable: true, get: function () { return bundler_1.DSSEBundleBuilder; } });
Object.defineProperty(exports, "MessageSignatureBundleBuilder", { enumerable: true, get: function () { return bundler_1.MessageSignatureBundleBuilder; } });
var error_1 = require("./error");
Object.defineProperty(exports, "InternalError", { enumerable: true, get: function () { return error_1.InternalError; } });
var identity_1 = require("./identity");
Object.defineProperty(exports, "CIContextProvider", { enumerable: true, get: function () { return identity_1.CIContextProvider; } });
var signer_1 = require("./signer");
Object.defineProperty(exports, "DEFAULT_FULCIO_URL", { enumerable: true, get: function () { return signer_1.DEFAULT_FULCIO_URL; } });
Object.defineProperty(exports, "FulcioSigner", { enumerable: true, get: function () { return signer_1.FulcioSigner; } });
var witness_1 = require("./witness");
Object.defineProperty(exports, "DEFAULT_REKOR_URL", { enumerable: true, get: function () { return witness_1.DEFAULT_REKOR_URL; } });
Object.defineProperty(exports, "RekorWitness", { enumerable: true, get: function () { return witness_1.RekorWitness; } });
Object.defineProperty(exports, "TSAWitness", { enumerable: true, get: function () { return witness_1.TSAWitness; } });
PK~\VBVEE%@sigstore/sign/dist/identity/index.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CIContextProvider = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var ci_1 = require("./ci");
Object.defineProperty(exports, "CIContextProvider", { enumerable: true, get: function () { return ci_1.CIContextProvider; } });
PK~\-TMM(@sigstore/sign/dist/identity/provider.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
PK~\hN"@sigstore/sign/dist/identity/ci.jsnu["use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CIContextProvider = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const make_fetch_happen_1 = __importDefault(require("make-fetch-happen"));
// Collection of all the CI-specific providers we have implemented
const providers = [getGHAToken, getEnv];
/**
 * CIContextProvider is a composite identity provider which will iterate
 * over all of the CI-specific providers and return the token from the first
 * one that resolves.
 */
class CIContextProvider {
    /* istanbul ignore next */
    constructor(audience = 'sigstore') {
        this.audience = audience;
    }
    // Invoke all registered ProviderFuncs and return the value of whichever one
    // resolves first.
    async getToken() {
        return Promise.any(providers.map((getToken) => getToken(this.audience))).catch(() => Promise.reject('CI: no tokens available'));
    }
}
exports.CIContextProvider = CIContextProvider;
/**
 * getGHAToken can retrieve an OIDC token when running in a GitHub Actions
 * workflow
 */
async function getGHAToken(audience) {
    // Check to see if we're running in GitHub Actions
    if (!process.env.ACTIONS_ID_TOKEN_REQUEST_URL ||
        !process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN) {
        return Promise.reject('no token available');
    }
    // Construct URL to request token w/ appropriate audience
    const url = new URL(process.env.ACTIONS_ID_TOKEN_REQUEST_URL);
    url.searchParams.append('audience', audience);
    const response = await (0, make_fetch_happen_1.default)(url.href, {
        retry: 2,
        headers: {
            Accept: 'application/json',
            Authorization: `Bearer ${process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN}`,
        },
    });
    return response.json().then((data) => data.value);
}
/**
 * getEnv can retrieve an OIDC token from an environment variable.
 * This matches the behavior of https://github.com/sigstore/cosign/tree/main/pkg/providers/envvar
 */
async function getEnv() {
    if (!process.env.SIGSTORE_ID_TOKEN) {
        return Promise.reject('no token available');
    }
    return process.env.SIGSTORE_ID_TOKEN;
}
PK~\-TMM"@sigstore/sign/dist/types/fetch.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
PK~\]

*@sigstore/sign/dist/signer/fulcio/index.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FulcioSigner = exports.DEFAULT_FULCIO_URL = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const error_1 = require("../../error");
const util_1 = require("../../util");
const ca_1 = require("./ca");
const ephemeral_1 = require("./ephemeral");
exports.DEFAULT_FULCIO_URL = 'https://fulcio.sigstore.dev';
// Signer implementation which can be used to decorate another signer
// with a Fulcio-issued signing certificate for the signer's public key.
// Must be instantiated with an identity provider which can provide a JWT
// which represents the identity to be bound to the signing certificate.
class FulcioSigner {
    constructor(options) {
        this.ca = new ca_1.CAClient({
            ...options,
            fulcioBaseURL: options.fulcioBaseURL || /* istanbul ignore next */ exports.DEFAULT_FULCIO_URL,
        });
        this.identityProvider = options.identityProvider;
        this.keyHolder = options.keyHolder || new ephemeral_1.EphemeralSigner();
    }
    async sign(data) {
        // Retrieve identity token from the supplied identity provider
        const identityToken = await this.getIdentityToken();
        // Extract challenge claim from OIDC token
        let subject;
        try {
            subject = util_1.oidc.extractJWTSubject(identityToken);
        }
        catch (err) {
            throw new error_1.InternalError({
                code: 'IDENTITY_TOKEN_PARSE_ERROR',
                message: `invalid identity token: ${identityToken}`,
                cause: err,
            });
        }
        // Construct challenge value by signing the subject claim
        const challenge = await this.keyHolder.sign(Buffer.from(subject));
        if (challenge.key.$case !== 'publicKey') {
            throw new error_1.InternalError({
                code: 'CA_CREATE_SIGNING_CERTIFICATE_ERROR',
                message: 'unexpected format for signing key',
            });
        }
        // Create signing certificate
        const certificates = await this.ca.createSigningCertificate(identityToken, challenge.key.publicKey, challenge.signature);
        // Generate artifact signature
        const signature = await this.keyHolder.sign(data);
        // Specifically returning only the first certificate in the chain
        // as the key.
        return {
            signature: signature.signature,
            key: {
                $case: 'x509Certificate',
                certificate: certificates[0],
            },
        };
    }
    async getIdentityToken() {
        try {
            return await this.identityProvider.getToken();
        }
        catch (err) {
            throw new error_1.InternalError({
                code: 'IDENTITY_TOKEN_READ_ERROR',
                message: 'error retrieving identity token',
                cause: err,
            });
        }
    }
}
exports.FulcioSigner = FulcioSigner;
PK~\3	'@sigstore/sign/dist/signer/fulcio/ca.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CAClient = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const error_1 = require("../../error");
const fulcio_1 = require("../../external/fulcio");
class CAClient {
    constructor(options) {
        this.fulcio = new fulcio_1.Fulcio({
            baseURL: options.fulcioBaseURL,
            retry: options.retry,
            timeout: options.timeout,
        });
    }
    async createSigningCertificate(identityToken, publicKey, challenge) {
        const request = toCertificateRequest(identityToken, publicKey, challenge);
        try {
            const resp = await this.fulcio.createSigningCertificate(request);
            // Account for the fact that the response may contain either a
            // signedCertificateEmbeddedSct or a signedCertificateDetachedSct.
            const cert = resp.signedCertificateEmbeddedSct
                ? resp.signedCertificateEmbeddedSct
                : resp.signedCertificateDetachedSct;
            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
            return cert.chain.certificates;
        }
        catch (err) {
            (0, error_1.internalError)(err, 'CA_CREATE_SIGNING_CERTIFICATE_ERROR', 'error creating signing certificate');
        }
    }
}
exports.CAClient = CAClient;
function toCertificateRequest(identityToken, publicKey, challenge) {
    return {
        credentials: {
            oidcIdentityToken: identityToken,
        },
        publicKeyRequest: {
            publicKey: {
                algorithm: 'ECDSA',
                content: publicKey,
            },
            proofOfPossession: challenge.toString('base64'),
        },
    };
}
PK~\.@sigstore/sign/dist/signer/fulcio/ephemeral.jsnu["use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.EphemeralSigner = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const crypto_1 = __importDefault(require("crypto"));
const EC_KEYPAIR_TYPE = 'ec';
const P256_CURVE = 'P-256';
// Signer implementation which uses an ephemeral keypair to sign artifacts.
// The private key lives only in memory and is tied to the lifetime of the
// EphemeralSigner instance.
class EphemeralSigner {
    constructor() {
        this.keypair = crypto_1.default.generateKeyPairSync(EC_KEYPAIR_TYPE, {
            namedCurve: P256_CURVE,
        });
    }
    async sign(data) {
        const signature = crypto_1.default.sign(null, data, this.keypair.privateKey);
        const publicKey = this.keypair.publicKey
            .export({ format: 'pem', type: 'spki' })
            .toString('ascii');
        return {
            signature: signature,
            key: { $case: 'publicKey', publicKey },
        };
    }
}
exports.EphemeralSigner = EphemeralSigner;
PK~\#@sigstore/sign/dist/signer/index.jsnu["use strict";
/* istanbul ignore file */
Object.defineProperty(exports, "__esModule", { value: true });
exports.FulcioSigner = exports.DEFAULT_FULCIO_URL = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var fulcio_1 = require("./fulcio");
Object.defineProperty(exports, "DEFAULT_FULCIO_URL", { enumerable: true, get: function () { return fulcio_1.DEFAULT_FULCIO_URL; } });
Object.defineProperty(exports, "FulcioSigner", { enumerable: true, get: function () { return fulcio_1.FulcioSigner; } });
PK~\#$@sigstore/sign/dist/signer/signer.jsnu["use strict";
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
PK~\#@sigstore/sign/dist/bundler/base.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseBundleBuilder = void 0;
// BaseBundleBuilder is a base class for BundleBuilder implementations. It
// provides a the basic wokflow for signing and witnessing an artifact.
// Subclasses must implement the `package` method to assemble a valid bundle
// with the generated signature and verification material.
class BaseBundleBuilder {
    constructor(options) {
        this.signer = options.signer;
        this.witnesses = options.witnesses;
    }
    // Executes the signing/witnessing process for the given artifact.
    async create(artifact) {
        const signature = await this.prepare(artifact).then((blob) => this.signer.sign(blob));
        const bundle = await this.package(artifact, signature);
        // Invoke all of the witnesses in parallel
        const verificationMaterials = await Promise.all(this.witnesses.map((witness) => witness.testify(bundle.content, publicKey(signature.key))));
        // Collect the verification material from all of the witnesses
        const tlogEntryList = [];
        const timestampList = [];
        verificationMaterials.forEach(({ tlogEntries, rfc3161Timestamps }) => {
            tlogEntryList.push(...(tlogEntries ?? []));
            timestampList.push(...(rfc3161Timestamps ?? []));
        });
        // Merge the collected verification material into the bundle
        bundle.verificationMaterial.tlogEntries = tlogEntryList;
        bundle.verificationMaterial.timestampVerificationData = {
            rfc3161Timestamps: timestampList,
        };
        return bundle;
    }
    // Override this function to apply any pre-signing transformations to the
    // artifact. The returned buffer will be signed by the signer. The default
    // implementation simply returns the artifact data.
    async prepare(artifact) {
        return artifact.data;
    }
}
exports.BaseBundleBuilder = BaseBundleBuilder;
// Extracts the public key from a KeyMaterial. Returns either the public key
// or the certificate, depending on the type of key material.
function publicKey(key) {
    switch (key.$case) {
        case 'publicKey':
            return key.publicKey;
        case 'x509Certificate':
            return key.certificate;
    }
}
PK~\>J~||&@sigstore/sign/dist/bundler/message.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MessageSignatureBundleBuilder = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const base_1 = require("./base");
const bundle_1 = require("./bundle");
// BundleBuilder implementation for raw message signatures
class MessageSignatureBundleBuilder extends base_1.BaseBundleBuilder {
    constructor(options) {
        super(options);
    }
    async package(artifact, signature) {
        return (0, bundle_1.toMessageSignatureBundle)(artifact, signature);
    }
}
exports.MessageSignatureBundleBuilder = MessageSignatureBundleBuilder;
PK~\b`$@sigstore/sign/dist/bundler/index.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MessageSignatureBundleBuilder = exports.DSSEBundleBuilder = void 0;
var dsse_1 = require("./dsse");
Object.defineProperty(exports, "DSSEBundleBuilder", { enumerable: true, get: function () { return dsse_1.DSSEBundleBuilder; } });
var message_1 = require("./message");
Object.defineProperty(exports, "MessageSignatureBundleBuilder", { enumerable: true, get: function () { return message_1.MessageSignatureBundleBuilder; } });
PK~\;.#@sigstore/sign/dist/bundler/dsse.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DSSEBundleBuilder = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const util_1 = require("../util");
const base_1 = require("./base");
const bundle_1 = require("./bundle");
// BundleBuilder implementation for DSSE wrapped attestations
class DSSEBundleBuilder extends base_1.BaseBundleBuilder {
    constructor(options) {
        super(options);
        this.singleCertificate = options.singleCertificate ?? false;
    }
    // DSSE requires the artifact to be pre-encoded with the payload type
    // before the signature is generated.
    async prepare(artifact) {
        const a = artifactDefaults(artifact);
        return util_1.dsse.preAuthEncoding(a.type, a.data);
    }
    // Packages the artifact and signature into a DSSE bundle
    async package(artifact, signature) {
        return (0, bundle_1.toDSSEBundle)(artifactDefaults(artifact), signature, this.singleCertificate);
    }
}
exports.DSSEBundleBuilder = DSSEBundleBuilder;
// Defaults the artifact type to an empty string if not provided
function artifactDefaults(artifact) {
    return {
        ...artifact,
        type: artifact.type ?? '',
    };
}
PK~\h9%@sigstore/sign/dist/bundler/bundle.jsnu["use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.toDSSEBundle = exports.toMessageSignatureBundle = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const sigstore = __importStar(require("@sigstore/bundle"));
const util_1 = require("../util");
// Helper functions for assembling the parts of a Sigstore bundle
// Message signature bundle - $case: 'messageSignature'
function toMessageSignatureBundle(artifact, signature) {
    const digest = util_1.crypto.hash(artifact.data);
    return sigstore.toMessageSignatureBundle({
        digest,
        signature: signature.signature,
        certificate: signature.key.$case === 'x509Certificate'
            ? util_1.pem.toDER(signature.key.certificate)
            : undefined,
        keyHint: signature.key.$case === 'publicKey' ? signature.key.hint : undefined,
    });
}
exports.toMessageSignatureBundle = toMessageSignatureBundle;
// DSSE envelope bundle - $case: 'dsseEnvelope'
function toDSSEBundle(artifact, signature, singleCertificate) {
    return sigstore.toDSSEBundle({
        artifact: artifact.data,
        artifactType: artifact.type,
        signature: signature.signature,
        certificate: signature.key.$case === 'x509Certificate'
            ? util_1.pem.toDER(signature.key.certificate)
            : undefined,
        keyHint: signature.key.$case === 'publicKey' ? signature.key.hint : undefined,
        singleCertificate,
    });
}
exports.toDSSEBundle = toDSSEBundle;
PK~\iK@sigstore/sign/dist/error.jsnu["use strict";
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.internalError = exports.InternalError = void 0;
const error_1 = require("./external/error");
class InternalError extends Error {
    constructor({ code, message, cause, }) {
        super(message);
        this.name = this.constructor.name;
        this.cause = cause;
        this.code = code;
    }
}
exports.InternalError = InternalError;
function internalError(err, code, message) {
    if (err instanceof error_1.HTTPError) {
        message += ` - ${err.message}`;
    }
    throw new InternalError({
        code: code,
        message: message,
        cause: err,
    });
}
exports.internalError = internalError;
PK~\˯		!@sigstore/sign/dist/util/index.jsnu["use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ua = exports.oidc = exports.pem = exports.json = exports.encoding = exports.dsse = exports.crypto = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var core_1 = require("@sigstore/core");
Object.defineProperty(exports, "crypto", { enumerable: true, get: function () { return core_1.crypto; } });
Object.defineProperty(exports, "dsse", { enumerable: true, get: function () { return core_1.dsse; } });
Object.defineProperty(exports, "encoding", { enumerable: true, get: function () { return core_1.encoding; } });
Object.defineProperty(exports, "json", { enumerable: true, get: function () { return core_1.json; } });
Object.defineProperty(exports, "pem", { enumerable: true, get: function () { return core_1.pem; } });
exports.oidc = __importStar(require("./oidc"));
exports.ua = __importStar(require("./ua"));
PK~\}dd @sigstore/sign/dist/util/oidc.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractJWTSubject = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const core_1 = require("@sigstore/core");
function extractJWTSubject(jwt) {
    const parts = jwt.split('.', 3);
    const payload = JSON.parse(core_1.encoding.base64Decode(parts[1]));
    switch (payload.iss) {
        case 'https://accounts.google.com':
        case 'https://oauth2.sigstore.dev/auth':
            return payload.email;
        default:
            return payload.sub;
    }
}
exports.extractJWTSubject = extractJWTSubject;
PK~\j6@sigstore/sign/dist/util/ua.jsnu["use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getUserAgent = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const os_1 = __importDefault(require("os"));
// Format User-Agent:  /  ()
// source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent
const getUserAgent = () => {
    // eslint-disable-next-line @typescript-eslint/no-var-requires
    const packageVersion = require('../../package.json').version;
    const nodeVersion = process.version;
    const platformName = os_1.default.platform();
    const archName = os_1.default.arch();
    return `sigstore-js/${packageVersion} (Node ${nodeVersion}) (${platformName}/${archName})`;
};
exports.getUserAgent = getUserAgent;
PK~\r	כ$@sigstore/sign/dist/witness/index.jsnu["use strict";
/* istanbul ignore file */
Object.defineProperty(exports, "__esModule", { value: true });
exports.TSAWitness = exports.RekorWitness = exports.DEFAULT_REKOR_URL = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var tlog_1 = require("./tlog");
Object.defineProperty(exports, "DEFAULT_REKOR_URL", { enumerable: true, get: function () { return tlog_1.DEFAULT_REKOR_URL; } });
Object.defineProperty(exports, "RekorWitness", { enumerable: true, get: function () { return tlog_1.RekorWitness; } });
var tsa_1 = require("./tsa");
Object.defineProperty(exports, "TSAWitness", { enumerable: true, get: function () { return tsa_1.TSAWitness; } });
PK~\-TMM&@sigstore/sign/dist/witness/witness.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
PK~\{gg)@sigstore/sign/dist/witness/tlog/entry.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toProposedEntry = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const bundle_1 = require("@sigstore/bundle");
const util_1 = require("../../util");
function toProposedEntry(content, publicKey, 
// TODO: Remove this parameter once have completely switched to 'dsse' entries
entryType = 'intoto') {
    switch (content.$case) {
        case 'dsseEnvelope':
            // TODO: Remove this conditional once have completely switched to 'dsse' entries
            if (entryType === 'dsse') {
                return toProposedDSSEEntry(content.dsseEnvelope, publicKey);
            }
            return toProposedIntotoEntry(content.dsseEnvelope, publicKey);
        case 'messageSignature':
            return toProposedHashedRekordEntry(content.messageSignature, publicKey);
    }
}
exports.toProposedEntry = toProposedEntry;
// Returns a properly formatted Rekor "hashedrekord" entry for the given digest
// and signature
function toProposedHashedRekordEntry(messageSignature, publicKey) {
    const hexDigest = messageSignature.messageDigest.digest.toString('hex');
    const b64Signature = messageSignature.signature.toString('base64');
    const b64Key = util_1.encoding.base64Encode(publicKey);
    return {
        apiVersion: '0.0.1',
        kind: 'hashedrekord',
        spec: {
            data: {
                hash: {
                    algorithm: 'sha256',
                    value: hexDigest,
                },
            },
            signature: {
                content: b64Signature,
                publicKey: {
                    content: b64Key,
                },
            },
        },
    };
}
// Returns a properly formatted Rekor "dsse" entry for the given DSSE envelope
// and signature
function toProposedDSSEEntry(envelope, publicKey) {
    const envelopeJSON = JSON.stringify((0, bundle_1.envelopeToJSON)(envelope));
    const encodedKey = util_1.encoding.base64Encode(publicKey);
    return {
        apiVersion: '0.0.1',
        kind: 'dsse',
        spec: {
            proposedContent: {
                envelope: envelopeJSON,
                verifiers: [encodedKey],
            },
        },
    };
}
// Returns a properly formatted Rekor "intoto" entry for the given DSSE
// envelope and signature
function toProposedIntotoEntry(envelope, publicKey) {
    // Calculate the value for the payloadHash field in the Rekor entry
    const payloadHash = util_1.crypto.hash(envelope.payload).toString('hex');
    // Calculate the value for the hash field in the Rekor entry
    const envelopeHash = calculateDSSEHash(envelope, publicKey);
    // Collect values for re-creating the DSSE envelope.
    // Double-encode payload and signature cause that's what Rekor expects
    const payload = util_1.encoding.base64Encode(envelope.payload.toString('base64'));
    const sig = util_1.encoding.base64Encode(envelope.signatures[0].sig.toString('base64'));
    const keyid = envelope.signatures[0].keyid;
    const encodedKey = util_1.encoding.base64Encode(publicKey);
    // Create the envelope portion of the entry. Note the inclusion of the
    // publicKey in the signature struct is not a standard part of a DSSE
    // envelope, but is required by Rekor.
    const dsse = {
        payloadType: envelope.payloadType,
        payload: payload,
        signatures: [{ sig, publicKey: encodedKey }],
    };
    // If the keyid is an empty string, Rekor seems to remove it altogether. We
    // need to do the same here so that we can properly recreate the entry for
    // verification.
    if (keyid.length > 0) {
        dsse.signatures[0].keyid = keyid;
    }
    return {
        apiVersion: '0.0.2',
        kind: 'intoto',
        spec: {
            content: {
                envelope: dsse,
                hash: { algorithm: 'sha256', value: envelopeHash },
                payloadHash: { algorithm: 'sha256', value: payloadHash },
            },
        },
    };
}
// Calculates the hash of a DSSE envelope for inclusion in a Rekor entry.
// There is no standard way to do this, so the scheme we're using as as
// follows:
//  * payload is base64 encoded
//  * signature is base64 encoded (only the first signature is used)
//  * keyid is included ONLY if it is NOT an empty string
//  * The resulting JSON is canonicalized and hashed to a hex string
function calculateDSSEHash(envelope, publicKey) {
    const dsse = {
        payloadType: envelope.payloadType,
        payload: envelope.payload.toString('base64'),
        signatures: [
            { sig: envelope.signatures[0].sig.toString('base64'), publicKey },
        ],
    };
    // If the keyid is an empty string, Rekor seems to remove it altogether.
    if (envelope.signatures[0].keyid.length > 0) {
        dsse.signatures[0].keyid = envelope.signatures[0].keyid;
    }
    return util_1.crypto.hash(util_1.json.canonicalize(dsse)).toString('hex');
}
PK~\?N=:{{)@sigstore/sign/dist/witness/tlog/index.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RekorWitness = exports.DEFAULT_REKOR_URL = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const util_1 = require("../../util");
const client_1 = require("./client");
const entry_1 = require("./entry");
exports.DEFAULT_REKOR_URL = 'https://rekor.sigstore.dev';
class RekorWitness {
    constructor(options) {
        this.entryType = options.entryType;
        this.tlog = new client_1.TLogClient({
            ...options,
            rekorBaseURL: options.rekorBaseURL || /* istanbul ignore next */ exports.DEFAULT_REKOR_URL,
        });
    }
    async testify(content, publicKey) {
        const proposedEntry = (0, entry_1.toProposedEntry)(content, publicKey, this.entryType);
        const entry = await this.tlog.createEntry(proposedEntry);
        return toTransparencyLogEntry(entry);
    }
}
exports.RekorWitness = RekorWitness;
function toTransparencyLogEntry(entry) {
    const logID = Buffer.from(entry.logID, 'hex');
    // Parse entry body so we can extract the kind and version.
    const bodyJSON = util_1.encoding.base64Decode(entry.body);
    const entryBody = JSON.parse(bodyJSON);
    const promise = entry?.verification?.signedEntryTimestamp
        ? inclusionPromise(entry.verification.signedEntryTimestamp)
        : undefined;
    const proof = entry?.verification?.inclusionProof
        ? inclusionProof(entry.verification.inclusionProof)
        : undefined;
    const tlogEntry = {
        logIndex: entry.logIndex.toString(),
        logId: {
            keyId: logID,
        },
        integratedTime: entry.integratedTime.toString(),
        kindVersion: {
            kind: entryBody.kind,
            version: entryBody.apiVersion,
        },
        inclusionPromise: promise,
        inclusionProof: proof,
        canonicalizedBody: Buffer.from(entry.body, 'base64'),
    };
    return {
        tlogEntries: [tlogEntry],
    };
}
function inclusionPromise(promise) {
    return {
        signedEntryTimestamp: Buffer.from(promise, 'base64'),
    };
}
function inclusionProof(proof) {
    return {
        logIndex: proof.logIndex.toString(),
        treeSize: proof.treeSize.toString(),
        rootHash: Buffer.from(proof.rootHash, 'hex'),
        hashes: proof.hashes.map((h) => Buffer.from(h, 'hex')),
        checkpoint: {
            envelope: proof.checkpoint,
        },
    };
}
PK~\*@sigstore/sign/dist/witness/tlog/client.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TLogClient = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const error_1 = require("../../error");
const error_2 = require("../../external/error");
const rekor_1 = require("../../external/rekor");
class TLogClient {
    constructor(options) {
        this.fetchOnConflict = options.fetchOnConflict ?? false;
        this.rekor = new rekor_1.Rekor({
            baseURL: options.rekorBaseURL,
            retry: options.retry,
            timeout: options.timeout,
        });
    }
    async createEntry(proposedEntry) {
        let entry;
        try {
            entry = await this.rekor.createEntry(proposedEntry);
        }
        catch (err) {
            // If the entry already exists, fetch it (if enabled)
            if (entryExistsError(err) && this.fetchOnConflict) {
                // Grab the UUID of the existing entry from the location header
                /* istanbul ignore next */
                const uuid = err.location.split('/').pop() || '';
                try {
                    entry = await this.rekor.getEntry(uuid);
                }
                catch (err) {
                    (0, error_1.internalError)(err, 'TLOG_FETCH_ENTRY_ERROR', 'error fetching tlog entry');
                }
            }
            else {
                (0, error_1.internalError)(err, 'TLOG_CREATE_ENTRY_ERROR', 'error creating tlog entry');
            }
        }
        return entry;
    }
}
exports.TLogClient = TLogClient;
function entryExistsError(value) {
    return (value instanceof error_2.HTTPError &&
        value.statusCode === 409 &&
        value.location !== undefined);
}
PK~\Zw1ֿ(@sigstore/sign/dist/witness/tsa/index.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TSAWitness = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const client_1 = require("./client");
class TSAWitness {
    constructor(options) {
        this.tsa = new client_1.TSAClient({
            tsaBaseURL: options.tsaBaseURL,
            retry: options.retry,
            timeout: options.timeout,
        });
    }
    async testify(content) {
        const signature = extractSignature(content);
        const timestamp = await this.tsa.createTimestamp(signature);
        return {
            rfc3161Timestamps: [{ signedTimestamp: timestamp }],
        };
    }
}
exports.TSAWitness = TSAWitness;
function extractSignature(content) {
    switch (content.$case) {
        case 'dsseEnvelope':
            return content.dsseEnvelope.signatures[0].sig;
        case 'messageSignature':
            return content.messageSignature.signature;
    }
}
PK~\JZb)@sigstore/sign/dist/witness/tsa/client.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TSAClient = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const error_1 = require("../../error");
const tsa_1 = require("../../external/tsa");
const util_1 = require("../../util");
class TSAClient {
    constructor(options) {
        this.tsa = new tsa_1.TimestampAuthority({
            baseURL: options.tsaBaseURL,
            retry: options.retry,
            timeout: options.timeout,
        });
    }
    async createTimestamp(signature) {
        const request = {
            artifactHash: util_1.crypto.hash(signature).toString('base64'),
            hashAlgorithm: 'sha256',
        };
        try {
            return await this.tsa.createTimestamp(request);
        }
        catch (err) {
            (0, error_1.internalError)(err, 'TSA_CREATE_TIMESTAMP_ERROR', 'error creating timestamp');
        }
    }
}
exports.TSAClient = TSAClient;
PK~\[@sigstore/core/package.jsonnu[{
  "_id": "@sigstore/core@1.1.0",
  "_inBundle": true,
  "_location": "/npm/@sigstore/core",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm/@sigstore/sign",
    "/npm/@sigstore/verify",
    "/npm/sigstore"
  ],
  "author": {
    "name": "bdehamer@github.com"
  },
  "bugs": {
    "url": "https://github.com/sigstore/sigstore-js/issues"
  },
  "description": "Base library for Sigstore",
  "engines": {
    "node": "^16.14.0 || >=18.0.0"
  },
  "files": [
    "dist"
  ],
  "homepage": "https://github.com/sigstore/sigstore-js/tree/main/packages/core#readme",
  "license": "Apache-2.0",
  "main": "dist/index.js",
  "name": "@sigstore/core",
  "publishConfig": {
    "provenance": true
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/sigstore/sigstore-js.git"
  },
  "scripts": {
    "build": "tsc --build",
    "clean": "shx rm -rf dist *.tsbuildinfo",
    "test": "jest"
  },
  "types": "dist/index.d.ts",
  "version": "1.1.0"
}
PK~\"KW,W,@sigstore/core/LICENSEnu[
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright 2023 The Sigstore Authors

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
PK~\~;ͽT T (@sigstore/core/dist/rfc3161/timestamp.jsnu["use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RFC3161Timestamp = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const asn1_1 = require("../asn1");
const crypto = __importStar(require("../crypto"));
const oid_1 = require("../oid");
const error_1 = require("./error");
const tstinfo_1 = require("./tstinfo");
const OID_PKCS9_CONTENT_TYPE_SIGNED_DATA = '1.2.840.113549.1.7.2';
const OID_PKCS9_CONTENT_TYPE_TSTINFO = '1.2.840.113549.1.9.16.1.4';
const OID_PKCS9_MESSAGE_DIGEST_KEY = '1.2.840.113549.1.9.4';
class RFC3161Timestamp {
    constructor(asn1) {
        this.root = asn1;
    }
    static parse(der) {
        const asn1 = asn1_1.ASN1Obj.parseBuffer(der);
        return new RFC3161Timestamp(asn1);
    }
    get status() {
        return this.pkiStatusInfoObj.subs[0].toInteger();
    }
    get contentType() {
        return this.contentTypeObj.toOID();
    }
    get eContentType() {
        return this.eContentTypeObj.toOID();
    }
    get signingTime() {
        return this.tstInfo.genTime;
    }
    get signerIssuer() {
        return this.signerSidObj.subs[0].value;
    }
    get signerSerialNumber() {
        return this.signerSidObj.subs[1].value;
    }
    get signerDigestAlgorithm() {
        const oid = this.signerDigestAlgorithmObj.subs[0].toOID();
        return oid_1.SHA2_HASH_ALGOS[oid];
    }
    get signatureAlgorithm() {
        const oid = this.signatureAlgorithmObj.subs[0].toOID();
        return oid_1.ECDSA_SIGNATURE_ALGOS[oid];
    }
    get signatureValue() {
        return this.signatureValueObj.value;
    }
    get tstInfo() {
        // Need to unpack tstInfo from an OCTET STRING
        return new tstinfo_1.TSTInfo(this.eContentObj.subs[0].subs[0]);
    }
    verify(data, publicKey) {
        if (!this.timeStampTokenObj) {
            throw new error_1.RFC3161TimestampVerificationError('timeStampToken is missing');
        }
        // Check for expected ContentInfo content type
        if (this.contentType !== OID_PKCS9_CONTENT_TYPE_SIGNED_DATA) {
            throw new error_1.RFC3161TimestampVerificationError(`incorrect content type: ${this.contentType}`);
        }
        // Check for expected encapsulated content type
        if (this.eContentType !== OID_PKCS9_CONTENT_TYPE_TSTINFO) {
            throw new error_1.RFC3161TimestampVerificationError(`incorrect encapsulated content type: ${this.eContentType}`);
        }
        // Check that the tstInfo references the correct artifact
        this.tstInfo.verify(data);
        // Check that the signed message digest matches the tstInfo
        this.verifyMessageDigest();
        // Check that the signature is valid for the signed attributes
        this.verifySignature(publicKey);
    }
    verifyMessageDigest() {
        // Check that the tstInfo matches the signed data
        const tstInfoDigest = crypto.digest(this.signerDigestAlgorithm, this.tstInfo.raw);
        const expectedDigest = this.messageDigestAttributeObj.subs[1].subs[0].value;
        if (!crypto.bufferEqual(tstInfoDigest, expectedDigest)) {
            throw new error_1.RFC3161TimestampVerificationError('signed data does not match tstInfo');
        }
    }
    verifySignature(key) {
        // Encode the signed attributes for verification
        const signedAttrs = this.signedAttrsObj.toDER();
        signedAttrs[0] = 0x31; // Change context-specific tag to SET
        // Check that the signature is valid for the signed attributes
        const verified = crypto.verify(signedAttrs, key, this.signatureValue, this.signatureAlgorithm);
        if (!verified) {
            throw new error_1.RFC3161TimestampVerificationError('signature verification failed');
        }
    }
    // https://www.rfc-editor.org/rfc/rfc3161#section-2.4.2
    get pkiStatusInfoObj() {
        // pkiStatusInfo is the first element of the timestamp response sequence
        return this.root.subs[0];
    }
    // https://www.rfc-editor.org/rfc/rfc3161#section-2.4.2
    get timeStampTokenObj() {
        // timeStampToken is the first element of the timestamp response sequence
        return this.root.subs[1];
    }
    // https://datatracker.ietf.org/doc/html/rfc5652#section-3
    get contentTypeObj() {
        return this.timeStampTokenObj.subs[0];
    }
    // https://www.rfc-editor.org/rfc/rfc5652#section-3
    get signedDataObj() {
        const obj = this.timeStampTokenObj.subs.find((sub) => sub.tag.isContextSpecific(0x00));
        return obj.subs[0];
    }
    // https://datatracker.ietf.org/doc/html/rfc5652#section-5.1
    get encapContentInfoObj() {
        return this.signedDataObj.subs[2];
    }
    // https://datatracker.ietf.org/doc/html/rfc5652#section-5.1
    get signerInfosObj() {
        // SignerInfos is the last element of the signed data sequence
        const sd = this.signedDataObj;
        return sd.subs[sd.subs.length - 1];
    }
    // https://www.rfc-editor.org/rfc/rfc5652#section-5.1
    get signerInfoObj() {
        // Only supporting one signer
        return this.signerInfosObj.subs[0];
    }
    // https://datatracker.ietf.org/doc/html/rfc5652#section-5.2
    get eContentTypeObj() {
        return this.encapContentInfoObj.subs[0];
    }
    // https://datatracker.ietf.org/doc/html/rfc5652#section-5.2
    get eContentObj() {
        return this.encapContentInfoObj.subs[1];
    }
    // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3
    get signedAttrsObj() {
        const signedAttrs = this.signerInfoObj.subs.find((sub) => sub.tag.isContextSpecific(0x00));
        return signedAttrs;
    }
    // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3
    get messageDigestAttributeObj() {
        const messageDigest = this.signedAttrsObj.subs.find((sub) => sub.subs[0].tag.isOID() &&
            sub.subs[0].toOID() === OID_PKCS9_MESSAGE_DIGEST_KEY);
        return messageDigest;
    }
    // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3
    get signerSidObj() {
        return this.signerInfoObj.subs[1];
    }
    // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3
    get signerDigestAlgorithmObj() {
        // Signature is the 2nd element of the signerInfoObj object
        return this.signerInfoObj.subs[2];
    }
    // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3
    get signatureAlgorithmObj() {
        // Signature is the 4th element of the signerInfoObj object
        return this.signerInfoObj.subs[4];
    }
    // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3
    get signatureValueObj() {
        // Signature is the 6th element of the signerInfoObj object
        return this.signerInfoObj.subs[5];
    }
}
exports.RFC3161Timestamp = RFC3161Timestamp;
PK~\hOlWW$@sigstore/core/dist/rfc3161/index.jsnu["use strict";
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.RFC3161Timestamp = void 0;
var timestamp_1 = require("./timestamp");
Object.defineProperty(exports, "RFC3161Timestamp", { enumerable: true, get: function () { return timestamp_1.RFC3161Timestamp; } });
PK~\v*V&@sigstore/core/dist/rfc3161/tstinfo.jsnu["use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TSTInfo = void 0;
const crypto = __importStar(require("../crypto"));
const oid_1 = require("../oid");
const error_1 = require("./error");
class TSTInfo {
    constructor(asn1) {
        this.root = asn1;
    }
    get version() {
        return this.root.subs[0].toInteger();
    }
    get genTime() {
        return this.root.subs[4].toDate();
    }
    get messageImprintHashAlgorithm() {
        const oid = this.messageImprintObj.subs[0].subs[0].toOID();
        return oid_1.SHA2_HASH_ALGOS[oid];
    }
    get messageImprintHashedMessage() {
        return this.messageImprintObj.subs[1].value;
    }
    get raw() {
        return this.root.toDER();
    }
    verify(data) {
        const digest = crypto.digest(this.messageImprintHashAlgorithm, data);
        if (!crypto.bufferEqual(digest, this.messageImprintHashedMessage)) {
            throw new error_1.RFC3161TimestampVerificationError('message imprint does not match artifact');
        }
    }
    // https://www.rfc-editor.org/rfc/rfc3161#section-2.4.2
    get messageImprintObj() {
        return this.root.subs[2];
    }
}
exports.TSTInfo = TSTInfo;
PK~\9,BB$@sigstore/core/dist/rfc3161/error.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RFC3161TimestampVerificationError = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
class RFC3161TimestampVerificationError extends Error {
}
exports.RFC3161TimestampVerificationError = RFC3161TimestampVerificationError;
PK~\[dOO@sigstore/core/dist/pem.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fromDER = exports.toDER = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const PEM_HEADER = /-----BEGIN (.*)-----/;
const PEM_FOOTER = /-----END (.*)-----/;
function toDER(certificate) {
    let der = '';
    certificate.split('\n').forEach((line) => {
        if (line.match(PEM_HEADER) || line.match(PEM_FOOTER)) {
            return;
        }
        der += line;
    });
    return Buffer.from(der, 'base64');
}
exports.toDER = toDER;
// Translates a DER-encoded buffer into a PEM-encoded string. Standard PEM
// encoding dictates that each certificate should have a trailing newline after
// the footer.
function fromDER(certificate, type = 'CERTIFICATE') {
    // Base64-encode the certificate.
    const der = certificate.toString('base64');
    // Split the certificate into lines of 64 characters.
    const lines = der.match(/.{1,64}/g) || '';
    return [`-----BEGIN ${type}-----`, ...lines, `-----END ${type}-----`]
        .join('\n')
        .concat('\n');
}
exports.fromDER = fromDER;
PK~\@		@sigstore/core/dist/crypto.jsnu["use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.bufferEqual = exports.verify = exports.hash = exports.digest = exports.createPublicKey = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const crypto_1 = __importDefault(require("crypto"));
const SHA256_ALGORITHM = 'sha256';
function createPublicKey(key, type = 'spki') {
    if (typeof key === 'string') {
        return crypto_1.default.createPublicKey(key);
    }
    else {
        return crypto_1.default.createPublicKey({ key, format: 'der', type: type });
    }
}
exports.createPublicKey = createPublicKey;
function digest(algorithm, ...data) {
    const hash = crypto_1.default.createHash(algorithm);
    for (const d of data) {
        hash.update(d);
    }
    return hash.digest();
}
exports.digest = digest;
// TODO: deprecate this in favor of digest()
function hash(...data) {
    const hash = crypto_1.default.createHash(SHA256_ALGORITHM);
    for (const d of data) {
        hash.update(d);
    }
    return hash.digest();
}
exports.hash = hash;
function verify(data, key, signature, algorithm) {
    // The try/catch is to work around an issue in Node 14.x where verify throws
    // an error in some scenarios if the signature is invalid.
    try {
        return crypto_1.default.verify(algorithm, data, key, signature);
    }
    catch (e) {
        /* istanbul ignore next */
        return false;
    }
}
exports.verify = verify;
function bufferEqual(a, b) {
    try {
        return crypto_1.default.timingSafeEqual(a, b);
    }
    catch {
        /* istanbul ignore next */
        return false;
    }
}
exports.bufferEqual = bufferEqual;
PK~\,@sigstore/core/dist/index.jsnu["use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.X509SCTExtension = exports.X509Certificate = exports.EXTENSION_OID_SCT = exports.ByteStream = exports.RFC3161Timestamp = exports.pem = exports.json = exports.encoding = exports.dsse = exports.crypto = exports.ASN1Obj = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var asn1_1 = require("./asn1");
Object.defineProperty(exports, "ASN1Obj", { enumerable: true, get: function () { return asn1_1.ASN1Obj; } });
exports.crypto = __importStar(require("./crypto"));
exports.dsse = __importStar(require("./dsse"));
exports.encoding = __importStar(require("./encoding"));
exports.json = __importStar(require("./json"));
exports.pem = __importStar(require("./pem"));
var rfc3161_1 = require("./rfc3161");
Object.defineProperty(exports, "RFC3161Timestamp", { enumerable: true, get: function () { return rfc3161_1.RFC3161Timestamp; } });
var stream_1 = require("./stream");
Object.defineProperty(exports, "ByteStream", { enumerable: true, get: function () { return stream_1.ByteStream; } });
var x509_1 = require("./x509");
Object.defineProperty(exports, "EXTENSION_OID_SCT", { enumerable: true, get: function () { return x509_1.EXTENSION_OID_SCT; } });
Object.defineProperty(exports, "X509Certificate", { enumerable: true, get: function () { return x509_1.X509Certificate; } });
Object.defineProperty(exports, "X509SCTExtension", { enumerable: true, get: function () { return x509_1.X509SCTExtension; } });
PK~\CZ@sigstore/core/dist/dsse.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.preAuthEncoding = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const PAE_PREFIX = 'DSSEv1';
// DSSE Pre-Authentication Encoding
function preAuthEncoding(payloadType, payload) {
    const prefix = [
        PAE_PREFIX,
        payloadType.length,
        payloadType,
        payload.length,
        '',
    ].join(' ');
    return Buffer.concat([Buffer.from(prefix, 'ascii'), payload]);
}
exports.preAuthEncoding = preAuthEncoding;
PK~\>+## @sigstore/core/dist/x509/cert.jsnu["use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.X509Certificate = exports.EXTENSION_OID_SCT = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const asn1_1 = require("../asn1");
const crypto = __importStar(require("../crypto"));
const oid_1 = require("../oid");
const pem = __importStar(require("../pem"));
const ext_1 = require("./ext");
const EXTENSION_OID_SUBJECT_KEY_ID = '2.5.29.14';
const EXTENSION_OID_KEY_USAGE = '2.5.29.15';
const EXTENSION_OID_SUBJECT_ALT_NAME = '2.5.29.17';
const EXTENSION_OID_BASIC_CONSTRAINTS = '2.5.29.19';
const EXTENSION_OID_AUTHORITY_KEY_ID = '2.5.29.35';
exports.EXTENSION_OID_SCT = '1.3.6.1.4.1.11129.2.4.2';
class X509Certificate {
    constructor(asn1) {
        this.root = asn1;
    }
    static parse(cert) {
        const der = typeof cert === 'string' ? pem.toDER(cert) : cert;
        const asn1 = asn1_1.ASN1Obj.parseBuffer(der);
        return new X509Certificate(asn1);
    }
    get tbsCertificate() {
        return this.tbsCertificateObj;
    }
    get version() {
        // version number is the first element of the version context specific tag
        const ver = this.versionObj.subs[0].toInteger();
        return `v${(ver + BigInt(1)).toString()}`;
    }
    get serialNumber() {
        return this.serialNumberObj.value;
    }
    get notBefore() {
        // notBefore is the first element of the validity sequence
        return this.validityObj.subs[0].toDate();
    }
    get notAfter() {
        // notAfter is the second element of the validity sequence
        return this.validityObj.subs[1].toDate();
    }
    get issuer() {
        return this.issuerObj.value;
    }
    get subject() {
        return this.subjectObj.value;
    }
    get publicKey() {
        return this.subjectPublicKeyInfoObj.toDER();
    }
    get signatureAlgorithm() {
        const oid = this.signatureAlgorithmObj.subs[0].toOID();
        return oid_1.ECDSA_SIGNATURE_ALGOS[oid];
    }
    get signatureValue() {
        // Signature value is a bit string, so we need to skip the first byte
        return this.signatureValueObj.value.subarray(1);
    }
    get subjectAltName() {
        const ext = this.extSubjectAltName;
        return ext?.uri || ext?.rfc822Name;
    }
    get extensions() {
        // The extension list is the first (and only) element of the extensions
        // context specific tag
        const extSeq = this.extensionsObj?.subs[0];
        return extSeq?.subs || /* istanbul ignore next */ [];
    }
    get extKeyUsage() {
        const ext = this.findExtension(EXTENSION_OID_KEY_USAGE);
        return ext ? new ext_1.X509KeyUsageExtension(ext) : undefined;
    }
    get extBasicConstraints() {
        const ext = this.findExtension(EXTENSION_OID_BASIC_CONSTRAINTS);
        return ext ? new ext_1.X509BasicConstraintsExtension(ext) : undefined;
    }
    get extSubjectAltName() {
        const ext = this.findExtension(EXTENSION_OID_SUBJECT_ALT_NAME);
        return ext ? new ext_1.X509SubjectAlternativeNameExtension(ext) : undefined;
    }
    get extAuthorityKeyID() {
        const ext = this.findExtension(EXTENSION_OID_AUTHORITY_KEY_ID);
        return ext ? new ext_1.X509AuthorityKeyIDExtension(ext) : undefined;
    }
    get extSubjectKeyID() {
        const ext = this.findExtension(EXTENSION_OID_SUBJECT_KEY_ID);
        return ext
            ? new ext_1.X509SubjectKeyIDExtension(ext)
            : /* istanbul ignore next */ undefined;
    }
    get extSCT() {
        const ext = this.findExtension(exports.EXTENSION_OID_SCT);
        return ext ? new ext_1.X509SCTExtension(ext) : undefined;
    }
    get isCA() {
        const ca = this.extBasicConstraints?.isCA || false;
        // If the KeyUsage extension is present, keyCertSign must be set
        if (this.extKeyUsage) {
            ca && this.extKeyUsage.keyCertSign;
        }
        return ca;
    }
    extension(oid) {
        const ext = this.findExtension(oid);
        return ext ? new ext_1.X509Extension(ext) : undefined;
    }
    verify(issuerCertificate) {
        // Use the issuer's public key if provided, otherwise use the subject's
        const publicKey = issuerCertificate?.publicKey || this.publicKey;
        const key = crypto.createPublicKey(publicKey);
        return crypto.verify(this.tbsCertificate.toDER(), key, this.signatureValue, this.signatureAlgorithm);
    }
    validForDate(date) {
        return this.notBefore <= date && date <= this.notAfter;
    }
    equals(other) {
        return this.root.toDER().equals(other.root.toDER());
    }
    // Creates a copy of the certificate with a new buffer
    clone() {
        const der = this.root.toDER();
        const clone = Buffer.alloc(der.length);
        der.copy(clone);
        return X509Certificate.parse(clone);
    }
    findExtension(oid) {
        // Find the extension with the given OID. The OID will always be the first
        // element of the extension sequence
        return this.extensions.find((ext) => ext.subs[0].toOID() === oid);
    }
    /////////////////////////////////////////////////////////////////////////////
    // The following properties use the documented x509 structure to locate the
    // desired ASN.1 object
    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1
    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.1.1
    get tbsCertificateObj() {
        // tbsCertificate is the first element of the certificate sequence
        return this.root.subs[0];
    }
    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.1.2
    get signatureAlgorithmObj() {
        // signatureAlgorithm is the second element of the certificate sequence
        return this.root.subs[1];
    }
    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.1.3
    get signatureValueObj() {
        // signatureValue is the third element of the certificate sequence
        return this.root.subs[2];
    }
    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.1
    get versionObj() {
        // version is the first element of the tbsCertificate sequence
        return this.tbsCertificateObj.subs[0];
    }
    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.2
    get serialNumberObj() {
        // serialNumber is the second element of the tbsCertificate sequence
        return this.tbsCertificateObj.subs[1];
    }
    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.4
    get issuerObj() {
        // issuer is the fourth element of the tbsCertificate sequence
        return this.tbsCertificateObj.subs[3];
    }
    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.5
    get validityObj() {
        // version is the fifth element of the tbsCertificate sequence
        return this.tbsCertificateObj.subs[4];
    }
    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.6
    get subjectObj() {
        // subject is the sixth element of the tbsCertificate sequence
        return this.tbsCertificateObj.subs[5];
    }
    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.7
    get subjectPublicKeyInfoObj() {
        // subjectPublicKeyInfo is the seventh element of the tbsCertificate sequence
        return this.tbsCertificateObj.subs[6];
    }
    // Extensions can't be located by index because their position varies. Instead,
    // we need to find the extensions context specific tag
    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.9
    get extensionsObj() {
        return this.tbsCertificateObj.subs.find((sub) => sub.tag.isContextSpecific(0x03));
    }
}
exports.X509Certificate = X509Certificate;
PK~\<!@sigstore/core/dist/x509/index.jsnu["use strict";
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.X509SCTExtension = exports.X509Certificate = exports.EXTENSION_OID_SCT = void 0;
var cert_1 = require("./cert");
Object.defineProperty(exports, "EXTENSION_OID_SCT", { enumerable: true, get: function () { return cert_1.EXTENSION_OID_SCT; } });
Object.defineProperty(exports, "X509Certificate", { enumerable: true, get: function () { return cert_1.X509Certificate; } });
var ext_1 = require("./ext");
Object.defineProperty(exports, "X509SCTExtension", { enumerable: true, get: function () { return ext_1.X509SCTExtension; } });
PK~\g,@sigstore/core/dist/x509/ext.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.X509SCTExtension = exports.X509SubjectKeyIDExtension = exports.X509AuthorityKeyIDExtension = exports.X509SubjectAlternativeNameExtension = exports.X509KeyUsageExtension = exports.X509BasicConstraintsExtension = exports.X509Extension = void 0;
const stream_1 = require("../stream");
const sct_1 = require("./sct");
// https://www.rfc-editor.org/rfc/rfc5280#section-4.1
class X509Extension {
    constructor(asn1) {
        this.root = asn1;
    }
    get oid() {
        return this.root.subs[0].toOID();
    }
    get critical() {
        // The critical field is optional and will be the second element of the
        // extension sequence if present. Default to false if not present.
        return this.root.subs.length === 3 ? this.root.subs[1].toBoolean() : false;
    }
    get value() {
        return this.extnValueObj.value;
    }
    get valueObj() {
        return this.extnValueObj;
    }
    get extnValueObj() {
        // The extnValue field will be the last element of the extension sequence
        return this.root.subs[this.root.subs.length - 1];
    }
}
exports.X509Extension = X509Extension;
// https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.9
class X509BasicConstraintsExtension extends X509Extension {
    get isCA() {
        return this.sequence.subs[0]?.toBoolean() ?? false;
    }
    get pathLenConstraint() {
        return this.sequence.subs.length > 1
            ? this.sequence.subs[1].toInteger()
            : undefined;
    }
    // The extnValue field contains a single sequence wrapping the isCA and
    // pathLenConstraint.
    get sequence() {
        return this.extnValueObj.subs[0];
    }
}
exports.X509BasicConstraintsExtension = X509BasicConstraintsExtension;
// https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.3
class X509KeyUsageExtension extends X509Extension {
    get digitalSignature() {
        return this.bitString[0] === 1;
    }
    get keyCertSign() {
        return this.bitString[5] === 1;
    }
    get crlSign() {
        return this.bitString[6] === 1;
    }
    // The extnValue field contains a single bit string which is a bit mask
    // indicating which key usages are enabled.
    get bitString() {
        return this.extnValueObj.subs[0].toBitString();
    }
}
exports.X509KeyUsageExtension = X509KeyUsageExtension;
// https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.6
class X509SubjectAlternativeNameExtension extends X509Extension {
    get rfc822Name() {
        return this.findGeneralName(0x01)?.value.toString('ascii');
    }
    get uri() {
        return this.findGeneralName(0x06)?.value.toString('ascii');
    }
    // Retrieve the value of an otherName with the given OID.
    otherName(oid) {
        const otherName = this.findGeneralName(0x00);
        if (otherName === undefined) {
            return undefined;
        }
        // The otherName is a sequence containing an OID and a value.
        // Need to check that the OID matches the one we're looking for.
        const otherNameOID = otherName.subs[0].toOID();
        if (otherNameOID !== oid) {
            return undefined;
        }
        // The otherNameValue is a sequence containing the actual value.
        const otherNameValue = otherName.subs[1];
        return otherNameValue.subs[0].value.toString('ascii');
    }
    findGeneralName(tag) {
        return this.generalNames.find((gn) => gn.tag.isContextSpecific(tag));
    }
    // The extnValue field contains a sequence of GeneralNames.
    get generalNames() {
        return this.extnValueObj.subs[0].subs;
    }
}
exports.X509SubjectAlternativeNameExtension = X509SubjectAlternativeNameExtension;
// https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.1
class X509AuthorityKeyIDExtension extends X509Extension {
    get keyIdentifier() {
        return this.findSequenceMember(0x00)?.value;
    }
    findSequenceMember(tag) {
        return this.sequence.subs.find((el) => el.tag.isContextSpecific(tag));
    }
    // The extnValue field contains a single sequence wrapping the keyIdentifier
    get sequence() {
        return this.extnValueObj.subs[0];
    }
}
exports.X509AuthorityKeyIDExtension = X509AuthorityKeyIDExtension;
// https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.2
class X509SubjectKeyIDExtension extends X509Extension {
    get keyIdentifier() {
        return this.extnValueObj.subs[0].value;
    }
}
exports.X509SubjectKeyIDExtension = X509SubjectKeyIDExtension;
// https://www.rfc-editor.org/rfc/rfc6962#section-3.3
class X509SCTExtension extends X509Extension {
    constructor(asn1) {
        super(asn1);
    }
    get signedCertificateTimestamps() {
        const buf = this.extnValueObj.subs[0].value;
        const stream = new stream_1.ByteStream(buf);
        // The overall list length is encoded in the first two bytes -- note this
        // is the length of the list in bytes, NOT the number of SCTs in the list
        const end = stream.getUint16() + 2;
        const sctList = [];
        while (stream.position < end) {
            // Read the length of the next SCT
            const sctLength = stream.getUint16();
            // Slice out the bytes for the next SCT and parse it
            const sct = stream.getBlock(sctLength);
            sctList.push(sct_1.SignedCertificateTimestamp.parse(sct));
        }
        if (stream.position !== end) {
            throw new Error('SCT list length does not match actual length');
        }
        return sctList;
    }
}
exports.X509SCTExtension = X509SCTExtension;
PK~\PTT@sigstore/core/dist/x509/sct.jsnu["use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SignedCertificateTimestamp = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const crypto = __importStar(require("../crypto"));
const stream_1 = require("../stream");
class SignedCertificateTimestamp {
    constructor(options) {
        this.version = options.version;
        this.logID = options.logID;
        this.timestamp = options.timestamp;
        this.extensions = options.extensions;
        this.hashAlgorithm = options.hashAlgorithm;
        this.signatureAlgorithm = options.signatureAlgorithm;
        this.signature = options.signature;
    }
    get datetime() {
        return new Date(Number(this.timestamp.readBigInt64BE()));
    }
    // Returns the hash algorithm used to generate the SCT's signature.
    // https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.4.1
    get algorithm() {
        switch (this.hashAlgorithm) {
            /* istanbul ignore next */
            case 0:
                return 'none';
            /* istanbul ignore next */
            case 1:
                return 'md5';
            /* istanbul ignore next */
            case 2:
                return 'sha1';
            /* istanbul ignore next */
            case 3:
                return 'sha224';
            case 4:
                return 'sha256';
            /* istanbul ignore next */
            case 5:
                return 'sha384';
            /* istanbul ignore next */
            case 6:
                return 'sha512';
            /* istanbul ignore next */
            default:
                return 'unknown';
        }
    }
    verify(preCert, key) {
        // Assemble the digitally-signed struct (the data over which the signature
        // was generated).
        // https://www.rfc-editor.org/rfc/rfc6962#section-3.2
        const stream = new stream_1.ByteStream();
        stream.appendChar(this.version);
        stream.appendChar(0x00); // SignatureType = certificate_timestamp(0)
        stream.appendView(this.timestamp);
        stream.appendUint16(0x01); // LogEntryType = precert_entry(1)
        stream.appendView(preCert);
        stream.appendUint16(this.extensions.byteLength);
        /* istanbul ignore next - extensions are very uncommon */
        if (this.extensions.byteLength > 0) {
            stream.appendView(this.extensions);
        }
        return crypto.verify(stream.buffer, key, this.signature, this.algorithm);
    }
    // Parses a SignedCertificateTimestamp from a buffer. SCTs are encoded using
    // TLS encoding which means the fields and lengths of most fields are
    // specified as part of the SCT and TLS specs.
    // https://www.rfc-editor.org/rfc/rfc6962#section-3.2
    // https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.4.1
    static parse(buf) {
        const stream = new stream_1.ByteStream(buf);
        // Version - enum { v1(0), (255) }
        const version = stream.getUint8();
        // Log ID  - struct { opaque key_id[32]; }
        const logID = stream.getBlock(32);
        // Timestamp - uint64
        const timestamp = stream.getBlock(8);
        // Extensions - opaque extensions<0..2^16-1>;
        const extenstionLength = stream.getUint16();
        const extensions = stream.getBlock(extenstionLength);
        // Hash algo - enum { sha256(4), . . . (255) }
        const hashAlgorithm = stream.getUint8();
        // Signature algo - enum { anonymous(0), rsa(1), dsa(2), ecdsa(3), (255) }
        const signatureAlgorithm = stream.getUint8();
        // Signature  - opaque signature<0..2^16-1>;
        const sigLength = stream.getUint16();
        const signature = stream.getBlock(sigLength);
        // Check that we read the entire buffer
        if (stream.position !== buf.length) {
            throw new Error('SCT buffer length mismatch');
        }
        return new SignedCertificateTimestamp({
            version,
            logID,
            timestamp,
            extensions,
            hashAlgorithm,
            signatureAlgorithm,
            signature,
        });
    }
}
exports.SignedCertificateTimestamp = SignedCertificateTimestamp;
PK~\۟@sigstore/core/dist/encoding.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.base64Decode = exports.base64Encode = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const BASE64_ENCODING = 'base64';
const UTF8_ENCODING = 'utf-8';
function base64Encode(str) {
    return Buffer.from(str, UTF8_ENCODING).toString(BASE64_ENCODING);
}
exports.base64Encode = base64Encode;
function base64Decode(str) {
    return Buffer.from(str, BASE64_ENCODING).toString(UTF8_ENCODING);
}
exports.base64Decode = base64Decode;
PK~\q

@sigstore/core/dist/stream.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ByteStream = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
class StreamError extends Error {
}
class ByteStream {
    constructor(buffer) {
        this.start = 0;
        if (buffer) {
            this.buf = buffer;
            this.view = Buffer.from(buffer);
        }
        else {
            this.buf = new ArrayBuffer(0);
            this.view = Buffer.from(this.buf);
        }
    }
    get buffer() {
        return this.view.subarray(0, this.start);
    }
    get length() {
        return this.view.byteLength;
    }
    get position() {
        return this.start;
    }
    seek(position) {
        this.start = position;
    }
    // Returns a Buffer containing the specified number of bytes starting at the
    // given start position.
    slice(start, len) {
        const end = start + len;
        if (end > this.length) {
            throw new StreamError('request past end of buffer');
        }
        return this.view.subarray(start, end);
    }
    appendChar(char) {
        this.ensureCapacity(1);
        this.view[this.start] = char;
        this.start += 1;
    }
    appendUint16(num) {
        this.ensureCapacity(2);
        const value = new Uint16Array([num]);
        const view = new Uint8Array(value.buffer);
        this.view[this.start] = view[1];
        this.view[this.start + 1] = view[0];
        this.start += 2;
    }
    appendUint24(num) {
        this.ensureCapacity(3);
        const value = new Uint32Array([num]);
        const view = new Uint8Array(value.buffer);
        this.view[this.start] = view[2];
        this.view[this.start + 1] = view[1];
        this.view[this.start + 2] = view[0];
        this.start += 3;
    }
    appendView(view) {
        this.ensureCapacity(view.length);
        this.view.set(view, this.start);
        this.start += view.length;
    }
    getBlock(size) {
        if (size <= 0) {
            return Buffer.alloc(0);
        }
        if (this.start + size > this.view.length) {
            throw new Error('request past end of buffer');
        }
        const result = this.view.subarray(this.start, this.start + size);
        this.start += size;
        return result;
    }
    getUint8() {
        return this.getBlock(1)[0];
    }
    getUint16() {
        const block = this.getBlock(2);
        return (block[0] << 8) | block[1];
    }
    ensureCapacity(size) {
        if (this.start + size > this.view.byteLength) {
            const blockSize = ByteStream.BLOCK_SIZE + (size > ByteStream.BLOCK_SIZE ? size : 0);
            this.realloc(this.view.byteLength + blockSize);
        }
    }
    realloc(size) {
        const newArray = new ArrayBuffer(size);
        const newView = Buffer.from(newArray);
        // Copy the old buffer into the new one
        newView.set(this.view);
        this.buf = newArray;
        this.view = newView;
    }
}
exports.ByteStream = ByteStream;
ByteStream.BLOCK_SIZE = 1024;
PK~\t**!@sigstore/core/dist/asn1/index.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ASN1Obj = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var obj_1 = require("./obj");
Object.defineProperty(exports, "ASN1Obj", { enumerable: true, get: function () { return obj_1.ASN1Obj; } });
PK~\/9<<!@sigstore/core/dist/asn1/parse.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseBitString = exports.parseBoolean = exports.parseOID = exports.parseTime = exports.parseStringASCII = exports.parseInteger = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const RE_TIME_SHORT_YEAR = /^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\.\d{3})?Z$/;
const RE_TIME_LONG_YEAR = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\.\d{3})?Z$/;
// Parse a BigInt from the DER-encoded buffer
// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-integer
function parseInteger(buf) {
    let pos = 0;
    const end = buf.length;
    let val = buf[pos];
    const neg = val > 0x7f;
    // Consume any padding bytes
    const pad = neg ? 0xff : 0x00;
    while (val == pad && ++pos < end) {
        val = buf[pos];
    }
    // Calculate remaining bytes to read
    const len = end - pos;
    if (len === 0)
        return BigInt(neg ? -1 : 0);
    // Handle two's complement for negative numbers
    val = neg ? val - 256 : val;
    // Parse remaining bytes
    let n = BigInt(val);
    for (let i = pos + 1; i < end; ++i) {
        n = n * BigInt(256) + BigInt(buf[i]);
    }
    return n;
}
exports.parseInteger = parseInteger;
// Parse an ASCII string from the DER-encoded buffer
// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-basic-types#boolean
function parseStringASCII(buf) {
    return buf.toString('ascii');
}
exports.parseStringASCII = parseStringASCII;
// Parse a Date from the DER-encoded buffer
// https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.5.1
function parseTime(buf, shortYear) {
    const timeStr = parseStringASCII(buf);
    // Parse the time string into matches - captured groups start at index 1
    const m = shortYear
        ? RE_TIME_SHORT_YEAR.exec(timeStr)
        : RE_TIME_LONG_YEAR.exec(timeStr);
    if (!m) {
        throw new Error('invalid time');
    }
    // Translate dates with a 2-digit year to 4 digits per the spec
    if (shortYear) {
        let year = Number(m[1]);
        year += year >= 50 ? 1900 : 2000;
        m[1] = year.toString();
    }
    // Translate to ISO8601 format and parse
    return new Date(`${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}:${m[6]}Z`);
}
exports.parseTime = parseTime;
// Parse an OID from the DER-encoded buffer
// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-object-identifier
function parseOID(buf) {
    let pos = 0;
    const end = buf.length;
    // Consume first byte which encodes the first two OID components
    let n = buf[pos++];
    const first = Math.floor(n / 40);
    const second = n % 40;
    let oid = `${first}.${second}`;
    // Consume remaining bytes
    let val = 0;
    for (; pos < end; ++pos) {
        n = buf[pos];
        val = (val << 7) + (n & 0x7f);
        // If the left-most bit is NOT set, then this is the last byte in the
        // sequence and we can add the value to the OID and reset the accumulator
        if ((n & 0x80) === 0) {
            oid += `.${val}`;
            val = 0;
        }
    }
    return oid;
}
exports.parseOID = parseOID;
// Parse a boolean from the DER-encoded buffer
// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-basic-types#boolean
function parseBoolean(buf) {
    return buf[0] !== 0;
}
exports.parseBoolean = parseBoolean;
// Parse a bit string from the DER-encoded buffer
// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-bit-string
function parseBitString(buf) {
    // First byte tell us how many unused bits are in the last byte
    const unused = buf[0];
    const start = 1;
    const end = buf.length;
    const bits = [];
    for (let i = start; i < end; ++i) {
        const byte = buf[i];
        // The skip value is only used for the last byte
        const skip = i === end - 1 ? unused : 0;
        // Iterate over each bit in the byte (most significant first)
        for (let j = 7; j >= skip; --j) {
            // Read the bit and add it to the bit string
            bits.push((byte >> j) & 0x01);
        }
    }
    return bits;
}
exports.parseBitString = parseBitString;
PK~\!n@sigstore/core/dist/asn1/obj.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ASN1Obj = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const stream_1 = require("../stream");
const error_1 = require("./error");
const length_1 = require("./length");
const parse_1 = require("./parse");
const tag_1 = require("./tag");
class ASN1Obj {
    constructor(tag, value, subs) {
        this.tag = tag;
        this.value = value;
        this.subs = subs;
    }
    // Constructs an ASN.1 object from a Buffer of DER-encoded bytes.
    static parseBuffer(buf) {
        return parseStream(new stream_1.ByteStream(buf));
    }
    toDER() {
        const valueStream = new stream_1.ByteStream();
        if (this.subs.length > 0) {
            for (const sub of this.subs) {
                valueStream.appendView(sub.toDER());
            }
        }
        else {
            valueStream.appendView(this.value);
        }
        const value = valueStream.buffer;
        // Concat tag/length/value
        const obj = new stream_1.ByteStream();
        obj.appendChar(this.tag.toDER());
        obj.appendView((0, length_1.encodeLength)(value.length));
        obj.appendView(value);
        return obj.buffer;
    }
    /////////////////////////////////////////////////////////////////////////////
    // Convenience methods for parsing ASN.1 primitives into JS types
    // Returns the ASN.1 object's value as a boolean. Throws an error if the
    // object is not a boolean.
    toBoolean() {
        if (!this.tag.isBoolean()) {
            throw new error_1.ASN1TypeError('not a boolean');
        }
        return (0, parse_1.parseBoolean)(this.value);
    }
    // Returns the ASN.1 object's value as a BigInt. Throws an error if the
    // object is not an integer.
    toInteger() {
        if (!this.tag.isInteger()) {
            throw new error_1.ASN1TypeError('not an integer');
        }
        return (0, parse_1.parseInteger)(this.value);
    }
    // Returns the ASN.1 object's value as an OID string. Throws an error if the
    // object is not an OID.
    toOID() {
        if (!this.tag.isOID()) {
            throw new error_1.ASN1TypeError('not an OID');
        }
        return (0, parse_1.parseOID)(this.value);
    }
    // Returns the ASN.1 object's value as a Date. Throws an error if the object
    // is not either a UTCTime or a GeneralizedTime.
    toDate() {
        switch (true) {
            case this.tag.isUTCTime():
                return (0, parse_1.parseTime)(this.value, true);
            case this.tag.isGeneralizedTime():
                return (0, parse_1.parseTime)(this.value, false);
            default:
                throw new error_1.ASN1TypeError('not a date');
        }
    }
    // Returns the ASN.1 object's value as a number[] where each number is the
    // value of a bit in the bit string. Throws an error if the object is not a
    // bit string.
    toBitString() {
        if (!this.tag.isBitString()) {
            throw new error_1.ASN1TypeError('not a bit string');
        }
        return (0, parse_1.parseBitString)(this.value);
    }
}
exports.ASN1Obj = ASN1Obj;
/////////////////////////////////////////////////////////////////////////////
// Internal stream parsing functions
function parseStream(stream) {
    // Parse tag, length, and value from stream
    const tag = new tag_1.ASN1Tag(stream.getUint8());
    const len = (0, length_1.decodeLength)(stream);
    const value = stream.slice(stream.position, len);
    const start = stream.position;
    let subs = [];
    // If the object is constructed, parse its children. Sometimes, children
    // are embedded in OCTESTRING objects, so we need to check those
    // for children as well.
    if (tag.constructed) {
        subs = collectSubs(stream, len);
    }
    else if (tag.isOctetString()) {
        // Attempt to parse children of OCTETSTRING objects. If anything fails,
        // assume the object is not constructed and treat as primitive.
        try {
            subs = collectSubs(stream, len);
        }
        catch (e) {
            // Fail silently and treat as primitive
        }
    }
    // If there are no children, move stream cursor to the end of the object
    if (subs.length === 0) {
        stream.seek(start + len);
    }
    return new ASN1Obj(tag, value, subs);
}
function collectSubs(stream, len) {
    // Calculate end of object content
    const end = stream.position + len;
    // Make sure there are enough bytes left in the stream. This should never
    // happen, cause it'll get caught when the stream is sliced in parseStream.
    // Leaving as an extra check just in case.
    /* istanbul ignore if */
    if (end > stream.length) {
        throw new error_1.ASN1ParseError('invalid length');
    }
    // Parse all children
    const subs = [];
    while (stream.position < end) {
        subs.push(parseStream(stream));
    }
    // When we're done parsing children, we should be at the end of the object
    if (stream.position !== end) {
        throw new error_1.ASN1ParseError('invalid length');
    }
    return subs;
}
PK~\4<4	4	"@sigstore/core/dist/asn1/length.jsnu["use strict";
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.encodeLength = exports.decodeLength = void 0;
const error_1 = require("./error");
// Decodes the length of a DER-encoded ANS.1 element from the supplied stream.
// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-encoded-length-and-value-bytes
function decodeLength(stream) {
    const buf = stream.getUint8();
    // If the most significant bit is UNSET the length is just the value of the
    // byte.
    if ((buf & 0x80) === 0x00) {
        return buf;
    }
    // Otherwise, the lower 7 bits of the first byte indicate the number of bytes
    // that follow to encode the length.
    const byteCount = buf & 0x7f;
    // Ensure the encoded length can safely fit in a JS number.
    if (byteCount > 6) {
        throw new error_1.ASN1ParseError('length exceeds 6 byte limit');
    }
    // Iterate over the bytes that encode the length.
    let len = 0;
    for (let i = 0; i < byteCount; i++) {
        len = len * 256 + stream.getUint8();
    }
    // This is a valid ASN.1 length encoding, but we don't support it.
    if (len === 0) {
        throw new error_1.ASN1ParseError('indefinite length encoding not supported');
    }
    return len;
}
exports.decodeLength = decodeLength;
// Translates the supplied value to a DER-encoded length.
function encodeLength(len) {
    if (len < 128) {
        return Buffer.from([len]);
    }
    // Bitwise operations on large numbers are not supported in JS, so we need to
    // use BigInts.
    let val = BigInt(len);
    const bytes = [];
    while (val > 0n) {
        bytes.unshift(Number(val & 255n));
        val = val >> 8n;
    }
    return Buffer.from([0x80 | bytes.length, ...bytes]);
}
exports.encodeLength = encodeLength;
PK~\@sigstore/core/dist/asn1/tag.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ASN1Tag = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const error_1 = require("./error");
const UNIVERSAL_TAG = {
    BOOLEAN: 0x01,
    INTEGER: 0x02,
    BIT_STRING: 0x03,
    OCTET_STRING: 0x04,
    OBJECT_IDENTIFIER: 0x06,
    SEQUENCE: 0x10,
    SET: 0x11,
    PRINTABLE_STRING: 0x13,
    UTC_TIME: 0x17,
    GENERALIZED_TIME: 0x18,
};
const TAG_CLASS = {
    UNIVERSAL: 0x00,
    APPLICATION: 0x01,
    CONTEXT_SPECIFIC: 0x02,
    PRIVATE: 0x03,
};
// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-encoded-tag-bytes
class ASN1Tag {
    constructor(enc) {
        // Bits 0 through 4 are the tag number
        this.number = enc & 0x1f;
        // Bit 5 is the constructed bit
        this.constructed = (enc & 0x20) === 0x20;
        // Bit 6 & 7 are the class
        this.class = enc >> 6;
        if (this.number === 0x1f) {
            throw new error_1.ASN1ParseError('long form tags not supported');
        }
        if (this.class === TAG_CLASS.UNIVERSAL && this.number === 0x00) {
            throw new error_1.ASN1ParseError('unsupported tag 0x00');
        }
    }
    isUniversal() {
        return this.class === TAG_CLASS.UNIVERSAL;
    }
    isContextSpecific(num) {
        const res = this.class === TAG_CLASS.CONTEXT_SPECIFIC;
        return num !== undefined ? res && this.number === num : res;
    }
    isBoolean() {
        return this.isUniversal() && this.number === UNIVERSAL_TAG.BOOLEAN;
    }
    isInteger() {
        return this.isUniversal() && this.number === UNIVERSAL_TAG.INTEGER;
    }
    isBitString() {
        return this.isUniversal() && this.number === UNIVERSAL_TAG.BIT_STRING;
    }
    isOctetString() {
        return this.isUniversal() && this.number === UNIVERSAL_TAG.OCTET_STRING;
    }
    isOID() {
        return (this.isUniversal() && this.number === UNIVERSAL_TAG.OBJECT_IDENTIFIER);
    }
    isUTCTime() {
        return this.isUniversal() && this.number === UNIVERSAL_TAG.UTC_TIME;
    }
    isGeneralizedTime() {
        return this.isUniversal() && this.number === UNIVERSAL_TAG.GENERALIZED_TIME;
    }
    toDER() {
        return this.number | (this.constructed ? 0x20 : 0x00) | (this.class << 6);
    }
}
exports.ASN1Tag = ASN1Tag;
PK~\zl[[!@sigstore/core/dist/asn1/error.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ASN1TypeError = exports.ASN1ParseError = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
class ASN1ParseError extends Error {
}
exports.ASN1ParseError = ASN1ParseError;
class ASN1TypeError extends Error {
}
exports.ASN1TypeError = ASN1TypeError;
PK~\MC@sigstore/core/dist/oid.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SHA2_HASH_ALGOS = exports.ECDSA_SIGNATURE_ALGOS = void 0;
exports.ECDSA_SIGNATURE_ALGOS = {
    '1.2.840.10045.4.3.1': 'sha224',
    '1.2.840.10045.4.3.2': 'sha256',
    '1.2.840.10045.4.3.3': 'sha384',
    '1.2.840.10045.4.3.4': 'sha512',
};
exports.SHA2_HASH_ALGOS = {
    '2.16.840.1.101.3.4.2.1': 'sha256',
    '2.16.840.1.101.3.4.2.2': 'sha384',
    '2.16.840.1.101.3.4.2.3': 'sha512',
};
PK~\e@sigstore/core/dist/json.jsnu["use strict";
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.canonicalize = void 0;
// JSON canonicalization per https://github.com/cyberphone/json-canonicalization
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function canonicalize(object) {
    let buffer = '';
    if (object === null || typeof object !== 'object' || object.toJSON != null) {
        // Primitives or toJSONable objects
        buffer += JSON.stringify(object);
    }
    else if (Array.isArray(object)) {
        // Array - maintain element order
        buffer += '[';
        let first = true;
        object.forEach((element) => {
            if (!first) {
                buffer += ',';
            }
            first = false;
            // recursive call
            buffer += canonicalize(element);
        });
        buffer += ']';
    }
    else {
        // Object - Sort properties before serializing
        buffer += '{';
        let first = true;
        Object.keys(object)
            .sort()
            .forEach((property) => {
            if (!first) {
                buffer += ',';
            }
            first = false;
            buffer += JSON.stringify(property);
            buffer += ':';
            // recursive call
            buffer += canonicalize(object[property]);
        });
        buffer += '}';
    }
    return buffer;
}
exports.canonicalize = canonicalize;
PK~\z@sigstore/bundle/package.jsonnu[{
  "_id": "@sigstore/bundle@2.3.2",
  "_inBundle": true,
  "_location": "/npm/@sigstore/bundle",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm/@sigstore/sign",
    "/npm/@sigstore/verify",
    "/npm/sigstore"
  ],
  "author": {
    "name": "bdehamer@github.com"
  },
  "bugs": {
    "url": "https://github.com/sigstore/sigstore-js/issues"
  },
  "dependencies": {
    "@sigstore/protobuf-specs": "^0.3.2"
  },
  "description": "Sigstore bundle type",
  "engines": {
    "node": "^16.14.0 || >=18.0.0"
  },
  "files": [
    "dist",
    "store"
  ],
  "homepage": "https://github.com/sigstore/sigstore-js/tree/main/packages/bundle#readme",
  "license": "Apache-2.0",
  "main": "dist/index.js",
  "name": "@sigstore/bundle",
  "publishConfig": {
    "provenance": true
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/sigstore/sigstore-js.git"
  },
  "scripts": {
    "build": "tsc --build",
    "clean": "shx rm -rf dist *.tsbuildinfo",
    "test": "jest"
  },
  "types": "dist/index.d.ts",
  "version": "2.3.2"
}
PK~\"KW,W,@sigstore/bundle/LICENSEnu[
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright 2023 The Sigstore Authors

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
PK~\-TMM @sigstore/bundle/dist/utility.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
PK~\a.::@sigstore/bundle/dist/index.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isBundleV01 = exports.assertBundleV02 = exports.assertBundleV01 = exports.assertBundleLatest = exports.assertBundle = exports.envelopeToJSON = exports.envelopeFromJSON = exports.bundleToJSON = exports.bundleFromJSON = exports.ValidationError = exports.isBundleWithPublicKey = exports.isBundleWithMessageSignature = exports.isBundleWithDsseEnvelope = exports.isBundleWithCertificateChain = exports.BUNDLE_V03_MEDIA_TYPE = exports.BUNDLE_V03_LEGACY_MEDIA_TYPE = exports.BUNDLE_V02_MEDIA_TYPE = exports.BUNDLE_V01_MEDIA_TYPE = exports.toMessageSignatureBundle = exports.toDSSEBundle = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var build_1 = require("./build");
Object.defineProperty(exports, "toDSSEBundle", { enumerable: true, get: function () { return build_1.toDSSEBundle; } });
Object.defineProperty(exports, "toMessageSignatureBundle", { enumerable: true, get: function () { return build_1.toMessageSignatureBundle; } });
var bundle_1 = require("./bundle");
Object.defineProperty(exports, "BUNDLE_V01_MEDIA_TYPE", { enumerable: true, get: function () { return bundle_1.BUNDLE_V01_MEDIA_TYPE; } });
Object.defineProperty(exports, "BUNDLE_V02_MEDIA_TYPE", { enumerable: true, get: function () { return bundle_1.BUNDLE_V02_MEDIA_TYPE; } });
Object.defineProperty(exports, "BUNDLE_V03_LEGACY_MEDIA_TYPE", { enumerable: true, get: function () { return bundle_1.BUNDLE_V03_LEGACY_MEDIA_TYPE; } });
Object.defineProperty(exports, "BUNDLE_V03_MEDIA_TYPE", { enumerable: true, get: function () { return bundle_1.BUNDLE_V03_MEDIA_TYPE; } });
Object.defineProperty(exports, "isBundleWithCertificateChain", { enumerable: true, get: function () { return bundle_1.isBundleWithCertificateChain; } });
Object.defineProperty(exports, "isBundleWithDsseEnvelope", { enumerable: true, get: function () { return bundle_1.isBundleWithDsseEnvelope; } });
Object.defineProperty(exports, "isBundleWithMessageSignature", { enumerable: true, get: function () { return bundle_1.isBundleWithMessageSignature; } });
Object.defineProperty(exports, "isBundleWithPublicKey", { enumerable: true, get: function () { return bundle_1.isBundleWithPublicKey; } });
var error_1 = require("./error");
Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return error_1.ValidationError; } });
var serialized_1 = require("./serialized");
Object.defineProperty(exports, "bundleFromJSON", { enumerable: true, get: function () { return serialized_1.bundleFromJSON; } });
Object.defineProperty(exports, "bundleToJSON", { enumerable: true, get: function () { return serialized_1.bundleToJSON; } });
Object.defineProperty(exports, "envelopeFromJSON", { enumerable: true, get: function () { return serialized_1.envelopeFromJSON; } });
Object.defineProperty(exports, "envelopeToJSON", { enumerable: true, get: function () { return serialized_1.envelopeToJSON; } });
var validate_1 = require("./validate");
Object.defineProperty(exports, "assertBundle", { enumerable: true, get: function () { return validate_1.assertBundle; } });
Object.defineProperty(exports, "assertBundleLatest", { enumerable: true, get: function () { return validate_1.assertBundleLatest; } });
Object.defineProperty(exports, "assertBundleV01", { enumerable: true, get: function () { return validate_1.assertBundleV01; } });
Object.defineProperty(exports, "assertBundleV02", { enumerable: true, get: function () { return validate_1.assertBundleV02; } });
Object.defineProperty(exports, "isBundleV01", { enumerable: true, get: function () { return validate_1.isBundleV01; } });
PK~\E@sigstore/bundle/dist/bundle.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isBundleWithDsseEnvelope = exports.isBundleWithMessageSignature = exports.isBundleWithPublicKey = exports.isBundleWithCertificateChain = exports.BUNDLE_V03_MEDIA_TYPE = exports.BUNDLE_V03_LEGACY_MEDIA_TYPE = exports.BUNDLE_V02_MEDIA_TYPE = exports.BUNDLE_V01_MEDIA_TYPE = void 0;
exports.BUNDLE_V01_MEDIA_TYPE = 'application/vnd.dev.sigstore.bundle+json;version=0.1';
exports.BUNDLE_V02_MEDIA_TYPE = 'application/vnd.dev.sigstore.bundle+json;version=0.2';
exports.BUNDLE_V03_LEGACY_MEDIA_TYPE = 'application/vnd.dev.sigstore.bundle+json;version=0.3';
exports.BUNDLE_V03_MEDIA_TYPE = 'application/vnd.dev.sigstore.bundle.v0.3+json';
// Type guards for bundle variants.
function isBundleWithCertificateChain(b) {
    return b.verificationMaterial.content.$case === 'x509CertificateChain';
}
exports.isBundleWithCertificateChain = isBundleWithCertificateChain;
function isBundleWithPublicKey(b) {
    return b.verificationMaterial.content.$case === 'publicKey';
}
exports.isBundleWithPublicKey = isBundleWithPublicKey;
function isBundleWithMessageSignature(b) {
    return b.content.$case === 'messageSignature';
}
exports.isBundleWithMessageSignature = isBundleWithMessageSignature;
function isBundleWithDsseEnvelope(b) {
    return b.content.$case === 'dsseEnvelope';
}
exports.isBundleWithDsseEnvelope = isBundleWithDsseEnvelope;
PK~\&J5PP@sigstore/bundle/dist/build.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toDSSEBundle = exports.toMessageSignatureBundle = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const protobuf_specs_1 = require("@sigstore/protobuf-specs");
const bundle_1 = require("./bundle");
// Message signature bundle - $case: 'messageSignature'
function toMessageSignatureBundle(options) {
    return {
        mediaType: options.singleCertificate
            ? bundle_1.BUNDLE_V03_MEDIA_TYPE
            : bundle_1.BUNDLE_V02_MEDIA_TYPE,
        content: {
            $case: 'messageSignature',
            messageSignature: {
                messageDigest: {
                    algorithm: protobuf_specs_1.HashAlgorithm.SHA2_256,
                    digest: options.digest,
                },
                signature: options.signature,
            },
        },
        verificationMaterial: toVerificationMaterial(options),
    };
}
exports.toMessageSignatureBundle = toMessageSignatureBundle;
// DSSE envelope bundle - $case: 'dsseEnvelope'
function toDSSEBundle(options) {
    return {
        mediaType: options.singleCertificate
            ? bundle_1.BUNDLE_V03_MEDIA_TYPE
            : bundle_1.BUNDLE_V02_MEDIA_TYPE,
        content: {
            $case: 'dsseEnvelope',
            dsseEnvelope: toEnvelope(options),
        },
        verificationMaterial: toVerificationMaterial(options),
    };
}
exports.toDSSEBundle = toDSSEBundle;
function toEnvelope(options) {
    return {
        payloadType: options.artifactType,
        payload: options.artifact,
        signatures: [toSignature(options)],
    };
}
function toSignature(options) {
    return {
        keyid: options.keyHint || '',
        sig: options.signature,
    };
}
// Verification material
function toVerificationMaterial(options) {
    return {
        content: toKeyContent(options),
        tlogEntries: [],
        timestampVerificationData: { rfc3161Timestamps: [] },
    };
}
function toKeyContent(options) {
    if (options.certificate) {
        if (options.singleCertificate) {
            return {
                $case: 'certificate',
                certificate: { rawBytes: options.certificate },
            };
        }
        else {
            return {
                $case: 'x509CertificateChain',
                x509CertificateChain: {
                    certificates: [{ rawBytes: options.certificate }],
                },
            };
        }
    }
    else {
        return {
            $case: 'publicKey',
            publicKey: {
                hint: options.keyHint || '',
            },
        };
    }
}
PK~\9YY@sigstore/bundle/dist/error.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValidationError = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
class ValidationError extends Error {
    constructor(message, fields) {
        super(message);
        this.fields = fields;
    }
}
exports.ValidationError = ValidationError;
PK~\ZC#@sigstore/bundle/dist/serialized.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.envelopeToJSON = exports.envelopeFromJSON = exports.bundleToJSON = exports.bundleFromJSON = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const protobuf_specs_1 = require("@sigstore/protobuf-specs");
const bundle_1 = require("./bundle");
const validate_1 = require("./validate");
const bundleFromJSON = (obj) => {
    const bundle = protobuf_specs_1.Bundle.fromJSON(obj);
    switch (bundle.mediaType) {
        case bundle_1.BUNDLE_V01_MEDIA_TYPE:
            (0, validate_1.assertBundleV01)(bundle);
            break;
        case bundle_1.BUNDLE_V02_MEDIA_TYPE:
            (0, validate_1.assertBundleV02)(bundle);
            break;
        default:
            (0, validate_1.assertBundleLatest)(bundle);
            break;
    }
    return bundle;
};
exports.bundleFromJSON = bundleFromJSON;
const bundleToJSON = (bundle) => {
    return protobuf_specs_1.Bundle.toJSON(bundle);
};
exports.bundleToJSON = bundleToJSON;
const envelopeFromJSON = (obj) => {
    return protobuf_specs_1.Envelope.fromJSON(obj);
};
exports.envelopeFromJSON = envelopeFromJSON;
const envelopeToJSON = (envelope) => {
    return protobuf_specs_1.Envelope.toJSON(envelope);
};
exports.envelopeToJSON = envelopeToJSON;
PK~\o}!@sigstore/bundle/dist/validate.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.assertBundleLatest = exports.assertBundleV02 = exports.isBundleV01 = exports.assertBundleV01 = exports.assertBundle = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const error_1 = require("./error");
// Performs basic validation of a Sigstore bundle to ensure that all required
// fields are populated. This is not a complete validation of the bundle, but
// rather a check that the bundle is in a valid state to be processed by the
// rest of the code.
function assertBundle(b) {
    const invalidValues = validateBundleBase(b);
    if (invalidValues.length > 0) {
        throw new error_1.ValidationError('invalid bundle', invalidValues);
    }
}
exports.assertBundle = assertBundle;
// Asserts that the given bundle conforms to the v0.1 bundle format.
function assertBundleV01(b) {
    const invalidValues = [];
    invalidValues.push(...validateBundleBase(b));
    invalidValues.push(...validateInclusionPromise(b));
    if (invalidValues.length > 0) {
        throw new error_1.ValidationError('invalid v0.1 bundle', invalidValues);
    }
}
exports.assertBundleV01 = assertBundleV01;
// Type guard to determine if Bundle is a v0.1 bundle.
function isBundleV01(b) {
    try {
        assertBundleV01(b);
        return true;
    }
    catch (e) {
        return false;
    }
}
exports.isBundleV01 = isBundleV01;
// Asserts that the given bundle conforms to the v0.2 bundle format.
function assertBundleV02(b) {
    const invalidValues = [];
    invalidValues.push(...validateBundleBase(b));
    invalidValues.push(...validateInclusionProof(b));
    if (invalidValues.length > 0) {
        throw new error_1.ValidationError('invalid v0.2 bundle', invalidValues);
    }
}
exports.assertBundleV02 = assertBundleV02;
// Asserts that the given bundle conforms to the newest (0.3) bundle format.
function assertBundleLatest(b) {
    const invalidValues = [];
    invalidValues.push(...validateBundleBase(b));
    invalidValues.push(...validateInclusionProof(b));
    invalidValues.push(...validateNoCertificateChain(b));
    if (invalidValues.length > 0) {
        throw new error_1.ValidationError('invalid bundle', invalidValues);
    }
}
exports.assertBundleLatest = assertBundleLatest;
function validateBundleBase(b) {
    const invalidValues = [];
    // Media type validation
    if (b.mediaType === undefined ||
        (!b.mediaType.match(/^application\/vnd\.dev\.sigstore\.bundle\+json;version=\d\.\d/) &&
            !b.mediaType.match(/^application\/vnd\.dev\.sigstore\.bundle\.v\d\.\d\+json/))) {
        invalidValues.push('mediaType');
    }
    // Content-related validation
    if (b.content === undefined) {
        invalidValues.push('content');
    }
    else {
        switch (b.content.$case) {
            case 'messageSignature':
                if (b.content.messageSignature.messageDigest === undefined) {
                    invalidValues.push('content.messageSignature.messageDigest');
                }
                else {
                    if (b.content.messageSignature.messageDigest.digest.length === 0) {
                        invalidValues.push('content.messageSignature.messageDigest.digest');
                    }
                }
                if (b.content.messageSignature.signature.length === 0) {
                    invalidValues.push('content.messageSignature.signature');
                }
                break;
            case 'dsseEnvelope':
                if (b.content.dsseEnvelope.payload.length === 0) {
                    invalidValues.push('content.dsseEnvelope.payload');
                }
                if (b.content.dsseEnvelope.signatures.length !== 1) {
                    invalidValues.push('content.dsseEnvelope.signatures');
                }
                else {
                    if (b.content.dsseEnvelope.signatures[0].sig.length === 0) {
                        invalidValues.push('content.dsseEnvelope.signatures[0].sig');
                    }
                }
                break;
        }
    }
    // Verification material-related validation
    if (b.verificationMaterial === undefined) {
        invalidValues.push('verificationMaterial');
    }
    else {
        if (b.verificationMaterial.content === undefined) {
            invalidValues.push('verificationMaterial.content');
        }
        else {
            switch (b.verificationMaterial.content.$case) {
                case 'x509CertificateChain':
                    if (b.verificationMaterial.content.x509CertificateChain.certificates
                        .length === 0) {
                        invalidValues.push('verificationMaterial.content.x509CertificateChain.certificates');
                    }
                    b.verificationMaterial.content.x509CertificateChain.certificates.forEach((cert, i) => {
                        if (cert.rawBytes.length === 0) {
                            invalidValues.push(`verificationMaterial.content.x509CertificateChain.certificates[${i}].rawBytes`);
                        }
                    });
                    break;
                case 'certificate':
                    if (b.verificationMaterial.content.certificate.rawBytes.length === 0) {
                        invalidValues.push('verificationMaterial.content.certificate.rawBytes');
                    }
                    break;
            }
        }
        if (b.verificationMaterial.tlogEntries === undefined) {
            invalidValues.push('verificationMaterial.tlogEntries');
        }
        else {
            if (b.verificationMaterial.tlogEntries.length > 0) {
                b.verificationMaterial.tlogEntries.forEach((entry, i) => {
                    if (entry.logId === undefined) {
                        invalidValues.push(`verificationMaterial.tlogEntries[${i}].logId`);
                    }
                    if (entry.kindVersion === undefined) {
                        invalidValues.push(`verificationMaterial.tlogEntries[${i}].kindVersion`);
                    }
                });
            }
        }
    }
    return invalidValues;
}
// Necessary for V01 bundles
function validateInclusionPromise(b) {
    const invalidValues = [];
    if (b.verificationMaterial &&
        b.verificationMaterial.tlogEntries?.length > 0) {
        b.verificationMaterial.tlogEntries.forEach((entry, i) => {
            if (entry.inclusionPromise === undefined) {
                invalidValues.push(`verificationMaterial.tlogEntries[${i}].inclusionPromise`);
            }
        });
    }
    return invalidValues;
}
// Necessary for V02 and later bundles
function validateInclusionProof(b) {
    const invalidValues = [];
    if (b.verificationMaterial &&
        b.verificationMaterial.tlogEntries?.length > 0) {
        b.verificationMaterial.tlogEntries.forEach((entry, i) => {
            if (entry.inclusionProof === undefined) {
                invalidValues.push(`verificationMaterial.tlogEntries[${i}].inclusionProof`);
            }
            else {
                if (entry.inclusionProof.checkpoint === undefined) {
                    invalidValues.push(`verificationMaterial.tlogEntries[${i}].inclusionProof.checkpoint`);
                }
            }
        });
    }
    return invalidValues;
}
// Necessary for V03 and later bundles
function validateNoCertificateChain(b) {
    const invalidValues = [];
    if (b.verificationMaterial?.content?.$case === 'x509CertificateChain') {
        invalidValues.push('verificationMaterial.content.$case');
    }
    return invalidValues;
}
PK~\.2V@sigstore/tuf/package.jsonnu[{
  "_id": "@sigstore/tuf@2.3.4",
  "_inBundle": true,
  "_location": "/npm/@sigstore/tuf",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm",
    "/npm/sigstore"
  ],
  "author": {
    "name": "bdehamer@github.com"
  },
  "bugs": {
    "url": "https://github.com/sigstore/sigstore-js/issues"
  },
  "dependencies": {
    "@sigstore/protobuf-specs": "^0.3.2",
    "tuf-js": "^2.2.1"
  },
  "description": "Client for the Sigstore TUF repository",
  "devDependencies": {
    "@sigstore/jest": "^0.0.0",
    "@tufjs/repo-mock": "^2.0.1",
    "@types/make-fetch-happen": "^10.0.4"
  },
  "engines": {
    "node": "^16.14.0 || >=18.0.0"
  },
  "files": [
    "dist",
    "seeds.json"
  ],
  "homepage": "https://github.com/sigstore/sigstore-js/tree/main/packages/tuf#readme",
  "license": "Apache-2.0",
  "main": "dist/index.js",
  "name": "@sigstore/tuf",
  "publishConfig": {
    "provenance": true
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/sigstore/sigstore-js.git"
  },
  "scripts": {
    "build": "tsc --build",
    "clean": "shx rm -rf dist *.tsbuildinfo",
    "test": "jest"
  },
  "types": "dist/index.d.ts",
  "version": "2.3.4"
}
PK~\"KW,W,@sigstore/tuf/LICENSEnu[
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright 2023 The Sigstore Authors

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
PK~\*

@sigstore/tuf/dist/target.jsnu["use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.readTarget = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const fs_1 = __importDefault(require("fs"));
const error_1 = require("./error");
// Downloads and returns the specified target from the provided TUF Updater.
async function readTarget(tuf, targetPath) {
    const path = await getTargetPath(tuf, targetPath);
    return new Promise((resolve, reject) => {
        fs_1.default.readFile(path, 'utf-8', (err, data) => {
            if (err) {
                reject(new error_1.TUFError({
                    code: 'TUF_READ_TARGET_ERROR',
                    message: `error reading target ${path}`,
                    cause: err,
                }));
            }
            else {
                resolve(data);
            }
        });
    });
}
exports.readTarget = readTarget;
// Returns the local path to the specified target. If the target is not yet
// cached locally, the provided TUF Updater will be used to download and
// cache the target.
async function getTargetPath(tuf, target) {
    let targetInfo;
    try {
        targetInfo = await tuf.getTargetInfo(target);
    }
    catch (err) {
        throw new error_1.TUFError({
            code: 'TUF_REFRESH_METADATA_ERROR',
            message: 'error refreshing TUF metadata',
            cause: err,
        });
    }
    if (!targetInfo) {
        throw new error_1.TUFError({
            code: 'TUF_FIND_TARGET_ERROR',
            message: `target ${target} not found`,
        });
    }
    let path = await tuf.findCachedTarget(targetInfo);
    // An empty path here means the target has not been cached locally, or is
    // out of date. In either case, we need to download it.
    if (!path) {
        try {
            path = await tuf.downloadTarget(targetInfo);
        }
        catch (err) {
            throw new error_1.TUFError({
                code: 'TUF_DOWNLOAD_TARGET_ERROR',
                message: `error downloading target ${path}`,
                cause: err,
            });
        }
    }
    return path;
}
PK~\2@sigstore/tuf/dist/appdata.jsnu["use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.appDataPath = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const os_1 = __importDefault(require("os"));
const path_1 = __importDefault(require("path"));
function appDataPath(name) {
    const homedir = os_1.default.homedir();
    switch (process.platform) {
        /* istanbul ignore next */
        case 'darwin': {
            const appSupport = path_1.default.join(homedir, 'Library', 'Application Support');
            return path_1.default.join(appSupport, name);
        }
        /* istanbul ignore next */
        case 'win32': {
            const localAppData = process.env.LOCALAPPDATA || path_1.default.join(homedir, 'AppData', 'Local');
            return path_1.default.join(localAppData, name, 'Data');
        }
        /* istanbul ignore next */
        default: {
            const localData = process.env.XDG_DATA_HOME || path_1.default.join(homedir, '.local', 'share');
            return path_1.default.join(localData, name);
        }
    }
}
exports.appDataPath = appDataPath;
PK~\P@sigstore/tuf/dist/index.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TUFError = exports.initTUF = exports.getTrustedRoot = exports.DEFAULT_MIRROR_URL = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const protobuf_specs_1 = require("@sigstore/protobuf-specs");
const appdata_1 = require("./appdata");
const client_1 = require("./client");
exports.DEFAULT_MIRROR_URL = 'https://tuf-repo-cdn.sigstore.dev';
const DEFAULT_CACHE_DIR = 'sigstore-js';
const DEFAULT_RETRY = { retries: 2 };
const DEFAULT_TIMEOUT = 5000;
const TRUSTED_ROOT_TARGET = 'trusted_root.json';
async function getTrustedRoot(
/* istanbul ignore next */
options = {}) {
    const client = createClient(options);
    const trustedRoot = await client.getTarget(TRUSTED_ROOT_TARGET);
    return protobuf_specs_1.TrustedRoot.fromJSON(JSON.parse(trustedRoot));
}
exports.getTrustedRoot = getTrustedRoot;
async function initTUF(
/* istanbul ignore next */
options = {}) {
    const client = createClient(options);
    return client.refresh().then(() => client);
}
exports.initTUF = initTUF;
// Create a TUF client with default options
function createClient(options) {
    /* istanbul ignore next */
    return new client_1.TUFClient({
        cachePath: options.cachePath || (0, appdata_1.appDataPath)(DEFAULT_CACHE_DIR),
        rootPath: options.rootPath,
        mirrorURL: options.mirrorURL || exports.DEFAULT_MIRROR_URL,
        retry: options.retry ?? DEFAULT_RETRY,
        timeout: options.timeout ?? DEFAULT_TIMEOUT,
        forceCache: options.forceCache ?? false,
        forceInit: options.forceInit ?? options.force ?? false,
    });
}
var error_1 = require("./error");
Object.defineProperty(exports, "TUFError", { enumerable: true, get: function () { return error_1.TUFError; } });
PK~\*
RR@sigstore/tuf/dist/error.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TUFError = void 0;
class TUFError extends Error {
    constructor({ code, message, cause, }) {
        super(message);
        this.code = code;
        this.cause = cause;
        this.name = this.constructor.name;
    }
}
exports.TUFError = TUFError;
PK~\=P@sigstore/tuf/dist/client.jsnu["use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TUFClient = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const tuf_js_1 = require("tuf-js");
const _1 = require(".");
const target_1 = require("./target");
const TARGETS_DIR_NAME = 'targets';
class TUFClient {
    constructor(options) {
        const url = new URL(options.mirrorURL);
        const repoName = encodeURIComponent(url.host + url.pathname.replace(/\/$/, ''));
        const cachePath = path_1.default.join(options.cachePath, repoName);
        initTufCache(cachePath);
        seedCache({
            cachePath,
            mirrorURL: options.mirrorURL,
            tufRootPath: options.rootPath,
            forceInit: options.forceInit,
        });
        this.updater = initClient({
            mirrorURL: options.mirrorURL,
            cachePath,
            forceCache: options.forceCache,
            retry: options.retry,
            timeout: options.timeout,
        });
    }
    async refresh() {
        return this.updater.refresh();
    }
    getTarget(targetName) {
        return (0, target_1.readTarget)(this.updater, targetName);
    }
}
exports.TUFClient = TUFClient;
// Initializes the TUF cache directory structure including the initial
// root.json file. If the cache directory does not exist, it will be
// created. If the targets directory does not exist, it will be created.
// If the root.json file does not exist, it will be copied from the
// rootPath argument.
function initTufCache(cachePath) {
    const targetsPath = path_1.default.join(cachePath, TARGETS_DIR_NAME);
    if (!fs_1.default.existsSync(cachePath)) {
        fs_1.default.mkdirSync(cachePath, { recursive: true });
    }
    if (!fs_1.default.existsSync(targetsPath)) {
        fs_1.default.mkdirSync(targetsPath);
    }
}
// Populates the TUF cache with the initial root.json file. If the root.json
// file does not exist (or we're forcing re-initialization), copy it from either
// the rootPath argument or from one of the repo seeds.
function seedCache({ cachePath, mirrorURL, tufRootPath, forceInit, }) {
    const cachedRootPath = path_1.default.join(cachePath, 'root.json');
    // If the root.json file does not exist (or we're forcing re-initialization),
    // populate it either from the supplied rootPath or from one of the repo seeds.
    if (!fs_1.default.existsSync(cachedRootPath) || forceInit) {
        if (tufRootPath) {
            fs_1.default.copyFileSync(tufRootPath, cachedRootPath);
        }
        else {
            /* eslint-disable @typescript-eslint/no-var-requires */
            const seeds = require('../seeds.json');
            const repoSeed = seeds[mirrorURL];
            if (!repoSeed) {
                throw new _1.TUFError({
                    code: 'TUF_INIT_CACHE_ERROR',
                    message: `No root.json found for mirror: ${mirrorURL}`,
                });
            }
            fs_1.default.writeFileSync(cachedRootPath, Buffer.from(repoSeed['root.json'], 'base64'));
            // Copy any seed targets into the cache
            Object.entries(repoSeed.targets).forEach(([targetName, target]) => {
                fs_1.default.writeFileSync(path_1.default.join(cachePath, TARGETS_DIR_NAME, targetName), Buffer.from(target, 'base64'));
            });
        }
    }
}
function initClient(options) {
    const config = {
        fetchTimeout: options.timeout,
        fetchRetry: options.retry,
    };
    return new tuf_js_1.Updater({
        metadataBaseUrl: options.mirrorURL,
        targetBaseUrl: `${options.mirrorURL}/targets`,
        metadataDir: options.cachePath,
        targetDir: path_1.default.join(options.cachePath, TARGETS_DIR_NAME),
        forceCache: options.forceCache,
        config,
    });
}
PK~\AMM@sigstore/tuf/seeds.jsonnu[{"https://tuf-repo-cdn.sigstore.dev":{"root.json":"ewoJInNpZ25lZCI6IHsKCQkiX3R5cGUiOiAicm9vdCIsCgkJInNwZWNfdmVyc2lvbiI6ICIxLjAiLAoJCSJ2ZXJzaW9uIjogOSwKCQkiZXhwaXJlcyI6ICIyMDI0LTA5LTEyVDA2OjUzOjEwWiIsCgkJImtleXMiOiB7CgkJCSIxZTFkNjVjZTk4YjEwYWRkYWQ0NzY0ZmViZjdkZGEyZDA0MzZiM2QzYTM4OTM1NzljMGRkZGFlYTIwZTU0ODQ5IjogewoJCQkJImtleXR5cGUiOiAiZWNkc2EiLAoJCQkJInNjaGVtZSI6ICJlY2RzYS1zaGEyLW5pc3RwMjU2IiwKCQkJCSJrZXlpZF9oYXNoX2FsZ29yaXRobXMiOiBbCgkJCQkJInNoYTI1NiIsCgkJCQkJInNoYTUxMiIKCQkJCV0sCgkJCQkia2V5dmFsIjogewoJCQkJCSJwdWJsaWMiOiAiLS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS1cbk1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRXpCelZPbUhDUG9qTVZMU0kzNjRXaWlWOE5QckRcbjZJZ1J4Vmxpc2t6L3YreTNKRVI1bWNWR2NPTmxpRGNXTUM1SjJsZkhtalBOUGhiNEg3eG04THpmU0E9PVxuLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tXG4iCgkJCQl9CgkJCX0s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UyZTU2ZjAyOGIzIgoJCX0KCV0KfQ==","targets":{"trusted_root.json":"ewogICJtZWRpYVR5cGUiOiAiYXBwbGljYXRpb24vdm5kLmRldi5zaWdzdG9yZS50cnVzdGVkcm9vdCtqc29uO3ZlcnNpb249MC4xIiwKICAidGxvZ3MiOiBbCiAgICB7CiAgICAgICJiYXNlVXJsIjogImh0dHBzOi8vcmVrb3Iuc2lnc3RvcmUuZGV2IiwKICAgICAgImhhc2hBbGdvcml0aG0iOiAiU0hBMl8yNTYiLAogICAgICAicHVibGljS2V5IjogewogICAgICAgICJyYXdCeXRlcyI6ICJNRmt3RXdZSEtvWkl6ajBDQVFZSUtvWkl6ajBEQVFjRFFnQUUyRzJZKzJ0YWJkVFY1QmNHaUJJeDBhOWZBRndya0JibUxTR3RrczRMM3FYNnlZWTB6dWZCbmhDOFVyL2l5NTVHaFdQLzlBL2JZMkxoQzMwTTkrUll0dz09IiwKICAgICAgICAia2V5RGV0YWlscyI6ICJQS0lYX0VDRFNBX1AyNTZfU0hBXzI1NiIsCiAgICAgICAgInZhbGlkRm9yIjogewogICAgICAgICAgInN0YXJ0IjogIjIwMjEtMDEtMTJUMTE6NTM6MjcuMDAwWiIKICAgICAgICB9CiAgICAgIH0sCiAgICAgICJsb2dJZCI6IHsKICAgICAgICAia2V5SWQiOiAid05JOWF0UUdseitWV2ZPNkxSeWdINFFVZlkvOFc0UkZ3aVQ1aTVXUmdCMD0iCiAgICAgIH0KICAgIH0KICBdLAogICJjZXJ0aWZpY2F0ZUF1dGhvcml0aWVzIjogWwogICAgewogICAgICAic3ViamVjdCI6IHsKICAgICAgICAib3JnYW5pemF0aW9uIjogInNpZ3N0b3JlLmRldiIsCiAgICAgICAgImNvbW1vbk5hbWUiOiAic2lnc3RvcmUiCiAgICAgIH0sCiAgICAgICJ1cmkiOiAiaHR0cHM6Ly9mdWxjaW8uc2lnc3RvcmUuZGV2IiwKICAgICAgImNlcnRDaGFpbiI6IHsKICAgICAgICAiY2VydGlmaWN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UVBQ0lEWWdBRWY5akZBWHh6NGt4NjhBSFJNT2tGQmhmbERjTVR2emFYejR4L0ZDY1hqSi8xcUVLb24vcVBJR25hVVJza0R0eU5iTkRPcGVKVERERnF0NDhpTVBybnpweDZJWndxZW1mVUpONHhCRVpmemErcFl0L2l5b2QrOXRacjIwUlJXU3YvbzBVd1F6QU9CZ05WSFE4QkFmOEVCQU1DQVFZd0VnWURWUjBUQVFIL0JBZ3dCZ0VCL3dJQkFqQWRCZ05WSFE0RUZnUVU5TllZbG9ibkFHNGMwL3FqeHlIL2xxL3d6K1F3Q2dZSUtvWkl6ajBFQXdNRGFBQXdaUUl4QUxaTFo4QmdSWHpLeExNTU45VklsTytlNGhyQm5OQmdGN3R6N0hucm93djJOZXRaRXJJQUNLRnltQmx2V0R2dE1BSXdaTytraTZzc1ExYnNabzk4TzhtRUFmMk5aN2lpQ2dERFUwVndqZWNvNnp5ZWgwekJUczkvN2dWNkFITlE1M3hEIgogICAgICAgICAgfQogICAgICAgIF0KICAgICAgfSwKICAgICAgInZhbGlkRm9yIjogewogICAgICAgICJzdGFydCI6ICIyMDIzLTA0LTE0VDAwOjAwOjAwLjAwMFoiCiAgICAgIH0KICAgIH0KICBdCn0K","registry.npmjs.org%2Fkeys.json":"ewogICAgImtleXMiOiBbCiAgICAgICAgewogICAgICAgICAgICAia2V5SWQiOiAiU0hBMjU2OmpsM2J3c3d1ODBQampva0NnaDBvMnc1YzJVNExoUUFFNTdnajljejFrekEiLAogICAgICAgICAgICAia2V5VXNhZ2UiOiAibnBtOnNpZ25hdHVyZXMiLAogICAgICAgICAgICAicHVibGljS2V5IjogewogICAgICAgICAgICAgICAgInJhd0J5dGVzIjogIk1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRTFPbGIzek1BRkZ4WEtIaUlrUU81Y0ozWWhsNWk2VVBwK0lodXRlQkpidUhjQTVVb2dLbzBFV3RsV3dXNktTYUtvVE5FWUw3SmxDUWlWbmtoQmt0VWdnPT0iLAogICAgICAgICAgICAgICAgImtleURldGFpbHMiOiAiUEtJWF9FQ0RTQV9QMjU2X1NIQV8yNTYiLAogICAgICAgICAgICAgICAgInZhbGlkRm9yIjogewogICAgICAgICAgICAgICAgICAgICJzdGFydCI6ICIxOTk5LTAxLTAxVDAwOjAwOjAwLjAwMFoiCiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICB9LAogICAgICAgIHsKICAgICAgICAgICAgImtleUlkIjogIlNIQTI1NjpqbDNid3N3dTgwUGpqb2tDZ2gwbzJ3NWMyVTRMaFFBRTU3Z2o5Y3oxa3pBIiwKICAgICAgICAgICAgImtleVVzYWdlIjogIm5wbTphdHRlc3RhdGlvbnMiLAogICAgICAgICAgICAicHVibGljS2V5IjogewogICAgICAgICAgICAgICAgInJhd0J5dGVzIjogIk1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRTFPbGIzek1BRkZ4WEtIaUlrUU81Y0ozWWhsNWk2VVBwK0lodXRlQkpidUhjQTVVb2dLbzBFV3RsV3dXNktTYUtvVE5FWUw3SmxDUWlWbmtoQmt0VWdnPT0iLAogICAgICAgICAgICAgICAgImtleURldGFpbHMiOiAiUEtJWF9FQ0RTQV9QMjU2X1NIQV8yNTYiLAogICAgICAgICAgICAgICAgInZhbGlkRm9yIjogewogICAgICAgICAgICAgICAgICAgICJzdGFydCI6ICIyMDIyLTEyLTAxVDAwOjAwOjAwLjAwMFoiCiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICB9CiAgICBdCn0K"}}}
PK~\Y֋&&@sigstore/verify/package.jsonnu[{
  "_id": "@sigstore/verify@1.2.1",
  "_inBundle": true,
  "_location": "/npm/@sigstore/verify",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm/sigstore"
  ],
  "author": {
    "name": "bdehamer@github.com"
  },
  "bugs": {
    "url": "https://github.com/sigstore/sigstore-js/issues"
  },
  "dependencies": {
    "@sigstore/bundle": "^2.3.2",
    "@sigstore/core": "^1.1.0",
    "@sigstore/protobuf-specs": "^0.3.2"
  },
  "description": "Verification of Sigstore signatures",
  "engines": {
    "node": "^16.14.0 || >=18.0.0"
  },
  "files": [
    "dist"
  ],
  "homepage": "https://github.com/sigstore/sigstore-js/tree/main/packages/verify#readme",
  "license": "Apache-2.0",
  "main": "dist/index.js",
  "name": "@sigstore/verify",
  "publishConfig": {
    "provenance": true
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/sigstore/sigstore-js.git"
  },
  "scripts": {
    "build": "tsc --build",
    "clean": "shx rm -rf dist *.tsbuildinfo",
    "test": "jest"
  },
  "types": "dist/index.d.ts",
  "version": "1.2.1"
}
PK~\5Z

"@sigstore/verify/dist/key/index.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.verifyCertificate = exports.verifyPublicKey = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const core_1 = require("@sigstore/core");
const error_1 = require("../error");
const certificate_1 = require("./certificate");
const sct_1 = require("./sct");
const OID_FULCIO_ISSUER_V1 = '1.3.6.1.4.1.57264.1.1';
const OID_FULCIO_ISSUER_V2 = '1.3.6.1.4.1.57264.1.8';
function verifyPublicKey(hint, timestamps, trustMaterial) {
    const key = trustMaterial.publicKey(hint);
    timestamps.forEach((timestamp) => {
        if (!key.validFor(timestamp)) {
            throw new error_1.VerificationError({
                code: 'PUBLIC_KEY_ERROR',
                message: `Public key is not valid for timestamp: ${timestamp.toISOString()}`,
            });
        }
    });
    return { key: key.publicKey };
}
exports.verifyPublicKey = verifyPublicKey;
function verifyCertificate(leaf, timestamps, trustMaterial) {
    // Check that leaf certificate chains to a trusted CA
    const path = (0, certificate_1.verifyCertificateChain)(leaf, trustMaterial.certificateAuthorities);
    // Check that ALL certificates are valid for ALL of the timestamps
    const validForDate = timestamps.every((timestamp) => path.every((cert) => cert.validForDate(timestamp)));
    if (!validForDate) {
        throw new error_1.VerificationError({
            code: 'CERTIFICATE_ERROR',
            message: 'certificate is not valid or expired at the specified date',
        });
    }
    return {
        scts: (0, sct_1.verifySCTs)(path[0], path[1], trustMaterial.ctlogs),
        signer: getSigner(path[0]),
    };
}
exports.verifyCertificate = verifyCertificate;
function getSigner(cert) {
    let issuer;
    const issuerExtension = cert.extension(OID_FULCIO_ISSUER_V2);
    if (issuerExtension) {
        issuer = issuerExtension.valueObj.subs?.[0]?.value.toString('ascii');
    }
    else {
        issuer = cert.extension(OID_FULCIO_ISSUER_V1)?.value.toString('ascii');
    }
    const identity = {
        extensions: { issuer },
        subjectAlternativeName: cert.subjectAltName,
    };
    return {
        key: core_1.crypto.createPublicKey(cert.publicKey),
        identity,
    };
}
PK~\v
5 5 (@sigstore/verify/dist/key/certificate.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CertificateChainVerifier = exports.verifyCertificateChain = void 0;
const error_1 = require("../error");
const trust_1 = require("../trust");
function verifyCertificateChain(leaf, certificateAuthorities) {
    // Filter list of trusted CAs to those which are valid for the given
    // leaf certificate.
    const cas = (0, trust_1.filterCertAuthorities)(certificateAuthorities, {
        start: leaf.notBefore,
        end: leaf.notAfter,
    });
    /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
    let error;
    for (const ca of cas) {
        try {
            const verifier = new CertificateChainVerifier({
                trustedCerts: ca.certChain,
                untrustedCert: leaf,
            });
            return verifier.verify();
        }
        catch (err) {
            error = err;
        }
    }
    // If we failed to verify the certificate chain for all of the trusted
    // CAs, throw the last error we encountered.
    throw new error_1.VerificationError({
        code: 'CERTIFICATE_ERROR',
        message: 'Failed to verify certificate chain',
        cause: error,
    });
}
exports.verifyCertificateChain = verifyCertificateChain;
class CertificateChainVerifier {
    constructor(opts) {
        this.untrustedCert = opts.untrustedCert;
        this.trustedCerts = opts.trustedCerts;
        this.localCerts = dedupeCertificates([
            ...opts.trustedCerts,
            opts.untrustedCert,
        ]);
    }
    verify() {
        // Construct certificate path from leaf to root
        const certificatePath = this.sort();
        // Perform validation checks on each certificate in the path
        this.checkPath(certificatePath);
        // Return verified certificate path
        return certificatePath;
    }
    sort() {
        const leafCert = this.untrustedCert;
        // Construct all possible paths from the leaf
        let paths = this.buildPaths(leafCert);
        // Filter for paths which contain a trusted certificate
        paths = paths.filter((path) => path.some((cert) => this.trustedCerts.includes(cert)));
        if (paths.length === 0) {
            throw new error_1.VerificationError({
                code: 'CERTIFICATE_ERROR',
                message: 'no trusted certificate path found',
            });
        }
        // Find the shortest of possible paths
        /* istanbul ignore next */
        const path = paths.reduce((prev, curr) => prev.length < curr.length ? prev : curr);
        // Construct chain from shortest path
        // Removes the last certificate in the path, which will be a second copy
        // of the root certificate given that the root is self-signed.
        return [leafCert, ...path].slice(0, -1);
    }
    // Recursively build all possible paths from the leaf to the root
    buildPaths(certificate) {
        const paths = [];
        const issuers = this.findIssuer(certificate);
        if (issuers.length === 0) {
            throw new error_1.VerificationError({
                code: 'CERTIFICATE_ERROR',
                message: 'no valid certificate path found',
            });
        }
        for (let i = 0; i < issuers.length; i++) {
            const issuer = issuers[i];
            // Base case - issuer is self
            if (issuer.equals(certificate)) {
                paths.push([certificate]);
                continue;
            }
            // Recursively build path for the issuer
            const subPaths = this.buildPaths(issuer);
            // Construct paths by appending the issuer to each subpath
            for (let j = 0; j < subPaths.length; j++) {
                paths.push([issuer, ...subPaths[j]]);
            }
        }
        return paths;
    }
    // Return all possible issuers for the given certificate
    findIssuer(certificate) {
        let issuers = [];
        let keyIdentifier;
        // Exit early if the certificate is self-signed
        if (certificate.subject.equals(certificate.issuer)) {
            if (certificate.verify()) {
                return [certificate];
            }
        }
        // If the certificate has an authority key identifier, use that
        // to find the issuer
        if (certificate.extAuthorityKeyID) {
            keyIdentifier = certificate.extAuthorityKeyID.keyIdentifier;
            // TODO: Add support for authorityCertIssuer/authorityCertSerialNumber
            // though Fulcio doesn't appear to use these
        }
        // Find possible issuers by comparing the authorityKeyID/subjectKeyID
        // or issuer/subject. Potential issuers are added to the result array.
        this.localCerts.forEach((possibleIssuer) => {
            if (keyIdentifier) {
                if (possibleIssuer.extSubjectKeyID) {
                    if (possibleIssuer.extSubjectKeyID.keyIdentifier.equals(keyIdentifier)) {
                        issuers.push(possibleIssuer);
                    }
                    return;
                }
            }
            // Fallback to comparing certificate issuer and subject if
            // subjectKey/authorityKey extensions are not present
            if (possibleIssuer.subject.equals(certificate.issuer)) {
                issuers.push(possibleIssuer);
            }
        });
        // Remove any issuers which fail to verify the certificate
        issuers = issuers.filter((issuer) => {
            try {
                return certificate.verify(issuer);
            }
            catch (ex) {
                /* istanbul ignore next - should never error */
                return false;
            }
        });
        return issuers;
    }
    checkPath(path) {
        /* istanbul ignore if */
        if (path.length < 1) {
            throw new error_1.VerificationError({
                code: 'CERTIFICATE_ERROR',
                message: 'certificate chain must contain at least one certificate',
            });
        }
        // Ensure that all certificates beyond the leaf are CAs
        const validCAs = path.slice(1).every((cert) => cert.isCA);
        if (!validCAs) {
            throw new error_1.VerificationError({
                code: 'CERTIFICATE_ERROR',
                message: 'intermediate certificate is not a CA',
            });
        }
        // Certificate's issuer must match the subject of the next certificate
        // in the chain
        for (let i = path.length - 2; i >= 0; i--) {
            /* istanbul ignore if */
            if (!path[i].issuer.equals(path[i + 1].subject)) {
                throw new error_1.VerificationError({
                    code: 'CERTIFICATE_ERROR',
                    message: 'incorrect certificate name chaining',
                });
            }
        }
        // Check pathlength constraints
        for (let i = 0; i < path.length; i++) {
            const cert = path[i];
            // If the certificate is a CA, check the path length
            if (cert.extBasicConstraints?.isCA) {
                const pathLength = cert.extBasicConstraints.pathLenConstraint;
                // The path length, if set, indicates how many intermediate
                // certificates (NOT including the leaf) are allowed to follow. The
                // pathLength constraint of any intermediate CA certificate MUST be
                // greater than or equal to it's own depth in the chain (with an
                // adjustment for the leaf certificate)
                if (pathLength !== undefined && pathLength < i - 1) {
                    throw new error_1.VerificationError({
                        code: 'CERTIFICATE_ERROR',
                        message: 'path length constraint exceeded',
                    });
                }
            }
        }
    }
}
exports.CertificateChainVerifier = CertificateChainVerifier;
// Remove duplicate certificates from the array
function dedupeCertificates(certs) {
    for (let i = 0; i < certs.length; i++) {
        for (let j = i + 1; j < certs.length; j++) {
            if (certs[i].equals(certs[j])) {
                certs.splice(j, 1);
                j--;
            }
        }
    }
    return certs;
}
PK~\
c @sigstore/verify/dist/key/sct.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.verifySCTs = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const core_1 = require("@sigstore/core");
const error_1 = require("../error");
const trust_1 = require("../trust");
function verifySCTs(cert, issuer, ctlogs) {
    let extSCT;
    // Verifying the SCT requires that we remove the SCT extension and
    // re-encode the TBS structure to DER -- this value is part of the data
    // over which the signature is calculated. Since this is a destructive action
    // we create a copy of the certificate so we can remove the SCT extension
    // without affecting the original certificate.
    const clone = cert.clone();
    // Intentionally not using the findExtension method here because we want to
    // remove the the SCT extension from the certificate before calculating the
    // PreCert structure
    for (let i = 0; i < clone.extensions.length; i++) {
        const ext = clone.extensions[i];
        if (ext.subs[0].toOID() === core_1.EXTENSION_OID_SCT) {
            extSCT = new core_1.X509SCTExtension(ext);
            // Remove the extension from the certificate
            clone.extensions.splice(i, 1);
            break;
        }
    }
    // No SCT extension found to verify
    if (!extSCT) {
        return [];
    }
    // Found an SCT extension but it has no SCTs
    /* istanbul ignore if -- too difficult to fabricate test case for this */
    if (extSCT.signedCertificateTimestamps.length === 0) {
        return [];
    }
    // Construct the PreCert structure
    // https://www.rfc-editor.org/rfc/rfc6962#section-3.2
    const preCert = new core_1.ByteStream();
    // Calculate hash of the issuer's public key
    const issuerId = core_1.crypto.hash(issuer.publicKey);
    preCert.appendView(issuerId);
    // Re-encodes the certificate to DER after removing the SCT extension
    const tbs = clone.tbsCertificate.toDER();
    preCert.appendUint24(tbs.length);
    preCert.appendView(tbs);
    // Calculate and return the verification results for each SCT
    return extSCT.signedCertificateTimestamps.map((sct) => {
        // Find the ctlog instance that corresponds to the SCT's logID
        const validCTLogs = (0, trust_1.filterTLogAuthorities)(ctlogs, {
            logID: sct.logID,
            targetDate: sct.datetime,
        });
        // See if the SCT is valid for any of the CT logs
        const verified = validCTLogs.some((log) => sct.verify(preCert.buffer, log.publicKey));
        if (!verified) {
            throw new error_1.VerificationError({
                code: 'CERTIFICATE_ERROR',
                message: 'SCT verification failed',
            });
        }
        return sct.logID;
    });
}
exports.verifySCTs = verifySCTs;
PK~\8Ǭ)@sigstore/verify/dist/timestamp/merkle.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.verifyMerkleInclusion = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const core_1 = require("@sigstore/core");
const error_1 = require("../error");
const RFC6962_LEAF_HASH_PREFIX = Buffer.from([0x00]);
const RFC6962_NODE_HASH_PREFIX = Buffer.from([0x01]);
function verifyMerkleInclusion(entry) {
    const inclusionProof = entry.inclusionProof;
    const logIndex = BigInt(inclusionProof.logIndex);
    const treeSize = BigInt(inclusionProof.treeSize);
    if (logIndex < 0n || logIndex >= treeSize) {
        throw new error_1.VerificationError({
            code: 'TLOG_INCLUSION_PROOF_ERROR',
            message: `invalid index: ${logIndex}`,
        });
    }
    // Figure out which subset of hashes corresponds to the inner and border
    // nodes
    const { inner, border } = decompInclProof(logIndex, treeSize);
    if (inclusionProof.hashes.length !== inner + border) {
        throw new error_1.VerificationError({
            code: 'TLOG_INCLUSION_PROOF_ERROR',
            message: 'invalid hash count',
        });
    }
    const innerHashes = inclusionProof.hashes.slice(0, inner);
    const borderHashes = inclusionProof.hashes.slice(inner);
    // The entry's hash is the leaf hash
    const leafHash = hashLeaf(entry.canonicalizedBody);
    // Chain the hashes belonging to the inner and border portions
    const calculatedHash = chainBorderRight(chainInner(leafHash, innerHashes, logIndex), borderHashes);
    // Calculated hash should match the root hash in the inclusion proof
    if (!core_1.crypto.bufferEqual(calculatedHash, inclusionProof.rootHash)) {
        throw new error_1.VerificationError({
            code: 'TLOG_INCLUSION_PROOF_ERROR',
            message: 'calculated root hash does not match inclusion proof',
        });
    }
}
exports.verifyMerkleInclusion = verifyMerkleInclusion;
// Breaks down inclusion proof for a leaf at the specified index in a tree of
// the specified size. The split point is where paths to the index leaf and
// the (size - 1) leaf diverge. Returns lengths of the bottom and upper proof
// parts.
function decompInclProof(index, size) {
    const inner = innerProofSize(index, size);
    const border = onesCount(index >> BigInt(inner));
    return { inner, border };
}
// Computes a subtree hash for a node on or below the tree's right border.
// Assumes the provided proof hashes are ordered from lower to higher levels
// and seed is the initial hash of the node specified by the index.
function chainInner(seed, hashes, index) {
    return hashes.reduce((acc, h, i) => {
        if ((index >> BigInt(i)) & BigInt(1)) {
            return hashChildren(h, acc);
        }
        else {
            return hashChildren(acc, h);
        }
    }, seed);
}
// Computes a subtree hash for nodes along the tree's right border.
function chainBorderRight(seed, hashes) {
    return hashes.reduce((acc, h) => hashChildren(h, acc), seed);
}
function innerProofSize(index, size) {
    return bitLength(index ^ (size - BigInt(1)));
}
// Counts the number of ones in the binary representation of the given number.
// https://en.wikipedia.org/wiki/Hamming_weight
function onesCount(num) {
    return num.toString(2).split('1').length - 1;
}
// Returns the number of bits necessary to represent an integer in binary.
function bitLength(n) {
    if (n === 0n) {
        return 0;
    }
    return n.toString(2).length;
}
// Hashing logic according to RFC6962.
// https://datatracker.ietf.org/doc/html/rfc6962#section-2
function hashChildren(left, right) {
    return core_1.crypto.hash(RFC6962_NODE_HASH_PREFIX, left, right);
}
function hashLeaf(leaf) {
    return core_1.crypto.hash(RFC6962_LEAF_HASH_PREFIX, leaf);
}
PK~\G5
5
&@sigstore/verify/dist/timestamp/set.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.verifyTLogSET = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const core_1 = require("@sigstore/core");
const error_1 = require("../error");
const trust_1 = require("../trust");
// Verifies the SET for the given entry against the list of trusted
// transparency logs. Returns true if the SET can be verified against at least
// one of the trusted logs; otherwise, returns false.
function verifyTLogSET(entry, tlogs) {
    // Filter the list of tlog instances to only those which might be able to
    // verify the SET
    const validTLogs = (0, trust_1.filterTLogAuthorities)(tlogs, {
        logID: entry.logId.keyId,
        targetDate: new Date(Number(entry.integratedTime) * 1000),
    });
    // Check to see if we can verify the SET against any of the valid tlogs
    const verified = validTLogs.some((tlog) => {
        // Re-create the original Rekor verification payload
        const payload = toVerificationPayload(entry);
        // Canonicalize the payload and turn into a buffer for verification
        const data = Buffer.from(core_1.json.canonicalize(payload), 'utf8');
        // Extract the SET from the tlog entry
        const signature = entry.inclusionPromise.signedEntryTimestamp;
        return core_1.crypto.verify(data, tlog.publicKey, signature);
    });
    if (!verified) {
        throw new error_1.VerificationError({
            code: 'TLOG_INCLUSION_PROMISE_ERROR',
            message: 'inclusion promise could not be verified',
        });
    }
}
exports.verifyTLogSET = verifyTLogSET;
// Returns a properly formatted "VerificationPayload" for one of the
// transaction log entires in the given bundle which can be used for SET
// verification.
function toVerificationPayload(entry) {
    const { integratedTime, logIndex, logId, canonicalizedBody } = entry;
    return {
        body: canonicalizedBody.toString('base64'),
        integratedTime: Number(integratedTime),
        logIndex: Number(logIndex),
        logID: logId.keyId.toString('hex'),
    };
}
PK~\_{1(@sigstore/verify/dist/timestamp/index.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.verifyTLogTimestamp = exports.verifyTSATimestamp = void 0;
const error_1 = require("../error");
const checkpoint_1 = require("./checkpoint");
const merkle_1 = require("./merkle");
const set_1 = require("./set");
const tsa_1 = require("./tsa");
function verifyTSATimestamp(timestamp, data, timestampAuthorities) {
    (0, tsa_1.verifyRFC3161Timestamp)(timestamp, data, timestampAuthorities);
    return {
        type: 'timestamp-authority',
        logID: timestamp.signerSerialNumber,
        timestamp: timestamp.signingTime,
    };
}
exports.verifyTSATimestamp = verifyTSATimestamp;
function verifyTLogTimestamp(entry, tlogAuthorities) {
    let inclusionVerified = false;
    if (isTLogEntryWithInclusionPromise(entry)) {
        (0, set_1.verifyTLogSET)(entry, tlogAuthorities);
        inclusionVerified = true;
    }
    if (isTLogEntryWithInclusionProof(entry)) {
        (0, merkle_1.verifyMerkleInclusion)(entry);
        (0, checkpoint_1.verifyCheckpoint)(entry, tlogAuthorities);
        inclusionVerified = true;
    }
    if (!inclusionVerified) {
        throw new error_1.VerificationError({
            code: 'TLOG_MISSING_INCLUSION_ERROR',
            message: 'inclusion could not be verified',
        });
    }
    return {
        type: 'transparency-log',
        logID: entry.logId.keyId,
        timestamp: new Date(Number(entry.integratedTime) * 1000),
    };
}
exports.verifyTLogTimestamp = verifyTLogTimestamp;
function isTLogEntryWithInclusionPromise(entry) {
    return entry.inclusionPromise !== undefined;
}
function isTLogEntryWithInclusionProof(entry) {
    return entry.inclusionProof !== undefined;
}
PK~\tOPP-@sigstore/verify/dist/timestamp/checkpoint.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.verifyCheckpoint = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const core_1 = require("@sigstore/core");
const error_1 = require("../error");
const trust_1 = require("../trust");
// Separator between the note and the signatures in a checkpoint
const CHECKPOINT_SEPARATOR = '\n\n';
// Checkpoint signatures are of the following form:
// "–  \n"
// where:
// - the prefix is an emdash (U+2014).
// -  gives a human-readable representation of the signing ID.
// -  is the first 4 bytes of the SHA256 hash of the
//   associated public key followed by the signature bytes.
const SIGNATURE_REGEX = /\u2014 (\S+) (\S+)\n/g;
// Verifies the checkpoint value in the given tlog entry. There are two steps
// to the verification:
// 1. Verify that all signatures in the checkpoint can be verified against a
//    trusted public key
// 2. Verify that the root hash in the checkpoint matches the root hash in the
//    inclusion proof
// See: https://github.com/transparency-dev/formats/blob/main/log/README.md
function verifyCheckpoint(entry, tlogs) {
    // Filter tlog instances to just those which were valid at the time of the
    // entry
    const validTLogs = (0, trust_1.filterTLogAuthorities)(tlogs, {
        targetDate: new Date(Number(entry.integratedTime) * 1000),
    });
    const inclusionProof = entry.inclusionProof;
    const signedNote = SignedNote.fromString(inclusionProof.checkpoint.envelope);
    const checkpoint = LogCheckpoint.fromString(signedNote.note);
    // Verify that the signatures in the checkpoint are all valid
    if (!verifySignedNote(signedNote, validTLogs)) {
        throw new error_1.VerificationError({
            code: 'TLOG_INCLUSION_PROOF_ERROR',
            message: 'invalid checkpoint signature',
        });
    }
    // Verify that the root hash from the checkpoint matches the root hash in the
    // inclusion proof
    if (!core_1.crypto.bufferEqual(checkpoint.logHash, inclusionProof.rootHash)) {
        throw new error_1.VerificationError({
            code: 'TLOG_INCLUSION_PROOF_ERROR',
            message: 'root hash mismatch',
        });
    }
}
exports.verifyCheckpoint = verifyCheckpoint;
// Verifies the signatures in the SignedNote. For each signature, the
// corresponding transparency log is looked up by the key hint and the
// signature is verified against the public key in the transparency log.
// Throws an error if any of the signatures are invalid.
function verifySignedNote(signedNote, tlogs) {
    const data = Buffer.from(signedNote.note, 'utf-8');
    return signedNote.signatures.every((signature) => {
        // Find the transparency log instance with the matching key hint
        const tlog = tlogs.find((tlog) => core_1.crypto.bufferEqual(tlog.logID.subarray(0, 4), signature.keyHint));
        if (!tlog) {
            return false;
        }
        return core_1.crypto.verify(data, tlog.publicKey, signature.signature);
    });
}
// SignedNote represents a signed note from a transparency log checkpoint. Consists
// of a body (or note) and one more signatures calculated over the body. See
// https://github.com/transparency-dev/formats/blob/main/log/README.md#signed-envelope
class SignedNote {
    constructor(note, signatures) {
        this.note = note;
        this.signatures = signatures;
    }
    // Deserialize a SignedNote from a string
    static fromString(envelope) {
        if (!envelope.includes(CHECKPOINT_SEPARATOR)) {
            throw new error_1.VerificationError({
                code: 'TLOG_INCLUSION_PROOF_ERROR',
                message: 'missing checkpoint separator',
            });
        }
        // Split the note into the header and the data portions at the separator
        const split = envelope.indexOf(CHECKPOINT_SEPARATOR);
        const header = envelope.slice(0, split + 1);
        const data = envelope.slice(split + CHECKPOINT_SEPARATOR.length);
        // Find all the signature lines in the data portion
        const matches = data.matchAll(SIGNATURE_REGEX);
        // Parse each of the matched signature lines into the name and signature.
        // The first four bytes of the signature are the key hint (should match the
        // first four bytes of the log ID), and the rest is the signature itself.
        const signatures = Array.from(matches, (match) => {
            const [, name, signature] = match;
            const sigBytes = Buffer.from(signature, 'base64');
            if (sigBytes.length < 5) {
                throw new error_1.VerificationError({
                    code: 'TLOG_INCLUSION_PROOF_ERROR',
                    message: 'malformed checkpoint signature',
                });
            }
            return {
                name,
                keyHint: sigBytes.subarray(0, 4),
                signature: sigBytes.subarray(4),
            };
        });
        if (signatures.length === 0) {
            throw new error_1.VerificationError({
                code: 'TLOG_INCLUSION_PROOF_ERROR',
                message: 'no signatures found in checkpoint',
            });
        }
        return new SignedNote(header, signatures);
    }
}
// LogCheckpoint represents a transparency log checkpoint. Consists of the
// following:
//  - origin: the name of the transparency log
//  - logSize: the size of the log at the time of the checkpoint
//  - logHash: the root hash of the log at the time of the checkpoint
//  - rest: the rest of the checkpoint body, which is a list of log entries
// See:
// https://github.com/transparency-dev/formats/blob/main/log/README.md#checkpoint-body
class LogCheckpoint {
    constructor(origin, logSize, logHash, rest) {
        this.origin = origin;
        this.logSize = logSize;
        this.logHash = logHash;
        this.rest = rest;
    }
    static fromString(note) {
        const lines = note.trimEnd().split('\n');
        if (lines.length < 3) {
            throw new error_1.VerificationError({
                code: 'TLOG_INCLUSION_PROOF_ERROR',
                message: 'too few lines in checkpoint header',
            });
        }
        const origin = lines[0];
        const logSize = BigInt(lines[1]);
        const rootHash = Buffer.from(lines[2], 'base64');
        const rest = lines.slice(3);
        return new LogCheckpoint(origin, logSize, rootHash, rest);
    }
}
PK~\™&@sigstore/verify/dist/timestamp/tsa.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.verifyRFC3161Timestamp = void 0;
const core_1 = require("@sigstore/core");
const error_1 = require("../error");
const certificate_1 = require("../key/certificate");
const trust_1 = require("../trust");
function verifyRFC3161Timestamp(timestamp, data, timestampAuthorities) {
    const signingTime = timestamp.signingTime;
    // Filter for CAs which were valid at the time of signing
    timestampAuthorities = (0, trust_1.filterCertAuthorities)(timestampAuthorities, {
        start: signingTime,
        end: signingTime,
    });
    // Filter for CAs which match serial and issuer embedded in the timestamp
    timestampAuthorities = filterCAsBySerialAndIssuer(timestampAuthorities, {
        serialNumber: timestamp.signerSerialNumber,
        issuer: timestamp.signerIssuer,
    });
    // Check that we can verify the timestamp with AT LEAST ONE of the remaining
    // CAs
    const verified = timestampAuthorities.some((ca) => {
        try {
            verifyTimestampForCA(timestamp, data, ca);
            return true;
        }
        catch (e) {
            return false;
        }
    });
    if (!verified) {
        throw new error_1.VerificationError({
            code: 'TIMESTAMP_ERROR',
            message: 'timestamp could not be verified',
        });
    }
}
exports.verifyRFC3161Timestamp = verifyRFC3161Timestamp;
function verifyTimestampForCA(timestamp, data, ca) {
    const [leaf, ...cas] = ca.certChain;
    const signingKey = core_1.crypto.createPublicKey(leaf.publicKey);
    const signingTime = timestamp.signingTime;
    // Verify the certificate chain for the provided CA
    try {
        new certificate_1.CertificateChainVerifier({
            untrustedCert: leaf,
            trustedCerts: cas,
        }).verify();
    }
    catch (e) {
        throw new error_1.VerificationError({
            code: 'TIMESTAMP_ERROR',
            message: 'invalid certificate chain',
        });
    }
    // Check that all of the CA certs were valid at the time of signing
    const validAtSigningTime = ca.certChain.every((cert) => cert.validForDate(signingTime));
    if (!validAtSigningTime) {
        throw new error_1.VerificationError({
            code: 'TIMESTAMP_ERROR',
            message: 'timestamp was signed with an expired certificate',
        });
    }
    // Check that the signing certificate's key can be used to verify the
    // timestamp signature.
    timestamp.verify(data, signingKey);
}
// Filters the list of CAs to those which have a leaf signing certificate which
// matches the given serial number and issuer.
function filterCAsBySerialAndIssuer(timestampAuthorities, criteria) {
    return timestampAuthorities.filter((ca) => ca.certChain.length > 0 &&
        core_1.crypto.bufferEqual(ca.certChain[0].serialNumber, criteria.serialNumber) &&
        core_1.crypto.bufferEqual(ca.certChain[0].issuer, criteria.issuer));
}
PK~\-TMM%@sigstore/verify/dist/shared.types.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
PK~\@sigstore/verify/dist/index.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Verifier = exports.toTrustMaterial = exports.VerificationError = exports.PolicyError = exports.toSignedEntity = void 0;
/* istanbul ignore file */
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var bundle_1 = require("./bundle");
Object.defineProperty(exports, "toSignedEntity", { enumerable: true, get: function () { return bundle_1.toSignedEntity; } });
var error_1 = require("./error");
Object.defineProperty(exports, "PolicyError", { enumerable: true, get: function () { return error_1.PolicyError; } });
Object.defineProperty(exports, "VerificationError", { enumerable: true, get: function () { return error_1.VerificationError; } });
var trust_1 = require("./trust");
Object.defineProperty(exports, "toTrustMaterial", { enumerable: true, get: function () { return trust_1.toTrustMaterial; } });
var verifier_1 = require("./verifier");
Object.defineProperty(exports, "Verifier", { enumerable: true, get: function () { return verifier_1.Verifier; } });
PK~\&sTDD'@sigstore/verify/dist/bundle/message.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MessageSignatureContent = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const core_1 = require("@sigstore/core");
class MessageSignatureContent {
    constructor(messageSignature, artifact) {
        this.signature = messageSignature.signature;
        this.messageDigest = messageSignature.messageDigest.digest;
        this.artifact = artifact;
    }
    compareSignature(signature) {
        return core_1.crypto.bufferEqual(signature, this.signature);
    }
    compareDigest(digest) {
        return core_1.crypto.bufferEqual(digest, this.messageDigest);
    }
    verifySignature(key) {
        return core_1.crypto.verify(this.artifact, key, this.signature);
    }
}
exports.MessageSignatureContent = MessageSignatureContent;
PK~\%_AA%@sigstore/verify/dist/bundle/index.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.signatureContent = exports.toSignedEntity = void 0;
const core_1 = require("@sigstore/core");
const dsse_1 = require("./dsse");
const message_1 = require("./message");
function toSignedEntity(bundle, artifact) {
    const { tlogEntries, timestampVerificationData } = bundle.verificationMaterial;
    const timestamps = [];
    for (const entry of tlogEntries) {
        timestamps.push({
            $case: 'transparency-log',
            tlogEntry: entry,
        });
    }
    for (const ts of timestampVerificationData?.rfc3161Timestamps ?? []) {
        timestamps.push({
            $case: 'timestamp-authority',
            timestamp: core_1.RFC3161Timestamp.parse(ts.signedTimestamp),
        });
    }
    return {
        signature: signatureContent(bundle, artifact),
        key: key(bundle),
        tlogEntries,
        timestamps,
    };
}
exports.toSignedEntity = toSignedEntity;
function signatureContent(bundle, artifact) {
    switch (bundle.content.$case) {
        case 'dsseEnvelope':
            return new dsse_1.DSSESignatureContent(bundle.content.dsseEnvelope);
        case 'messageSignature':
            return new message_1.MessageSignatureContent(bundle.content.messageSignature, artifact);
    }
}
exports.signatureContent = signatureContent;
function key(bundle) {
    switch (bundle.verificationMaterial.content.$case) {
        case 'publicKey':
            return {
                $case: 'public-key',
                hint: bundle.verificationMaterial.content.publicKey.hint,
            };
        case 'x509CertificateChain':
            return {
                $case: 'certificate',
                certificate: core_1.X509Certificate.parse(bundle.verificationMaterial.content.x509CertificateChain
                    .certificates[0].rawBytes),
            };
        case 'certificate':
            return {
                $case: 'certificate',
                certificate: core_1.X509Certificate.parse(bundle.verificationMaterial.content.certificate.rawBytes),
            };
    }
}
PK~\ƯSu$@sigstore/verify/dist/bundle/dsse.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DSSESignatureContent = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const core_1 = require("@sigstore/core");
class DSSESignatureContent {
    constructor(env) {
        this.env = env;
    }
    compareDigest(digest) {
        return core_1.crypto.bufferEqual(digest, core_1.crypto.hash(this.env.payload));
    }
    compareSignature(signature) {
        return core_1.crypto.bufferEqual(signature, this.signature);
    }
    verifySignature(key) {
        return core_1.crypto.verify(this.preAuthEncoding, key, this.signature);
    }
    get signature() {
        return this.env.signatures.length > 0
            ? this.env.signatures[0].sig
            : Buffer.from('');
    }
    // DSSE Pre-Authentication Encoding
    get preAuthEncoding() {
        return core_1.dsse.preAuthEncoding(this.env.payloadType, this.env.payload);
    }
}
exports.DSSESignatureContent = DSSESignatureContent;
PK~\9uT#@sigstore/verify/dist/tlog/index.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.verifyTLogBody = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const error_1 = require("../error");
const dsse_1 = require("./dsse");
const hashedrekord_1 = require("./hashedrekord");
const intoto_1 = require("./intoto");
// Verifies that the given tlog entry matches the supplied signature content.
function verifyTLogBody(entry, sigContent) {
    const { kind, version } = entry.kindVersion;
    const body = JSON.parse(entry.canonicalizedBody.toString('utf8'));
    if (kind !== body.kind || version !== body.apiVersion) {
        throw new error_1.VerificationError({
            code: 'TLOG_BODY_ERROR',
            message: `kind/version mismatch - expected: ${kind}/${version}, received: ${body.kind}/${body.apiVersion}`,
        });
    }
    switch (body.kind) {
        case 'dsse':
            return (0, dsse_1.verifyDSSETLogBody)(body, sigContent);
        case 'intoto':
            return (0, intoto_1.verifyIntotoTLogBody)(body, sigContent);
        case 'hashedrekord':
            return (0, hashedrekord_1.verifyHashedRekordTLogBody)(body, sigContent);
        /* istanbul ignore next */
        default:
            throw new error_1.VerificationError({
                code: 'TLOG_BODY_ERROR',
                message: `unsupported kind: ${kind}`,
            });
    }
}
exports.verifyTLogBody = verifyTLogBody;
PK~\		"@sigstore/verify/dist/tlog/dsse.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.verifyDSSETLogBody = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const error_1 = require("../error");
// Compare the given intoto tlog entry to the given bundle
function verifyDSSETLogBody(tlogEntry, content) {
    switch (tlogEntry.apiVersion) {
        case '0.0.1':
            return verifyDSSE001TLogBody(tlogEntry, content);
        default:
            throw new error_1.VerificationError({
                code: 'TLOG_BODY_ERROR',
                message: `unsupported dsse version: ${tlogEntry.apiVersion}`,
            });
    }
}
exports.verifyDSSETLogBody = verifyDSSETLogBody;
// Compare the given dsse v0.0.1 tlog entry to the given DSSE envelope.
function verifyDSSE001TLogBody(tlogEntry, content) {
    // Ensure the bundle's DSSE only contains a single signature
    if (tlogEntry.spec.signatures?.length !== 1) {
        throw new error_1.VerificationError({
            code: 'TLOG_BODY_ERROR',
            message: 'signature count mismatch',
        });
    }
    const tlogSig = tlogEntry.spec.signatures[0].signature;
    // Ensure that the signature in the bundle's DSSE matches tlog entry
    if (!content.compareSignature(Buffer.from(tlogSig, 'base64')))
        throw new error_1.VerificationError({
            code: 'TLOG_BODY_ERROR',
            message: 'tlog entry signature mismatch',
        });
    // Ensure the digest of the bundle's DSSE payload matches the digest in the
    // tlog entry
    const tlogHash = tlogEntry.spec.payloadHash?.value || '';
    if (!content.compareDigest(Buffer.from(tlogHash, 'hex'))) {
        throw new error_1.VerificationError({
            code: 'TLOG_BODY_ERROR',
            message: 'DSSE payload hash mismatch',
        });
    }
}
PK~\		$@sigstore/verify/dist/tlog/intoto.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.verifyIntotoTLogBody = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const error_1 = require("../error");
// Compare the given intoto tlog entry to the given bundle
function verifyIntotoTLogBody(tlogEntry, content) {
    switch (tlogEntry.apiVersion) {
        case '0.0.2':
            return verifyIntoto002TLogBody(tlogEntry, content);
        default:
            throw new error_1.VerificationError({
                code: 'TLOG_BODY_ERROR',
                message: `unsupported intoto version: ${tlogEntry.apiVersion}`,
            });
    }
}
exports.verifyIntotoTLogBody = verifyIntotoTLogBody;
// Compare the given intoto v0.0.2 tlog entry to the given DSSE envelope.
function verifyIntoto002TLogBody(tlogEntry, content) {
    // Ensure the bundle's DSSE contains a single signature
    if (tlogEntry.spec.content.envelope.signatures?.length !== 1) {
        throw new error_1.VerificationError({
            code: 'TLOG_BODY_ERROR',
            message: 'signature count mismatch',
        });
    }
    // Signature is double-base64-encoded in the tlog entry
    const tlogSig = base64Decode(tlogEntry.spec.content.envelope.signatures[0].sig);
    // Ensure that the signature in the bundle's DSSE matches tlog entry
    if (!content.compareSignature(Buffer.from(tlogSig, 'base64'))) {
        throw new error_1.VerificationError({
            code: 'TLOG_BODY_ERROR',
            message: 'tlog entry signature mismatch',
        });
    }
    // Ensure the digest of the bundle's DSSE payload matches the digest in the
    // tlog entry
    const tlogHash = tlogEntry.spec.content.payloadHash?.value || '';
    if (!content.compareDigest(Buffer.from(tlogHash, 'hex'))) {
        throw new error_1.VerificationError({
            code: 'TLOG_BODY_ERROR',
            message: 'DSSE payload hash mismatch',
        });
    }
}
function base64Decode(str) {
    return Buffer.from(str, 'base64').toString('utf-8');
}
PK~\&E..*@sigstore/verify/dist/tlog/hashedrekord.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.verifyHashedRekordTLogBody = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const error_1 = require("../error");
// Compare the given hashedrekord tlog entry to the given bundle
function verifyHashedRekordTLogBody(tlogEntry, content) {
    switch (tlogEntry.apiVersion) {
        case '0.0.1':
            return verifyHashedrekord001TLogBody(tlogEntry, content);
        default:
            throw new error_1.VerificationError({
                code: 'TLOG_BODY_ERROR',
                message: `unsupported hashedrekord version: ${tlogEntry.apiVersion}`,
            });
    }
}
exports.verifyHashedRekordTLogBody = verifyHashedRekordTLogBody;
// Compare the given hashedrekord v0.0.1 tlog entry to the given message
// signature
function verifyHashedrekord001TLogBody(tlogEntry, content) {
    // Ensure that the bundles message signature matches the tlog entry
    const tlogSig = tlogEntry.spec.signature.content || '';
    if (!content.compareSignature(Buffer.from(tlogSig, 'base64'))) {
        throw new error_1.VerificationError({
            code: 'TLOG_BODY_ERROR',
            message: 'signature mismatch',
        });
    }
    // Ensure that the bundle's message digest matches the tlog entry
    const tlogDigest = tlogEntry.spec.data.hash?.value || '';
    if (!content.compareDigest(Buffer.from(tlogDigest, 'hex'))) {
        throw new error_1.VerificationError({
            code: 'TLOG_BODY_ERROR',
            message: 'digest mismatch',
        });
    }
}
PK~\hh!@sigstore/verify/dist/verifier.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Verifier = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const util_1 = require("util");
const error_1 = require("./error");
const key_1 = require("./key");
const policy_1 = require("./policy");
const timestamp_1 = require("./timestamp");
const tlog_1 = require("./tlog");
class Verifier {
    constructor(trustMaterial, options = {}) {
        this.trustMaterial = trustMaterial;
        this.options = {
            ctlogThreshold: options.ctlogThreshold ?? 1,
            tlogThreshold: options.tlogThreshold ?? 1,
            tsaThreshold: options.tsaThreshold ?? 0,
        };
    }
    verify(entity, policy) {
        const timestamps = this.verifyTimestamps(entity);
        const signer = this.verifySigningKey(entity, timestamps);
        this.verifyTLogs(entity);
        this.verifySignature(entity, signer);
        if (policy) {
            this.verifyPolicy(policy, signer.identity || {});
        }
        return signer;
    }
    // Checks that all of the timestamps in the entity are valid and returns them
    verifyTimestamps(entity) {
        let tlogCount = 0;
        let tsaCount = 0;
        const timestamps = entity.timestamps.map((timestamp) => {
            switch (timestamp.$case) {
                case 'timestamp-authority':
                    tsaCount++;
                    return (0, timestamp_1.verifyTSATimestamp)(timestamp.timestamp, entity.signature.signature, this.trustMaterial.timestampAuthorities);
                case 'transparency-log':
                    tlogCount++;
                    return (0, timestamp_1.verifyTLogTimestamp)(timestamp.tlogEntry, this.trustMaterial.tlogs);
            }
        });
        // Check for duplicate timestamps
        if (containsDupes(timestamps)) {
            throw new error_1.VerificationError({
                code: 'TIMESTAMP_ERROR',
                message: 'duplicate timestamp',
            });
        }
        if (tlogCount < this.options.tlogThreshold) {
            throw new error_1.VerificationError({
                code: 'TIMESTAMP_ERROR',
                message: `expected ${this.options.tlogThreshold} tlog timestamps, got ${tlogCount}`,
            });
        }
        if (tsaCount < this.options.tsaThreshold) {
            throw new error_1.VerificationError({
                code: 'TIMESTAMP_ERROR',
                message: `expected ${this.options.tsaThreshold} tsa timestamps, got ${tsaCount}`,
            });
        }
        return timestamps.map((t) => t.timestamp);
    }
    // Checks that the signing key is valid for all of the the supplied timestamps
    // and returns the signer.
    verifySigningKey({ key }, timestamps) {
        switch (key.$case) {
            case 'public-key': {
                return (0, key_1.verifyPublicKey)(key.hint, timestamps, this.trustMaterial);
            }
            case 'certificate': {
                const result = (0, key_1.verifyCertificate)(key.certificate, timestamps, this.trustMaterial);
                /* istanbul ignore next - no fixture */
                if (containsDupes(result.scts)) {
                    throw new error_1.VerificationError({
                        code: 'CERTIFICATE_ERROR',
                        message: 'duplicate SCT',
                    });
                }
                if (result.scts.length < this.options.ctlogThreshold) {
                    throw new error_1.VerificationError({
                        code: 'CERTIFICATE_ERROR',
                        message: `expected ${this.options.ctlogThreshold} SCTs, got ${result.scts.length}`,
                    });
                }
                return result.signer;
            }
        }
    }
    // Checks that the tlog entries are valid for the supplied content
    verifyTLogs({ signature: content, tlogEntries }) {
        tlogEntries.forEach((entry) => (0, tlog_1.verifyTLogBody)(entry, content));
    }
    // Checks that the signature is valid for the supplied content
    verifySignature(entity, signer) {
        if (!entity.signature.verifySignature(signer.key)) {
            throw new error_1.VerificationError({
                code: 'SIGNATURE_ERROR',
                message: 'signature verification failed',
            });
        }
    }
    verifyPolicy(policy, identity) {
        // Check the subject alternative name of the signer matches the policy
        if (policy.subjectAlternativeName) {
            (0, policy_1.verifySubjectAlternativeName)(policy.subjectAlternativeName, identity.subjectAlternativeName);
        }
        // Check that the extensions of the signer match the policy
        if (policy.extensions) {
            (0, policy_1.verifyExtensions)(policy.extensions, identity.extensions);
        }
    }
}
exports.Verifier = Verifier;
// Checks for duplicate items in the array. Objects are compared using
// deep equality.
function containsDupes(arr) {
    for (let i = 0; i < arr.length; i++) {
        for (let j = i + 1; j < arr.length; j++) {
            if ((0, util_1.isDeepStrictEqual)(arr[i], arr[j])) {
                return true;
            }
        }
    }
    return false;
}
PK~\t5RR@sigstore/verify/dist/policy.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.verifyExtensions = exports.verifySubjectAlternativeName = void 0;
const error_1 = require("./error");
function verifySubjectAlternativeName(policyIdentity, signerIdentity) {
    if (signerIdentity === undefined || !signerIdentity.match(policyIdentity)) {
        throw new error_1.PolicyError({
            code: 'UNTRUSTED_SIGNER_ERROR',
            message: `certificate identity error - expected ${policyIdentity}, got ${signerIdentity}`,
        });
    }
}
exports.verifySubjectAlternativeName = verifySubjectAlternativeName;
function verifyExtensions(policyExtensions, signerExtensions = {}) {
    let key;
    for (key in policyExtensions) {
        if (signerExtensions[key] !== policyExtensions[key]) {
            throw new error_1.PolicyError({
                code: 'UNTRUSTED_SIGNER_ERROR',
                message: `invalid certificate extension - expected ${key}=${policyExtensions[key]}, got ${key}=${signerExtensions[key]}`,
            });
        }
    }
}
exports.verifyExtensions = verifyExtensions;
PK~\Xdd%@sigstore/verify/dist/trust/filter.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.filterTLogAuthorities = exports.filterCertAuthorities = void 0;
function filterCertAuthorities(certAuthorities, criteria) {
    return certAuthorities.filter((ca) => {
        return (ca.validFor.start <= criteria.start && ca.validFor.end >= criteria.end);
    });
}
exports.filterCertAuthorities = filterCertAuthorities;
// Filter the list of tlog instances to only those which match the given log
// ID and have public keys which are valid for the given integrated time.
function filterTLogAuthorities(tlogAuthorities, criteria) {
    return tlogAuthorities.filter((tlog) => {
        // If we're filtering by log ID and the log IDs don't match, we can't use
        // this tlog
        if (criteria.logID && !tlog.logID.equals(criteria.logID)) {
            return false;
        }
        // Check that the integrated time is within the validFor range
        return (tlog.validFor.start <= criteria.targetDate &&
            criteria.targetDate <= tlog.validFor.end);
    });
}
exports.filterTLogAuthorities = filterTLogAuthorities;
PK~\@Y$@sigstore/verify/dist/trust/index.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toTrustMaterial = exports.filterTLogAuthorities = exports.filterCertAuthorities = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const core_1 = require("@sigstore/core");
const protobuf_specs_1 = require("@sigstore/protobuf-specs");
const error_1 = require("../error");
const BEGINNING_OF_TIME = new Date(0);
const END_OF_TIME = new Date(8640000000000000);
var filter_1 = require("./filter");
Object.defineProperty(exports, "filterCertAuthorities", { enumerable: true, get: function () { return filter_1.filterCertAuthorities; } });
Object.defineProperty(exports, "filterTLogAuthorities", { enumerable: true, get: function () { return filter_1.filterTLogAuthorities; } });
function toTrustMaterial(root, keys) {
    const keyFinder = typeof keys === 'function' ? keys : keyLocator(keys);
    return {
        certificateAuthorities: root.certificateAuthorities.map(createCertAuthority),
        timestampAuthorities: root.timestampAuthorities.map(createCertAuthority),
        tlogs: root.tlogs.map(createTLogAuthority),
        ctlogs: root.ctlogs.map(createTLogAuthority),
        publicKey: keyFinder,
    };
}
exports.toTrustMaterial = toTrustMaterial;
function createTLogAuthority(tlogInstance) {
    const keyDetails = tlogInstance.publicKey.keyDetails;
    const keyType = keyDetails === protobuf_specs_1.PublicKeyDetails.PKCS1_RSA_PKCS1V5 ||
        keyDetails === protobuf_specs_1.PublicKeyDetails.PKIX_RSA_PKCS1V5 ||
        keyDetails === protobuf_specs_1.PublicKeyDetails.PKIX_RSA_PKCS1V15_2048_SHA256 ||
        keyDetails === protobuf_specs_1.PublicKeyDetails.PKIX_RSA_PKCS1V15_3072_SHA256 ||
        keyDetails === protobuf_specs_1.PublicKeyDetails.PKIX_RSA_PKCS1V15_4096_SHA256
        ? 'pkcs1'
        : 'spki';
    return {
        logID: tlogInstance.logId.keyId,
        publicKey: core_1.crypto.createPublicKey(tlogInstance.publicKey.rawBytes, keyType),
        validFor: {
            start: tlogInstance.publicKey.validFor?.start || BEGINNING_OF_TIME,
            end: tlogInstance.publicKey.validFor?.end || END_OF_TIME,
        },
    };
}
function createCertAuthority(ca) {
    return {
        certChain: ca.certChain.certificates.map((cert) => {
            return core_1.X509Certificate.parse(cert.rawBytes);
        }),
        validFor: {
            start: ca.validFor?.start || BEGINNING_OF_TIME,
            end: ca.validFor?.end || END_OF_TIME,
        },
    };
}
function keyLocator(keys) {
    return (hint) => {
        const key = (keys || {})[hint];
        if (!key) {
            throw new error_1.VerificationError({
                code: 'PUBLIC_KEY_ERROR',
                message: `key not found: ${hint}`,
            });
        }
        return {
            publicKey: core_1.crypto.createPublicKey(key.rawBytes),
            validFor: (date) => {
                return ((key.validFor?.start || BEGINNING_OF_TIME) <= date &&
                    (key.validFor?.end || END_OF_TIME) >= date);
            },
        };
    };
}
PK~\-TMM*@sigstore/verify/dist/trust/trust.types.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
PK~\Oc55@sigstore/verify/dist/error.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PolicyError = exports.VerificationError = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
class BaseError extends Error {
    constructor({ code, message, cause, }) {
        super(message);
        this.code = code;
        this.cause = cause;
        this.name = this.constructor.name;
    }
}
class VerificationError extends BaseError {
}
exports.VerificationError = VerificationError;
class PolicyError extends BaseError {
}
exports.PolicyError = PolicyError;
PK~\4 cssesc/package.jsonnu[{
  "_id": "cssesc@3.0.0",
  "_inBundle": true,
  "_location": "/npm/cssesc",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm/postcss-selector-parser"
  ],
  "author": {
    "name": "Mathias Bynens",
    "url": "https://mathiasbynens.be/"
  },
  "bin": {
    "cssesc": "bin/cssesc"
  },
  "bugs": {
    "url": "https://github.com/mathiasbynens/cssesc/issues"
  },
  "description": "A JavaScript library for escaping CSS strings and identifiers while generating the shortest possible ASCII-only output.",
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-preset-env": "^1.6.1",
    "codecov": "^1.0.1",
    "grunt": "^1.0.1",
    "grunt-template": "^1.0.0",
    "istanbul": "^0.4.4",
    "mocha": "^2.5.3",
    "regenerate": "^1.2.1",
    "requirejs": "^2.1.16"
  },
  "engines": {
    "node": ">=4"
  },
  "files": [
    "LICENSE-MIT.txt",
    "cssesc.js",
    "bin/",
    "man/"
  ],
  "homepage": "https://mths.be/cssesc",
  "keywords": [
    "css",
    "escape",
    "identifier",
    "string",
    "tool"
  ],
  "license": "MIT",
  "main": "cssesc.js",
  "man": [
    "man/cssesc.1"
  ],
  "name": "cssesc",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/mathiasbynens/cssesc.git"
  },
  "scripts": {
    "build": "grunt template && babel cssesc.js -o cssesc.js",
    "cover": "istanbul cover --report html node_modules/.bin/_mocha tests -- -u exports -R spec",
    "test": "mocha tests"
  },
  "version": "3.0.0"
}
PK~\

cssesc/cssesc.jsnu[/*! https://mths.be/cssesc v3.0.0 by @mathias */
'use strict';

var object = {};
var hasOwnProperty = object.hasOwnProperty;
var merge = function merge(options, defaults) {
	if (!options) {
		return defaults;
	}
	var result = {};
	for (var key in defaults) {
		// `if (defaults.hasOwnProperty(key) { … }` is not needed here, since
		// only recognized option names are used.
		result[key] = hasOwnProperty.call(options, key) ? options[key] : defaults[key];
	}
	return result;
};

var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/;
var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/;
var regexAlwaysEscape = /['"\\]/;
var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;

// https://mathiasbynens.be/notes/css-escapes#css
var cssesc = function cssesc(string, options) {
	options = merge(options, cssesc.options);
	if (options.quotes != 'single' && options.quotes != 'double') {
		options.quotes = 'single';
	}
	var quote = options.quotes == 'double' ? '"' : '\'';
	var isIdentifier = options.isIdentifier;

	var firstChar = string.charAt(0);
	var output = '';
	var counter = 0;
	var length = string.length;
	while (counter < length) {
		var character = string.charAt(counter++);
		var codePoint = character.charCodeAt();
		var value = void 0;
		// If it’s not a printable ASCII character…
		if (codePoint < 0x20 || codePoint > 0x7E) {
			if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) {
				// It’s a high surrogate, and there is a next character.
				var extra = string.charCodeAt(counter++);
				if ((extra & 0xFC00) == 0xDC00) {
					// next character is low surrogate
					codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
				} else {
					// It’s an unmatched surrogate; only append this code unit, in case
					// the next code unit is the high surrogate of a surrogate pair.
					counter--;
				}
			}
			value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
		} else {
			if (options.escapeEverything) {
				if (regexAnySingleEscape.test(character)) {
					value = '\\' + character;
				} else {
					value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
				}
			} else if (/[\t\n\f\r\x0B]/.test(character)) {
				value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
			} else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) {
				value = '\\' + character;
			} else {
				value = character;
			}
		}
		output += value;
	}

	if (isIdentifier) {
		if (/^-[-\d]/.test(output)) {
			output = '\\-' + output.slice(1);
		} else if (/\d/.test(firstChar)) {
			output = '\\3' + firstChar + ' ' + output.slice(1);
		}
	}

	// Remove spaces after `\HEX` escapes that are not followed by a hex digit,
	// since they’re redundant. Note that this is only possible if the escape
	// sequence isn’t preceded by an odd number of backslashes.
	output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) {
		if ($1 && $1.length % 2) {
			// It’s not safe to remove the space, so don’t.
			return $0;
		}
		// Strip the space.
		return ($1 || '') + $2;
	});

	if (!isIdentifier && options.wrap) {
		return quote + output + quote;
	}
	return output;
};

// Expose default options (so they can be overridden globally).
cssesc.options = {
	'escapeEverything': false,
	'isIdentifier': false,
	'quotes': 'single',
	'wrap': false
};

cssesc.version = '3.0.0';

module.exports = cssesc;
PK~\ڌC55cssesc/LICENSE-MIT.txtnu[Copyright Mathias Bynens 

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
PK~\Ucssesc/bin/cssescnu[#!/usr/bin/env node
const fs = require('fs');
const cssesc = require('../cssesc.js');
const strings = process.argv.splice(2);
const stdin = process.stdin;
const options = {};
const log = console.log;

const main = function() {
	const option = strings[0];

	if (/^(?:-h|--help|undefined)$/.test(option)) {
		log(
			'cssesc v%s - https://mths.be/cssesc',
			cssesc.version
		);
		log([
			'\nUsage:\n',
			'\tcssesc [string]',
			'\tcssesc [-i | --identifier] [string]',
			'\tcssesc [-s | --single-quotes] [string]',
			'\tcssesc [-d | --double-quotes] [string]',
			'\tcssesc [-w | --wrap] [string]',
			'\tcssesc [-e | --escape-everything] [string]',
			'\tcssesc [-v | --version]',
			'\tcssesc [-h | --help]',
			'\nExamples:\n',
			'\tcssesc \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\'',
			'\tcssesc --identifier \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\'',
			'\tcssesc --escape-everything \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\'',
			'\tcssesc --double-quotes --wrap \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\'',
			'\techo \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\' | cssesc'
		].join('\n'));
		return process.exit(1);
	}

	if (/^(?:-v|--version)$/.test(option)) {
		log('v%s', cssesc.version);
		return process.exit(1);
	}

	strings.forEach(function(string) {
		// Process options
		if (/^(?:-i|--identifier)$/.test(string)) {
			options.isIdentifier = true;
			return;
		}
		if (/^(?:-s|--single-quotes)$/.test(string)) {
			options.quotes = 'single';
			return;
		}
		if (/^(?:-d|--double-quotes)$/.test(string)) {
			options.quotes = 'double';
			return;
		}
		if (/^(?:-w|--wrap)$/.test(string)) {
			options.wrap = true;
			return;
		}
		if (/^(?:-e|--escape-everything)$/.test(string)) {
			options.escapeEverything = true;
			return;
		}

		// Process string(s)
		let result;
		try {
			result = cssesc(string, options);
			log(result);
		} catch (exception) {
			log(exception.message + '\n');
			log('Error: failed to escape.');
			log('If you think this is a bug in cssesc, please report it:');
			log('https://github.com/mathiasbynens/cssesc/issues/new');
			log(
				'\nStack trace using cssesc@%s:\n',
				cssesc.version
			);
			log(exception.stack);
			return process.exit(1);
		}
	});
	// Return with exit status 0 outside of the `forEach` loop, in case
	// multiple strings were passed in.
	return process.exit(0);

};

if (stdin.isTTY) {
	// handle shell arguments
	main();
} else {
	let timeout;
	// Either the script is called from within a non-TTY context, or `stdin`
	// content is being piped in.
	if (!process.stdout.isTTY) {
		// The script was called from a non-TTY context. This is a rather uncommon
		// use case we don’t actively support. However, we don’t want the script
		// to wait forever in such cases, so…
		timeout = setTimeout(function() {
			// …if no piped data arrived after a whole minute, handle shell
			// arguments instead.
			main();
		}, 60000);
	}
	let data = '';
	stdin.on('data', function(chunk) {
		clearTimeout(timeout);
		data += chunk;
	});
	stdin.on('end', function() {
		strings.push(data.trim());
		main();
	});
	stdin.resume();
}
PK~\޹cssesc/README.mdnu[# cssesc [![Build status](https://travis-ci.org/mathiasbynens/cssesc.svg?branch=master)](https://travis-ci.org/mathiasbynens/cssesc) [![Code coverage status](https://img.shields.io/codecov/c/github/mathiasbynens/cssesc.svg)](https://codecov.io/gh/mathiasbynens/cssesc)

A JavaScript library for escaping CSS strings and identifiers while generating the shortest possible ASCII-only output.

This is a JavaScript library for [escaping text for use in CSS strings or identifiers](https://mathiasbynens.be/notes/css-escapes) while generating the shortest possible valid ASCII-only output. [Here’s an online demo.](https://mothereff.in/css-escapes)

[A polyfill for the CSSOM `CSS.escape()` method is available in a separate repository.](https://mths.be/cssescape) (In comparison, _cssesc_ is much more powerful.)

Feel free to fork if you see possible improvements!

## Installation

Via [npm](https://www.npmjs.com/):

```bash
npm install cssesc
```

In a browser:

```html

```

In [Node.js](https://nodejs.org/):

```js
const cssesc = require('cssesc');
```

In Ruby using [the `ruby-cssesc` wrapper gem](https://github.com/borodean/ruby-cssesc):

```bash
gem install ruby-cssesc
```

```ruby
require 'ruby-cssesc'
CSSEsc.escape('I ♥ Ruby', is_identifier: true)
```

In Sass using [`sassy-escape`](https://github.com/borodean/sassy-escape):

```bash
gem install sassy-escape
```

```scss
body {
  content: escape('I ♥ Sass', $is-identifier: true);
}
```

## API

### `cssesc(value, options)`

This function takes a value and returns an escaped version of the value where any characters that are not printable ASCII symbols are escaped using the shortest possible (but valid) [escape sequences for use in CSS strings or identifiers](https://mathiasbynens.be/notes/css-escapes).

```js
cssesc('Ich ♥ Bücher');
// → 'Ich \\2665  B\\FC cher'

cssesc('foo 𝌆 bar');
// → 'foo \\1D306  bar'
```

By default, `cssesc` returns a string that can be used as part of a CSS string. If the target is a CSS identifier rather than a CSS string, use the `isIdentifier: true` setting (see below).

The optional `options` argument accepts an object with the following options:

#### `isIdentifier`

The default value for the `isIdentifier` option is `false`. This means that the input text will be escaped for use in a CSS string literal. If you want to use the result as a CSS identifier instead (in a selector, for example), set this option to `true`.

```js
cssesc('123a2b');
// → '123a2b'

cssesc('123a2b', {
  'isIdentifier': true
});
// → '\\31 23a2b'
```

#### `quotes`

The default value for the `quotes` option is `'single'`. This means that any occurences of `'` in the input text will be escaped as `\'`, so that the output can be used in a CSS string literal wrapped in single quotes.

```js
cssesc('Lorem ipsum "dolor" sit \'amet\' etc.');
// → 'Lorem ipsum "dolor" sit \\\'amet\\\' etc.'
// → "Lorem ipsum \"dolor\" sit \\'amet\\' etc."

cssesc('Lorem ipsum "dolor" sit \'amet\' etc.', {
  'quotes': 'single'
});
// → 'Lorem ipsum "dolor" sit \\\'amet\\\' etc.'
// → "Lorem ipsum \"dolor\" sit \\'amet\\' etc."
```

If you want to use the output as part of a CSS string literal wrapped in double quotes, set the `quotes` option to `'double'`.

```js
cssesc('Lorem ipsum "dolor" sit \'amet\' etc.', {
  'quotes': 'double'
});
// → 'Lorem ipsum \\"dolor\\" sit \'amet\' etc.'
// → "Lorem ipsum \\\"dolor\\\" sit 'amet' etc."
```

#### `wrap`

The `wrap` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, the output will be a valid CSS string literal wrapped in quotes. The type of quotes can be specified through the `quotes` setting.

```js
cssesc('Lorem ipsum "dolor" sit \'amet\' etc.', {
  'quotes': 'single',
  'wrap': true
});
// → '\'Lorem ipsum "dolor" sit \\\'amet\\\' etc.\''
// → "\'Lorem ipsum \"dolor\" sit \\\'amet\\\' etc.\'"

cssesc('Lorem ipsum "dolor" sit \'amet\' etc.', {
  'quotes': 'double',
  'wrap': true
});
// → '"Lorem ipsum \\"dolor\\" sit \'amet\' etc."'
// → "\"Lorem ipsum \\\"dolor\\\" sit \'amet\' etc.\""
```

#### `escapeEverything`

The `escapeEverything` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, all the symbols in the output will be escaped, even printable ASCII symbols.

```js
cssesc('lolwat"foo\'bar', {
  'escapeEverything': true
});
// → '\\6C\\6F\\6C\\77\\61\\74\\"\\66\\6F\\6F\\\'\\62\\61\\72'
// → "\\6C\\6F\\6C\\77\\61\\74\\\"\\66\\6F\\6F\\'\\62\\61\\72"
```

#### Overriding the default options globally

The global default settings can be overridden by modifying the `css.options` object. This saves you from passing in an `options` object for every call to `encode` if you want to use the non-default setting.

```js
// Read the global default setting for `escapeEverything`:
cssesc.options.escapeEverything;
// → `false` by default

// Override the global default setting for `escapeEverything`:
cssesc.options.escapeEverything = true;

// Using the global default setting for `escapeEverything`, which is now `true`:
cssesc('foo © bar ≠ baz 𝌆 qux');
// → '\\66\\6F\\6F\\ \\A9\\ \\62\\61\\72\\ \\2260\\ \\62\\61\\7A\\ \\1D306\\ \\71\\75\\78'
```

### `cssesc.version`

A string representing the semantic version number.

### Using the `cssesc` binary

To use the `cssesc` binary in your shell, simply install cssesc globally using npm:

```bash
npm install -g cssesc
```

After that you will be able to escape text for use in CSS strings or identifiers from the command line:

```bash
$ cssesc 'föo ♥ bår 𝌆 baz'
f\F6o \2665  b\E5r \1D306  baz
```

If the output needs to be a CSS identifier rather than part of a string literal, use the `-i`/`--identifier` option:

```bash
$ cssesc --identifier 'föo ♥ bår 𝌆 baz'
f\F6o\ \2665\ b\E5r\ \1D306\ baz
```

See `cssesc --help` for the full list of options.

## Support

This library supports the Node.js and browser versions mentioned in [`.babelrc`](https://github.com/mathiasbynens/cssesc/blob/master/.babelrc). For a version that supports a wider variety of legacy browsers and environments out-of-the-box, [see v0.1.0](https://github.com/mathiasbynens/cssesc/releases/tag/v0.1.0).

## Author

| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") |
|---|
| [Mathias Bynens](https://mathiasbynens.be/) |

## License

This library is available under the [MIT](https://mths.be/mit) license.
PK~\jcssesc/man/cssesc.1nu[.Dd August 9, 2013
.Dt cssesc 1
.Sh NAME
.Nm cssesc
.Nd escape text for use in CSS string literals or identifiers
.Sh SYNOPSIS
.Nm
.Op Fl i | -identifier Ar string
.br
.Op Fl s | -single-quotes Ar string
.br
.Op Fl d | -double-quotes Ar string
.br
.Op Fl w | -wrap Ar string
.br
.Op Fl e | -escape-everything Ar string
.br
.Op Fl v | -version
.br
.Op Fl h | -help
.Sh DESCRIPTION
.Nm
escapes strings for use in CSS string literals or identifiers while generating the shortest possible valid ASCII-only output.
.Sh OPTIONS
.Bl -ohang -offset
.It Sy "-s, --single-quotes"
Escape any occurences of ' in the input string as \\', so that the output can be used in a CSS string literal wrapped in single quotes.
.It Sy "-d, --double-quotes"
Escape any occurences of " in the input string as \\", so that the output can be used in a CSS string literal wrapped in double quotes.
.It Sy "-w, --wrap"
Make sure the output is a valid CSS string literal wrapped in quotes. The type of quotes can be specified using the
.Ar -s | --single-quotes
or
.Ar -d | --double-quotes
settings.
.It Sy "-e, --escape-everything"
Escape all the symbols in the output, even printable ASCII symbols.
.It Sy "-v, --version"
Print cssesc's version.
.It Sy "-h, --help"
Show the help screen.
.El
.Sh EXIT STATUS
The
.Nm cssesc
utility exits with one of the following values:
.Pp
.Bl -tag -width flag -compact
.It Li 0
.Nm
successfully escaped the given text and printed the result.
.It Li 1
.Nm
wasn't instructed to escape anything (for example, the
.Ar --help
flag was set); or, an error occurred.
.El
.Sh EXAMPLES
.Bl -ohang -offset
.It Sy "cssesc 'foo bar baz'"
Print an escaped version of the given text.
.It Sy echo\ 'foo bar baz'\ |\ cssesc
Print an escaped version of the text that gets piped in.
.El
.Sh BUGS
cssesc's bug tracker is located at .
.Sh AUTHOR
Mathias Bynens 
.Sh WWW

PK~\P"[npm-package-arg/package.jsonnu[{
  "_id": "npm-package-arg@11.0.2",
  "_inBundle": true,
  "_location": "/npm/npm-package-arg",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm",
    "/npm/@npmcli/arborist",
    "/npm/init-package-json",
    "/npm/libnpmaccess",
    "/npm/libnpmdiff",
    "/npm/libnpmexec",
    "/npm/libnpmpack",
    "/npm/libnpmpublish",
    "/npm/npm-pick-manifest",
    "/npm/npm-registry-fetch",
    "/npm/pacote"
  ],
  "author": {
    "name": "GitHub Inc."
  },
  "bugs": {
    "url": "https://github.com/npm/npm-package-arg/issues"
  },
  "dependencies": {
    "hosted-git-info": "^7.0.0",
    "proc-log": "^4.0.0",
    "semver": "^7.3.5",
    "validate-npm-package-name": "^5.0.0"
  },
  "description": "Parse the things that can be arguments to `npm install`",
  "devDependencies": {
    "@npmcli/eslint-config": "^4.0.0",
    "@npmcli/template-oss": "4.21.3",
    "tap": "^16.0.1"
  },
  "directories": {
    "test": "test"
  },
  "engines": {
    "node": "^16.14.0 || >=18.0.0"
  },
  "files": [
    "bin/",
    "lib/"
  ],
  "homepage": "https://github.com/npm/npm-package-arg",
  "license": "ISC",
  "main": "./lib/npa.js",
  "name": "npm-package-arg",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/npm-package-arg.git"
  },
  "scripts": {
    "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"",
    "lintfix": "npm run lint -- --fix",
    "npmclilint": "npmcli-lint",
    "postlint": "template-oss-check",
    "postsnap": "npm run lintfix --",
    "posttest": "npm run lint",
    "snap": "tap",
    "template-oss-apply": "template-oss-apply --force",
    "test": "tap"
  },
  "tap": {
    "branches": 97,
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.21.3",
    "publish": true
  },
  "version": "11.0.2"
}
PK~\O;00npm-package-arg/lib/npa.jsnu['use strict'
module.exports = npa
module.exports.resolve = resolve
module.exports.toPurl = toPurl
module.exports.Result = Result

const { URL } = require('url')
const HostedGit = require('hosted-git-info')
const semver = require('semver')
const path = global.FAKE_WINDOWS ? require('path').win32 : require('path')
const validatePackageName = require('validate-npm-package-name')
const { homedir } = require('os')
const { log } = require('proc-log')

const isWindows = process.platform === 'win32' || global.FAKE_WINDOWS
const hasSlashes = isWindows ? /\\|[/]/ : /[/]/
const isURL = /^(?:git[+])?[a-z]+:/i
const isGit = /^[^@]+@[^:.]+\.[^:]+:.+$/i
const isFilename = /[.](?:tgz|tar.gz|tar)$/i

function npa (arg, where) {
  let name
  let spec
  if (typeof arg === 'object') {
    if (arg instanceof Result && (!where || where === arg.where)) {
      return arg
    } else if (arg.name && arg.rawSpec) {
      return npa.resolve(arg.name, arg.rawSpec, where || arg.where)
    } else {
      return npa(arg.raw, where || arg.where)
    }
  }
  const nameEndsAt = arg[0] === '@' ? arg.slice(1).indexOf('@') + 1 : arg.indexOf('@')
  const namePart = nameEndsAt > 0 ? arg.slice(0, nameEndsAt) : arg
  if (isURL.test(arg)) {
    spec = arg
  } else if (isGit.test(arg)) {
    spec = `git+ssh://${arg}`
  } else if (namePart[0] !== '@' && (hasSlashes.test(namePart) || isFilename.test(namePart))) {
    spec = arg
  } else if (nameEndsAt > 0) {
    name = namePart
    spec = arg.slice(nameEndsAt + 1) || '*'
  } else {
    const valid = validatePackageName(arg)
    if (valid.validForOldPackages) {
      name = arg
      spec = '*'
    } else {
      spec = arg
    }
  }
  return resolve(name, spec, where, arg)
}

const isFilespec = isWindows ? /^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/ : /^(?:[.]|~[/]|[/]|[a-zA-Z]:)/

function resolve (name, spec, where, arg) {
  const res = new Result({
    raw: arg,
    name: name,
    rawSpec: spec,
    fromArgument: arg != null,
  })

  if (name) {
    res.setName(name)
  }

  if (spec && (isFilespec.test(spec) || /^file:/i.test(spec))) {
    return fromFile(res, where)
  } else if (spec && /^npm:/i.test(spec)) {
    return fromAlias(res, where)
  }

  const hosted = HostedGit.fromUrl(spec, {
    noGitPlus: true,
    noCommittish: true,
  })
  if (hosted) {
    return fromHostedGit(res, hosted)
  } else if (spec && isURL.test(spec)) {
    return fromURL(res)
  } else if (spec && (hasSlashes.test(spec) || isFilename.test(spec))) {
    return fromFile(res, where)
  } else {
    return fromRegistry(res)
  }
}

const defaultRegistry = 'https://registry.npmjs.org'

function toPurl (arg, reg = defaultRegistry) {
  const res = npa(arg)

  if (res.type !== 'version') {
    throw invalidPurlType(res.type, res.raw)
  }

  // URI-encode leading @ of scoped packages
  let purl = 'pkg:npm/' + res.name.replace(/^@/, '%40') + '@' + res.rawSpec
  if (reg !== defaultRegistry) {
    purl += '?repository_url=' + reg
  }

  return purl
}

function invalidPackageName (name, valid, raw) {
  // eslint-disable-next-line max-len
  const err = new Error(`Invalid package name "${name}" of package "${raw}": ${valid.errors.join('; ')}.`)
  err.code = 'EINVALIDPACKAGENAME'
  return err
}

function invalidTagName (name, raw) {
  // eslint-disable-next-line max-len
  const err = new Error(`Invalid tag name "${name}" of package "${raw}": Tags may not have any characters that encodeURIComponent encodes.`)
  err.code = 'EINVALIDTAGNAME'
  return err
}

function invalidPurlType (type, raw) {
  // eslint-disable-next-line max-len
  const err = new Error(`Invalid type "${type}" of package "${raw}": Purl can only be generated for "version" types.`)
  err.code = 'EINVALIDPURLTYPE'
  return err
}

function Result (opts) {
  this.type = opts.type
  this.registry = opts.registry
  this.where = opts.where
  if (opts.raw == null) {
    this.raw = opts.name ? opts.name + '@' + opts.rawSpec : opts.rawSpec
  } else {
    this.raw = opts.raw
  }

  this.name = undefined
  this.escapedName = undefined
  this.scope = undefined
  this.rawSpec = opts.rawSpec || ''
  this.saveSpec = opts.saveSpec
  this.fetchSpec = opts.fetchSpec
  if (opts.name) {
    this.setName(opts.name)
  }
  this.gitRange = opts.gitRange
  this.gitCommittish = opts.gitCommittish
  this.gitSubdir = opts.gitSubdir
  this.hosted = opts.hosted
}

Result.prototype.setName = function (name) {
  const valid = validatePackageName(name)
  if (!valid.validForOldPackages) {
    throw invalidPackageName(name, valid, this.raw)
  }

  this.name = name
  this.scope = name[0] === '@' ? name.slice(0, name.indexOf('/')) : undefined
  // scoped packages in couch must have slash url-encoded, e.g. @foo%2Fbar
  this.escapedName = name.replace('/', '%2f')
  return this
}

Result.prototype.toString = function () {
  const full = []
  if (this.name != null && this.name !== '') {
    full.push(this.name)
  }
  const spec = this.saveSpec || this.fetchSpec || this.rawSpec
  if (spec != null && spec !== '') {
    full.push(spec)
  }
  return full.length ? full.join('@') : this.raw
}

Result.prototype.toJSON = function () {
  const result = Object.assign({}, this)
  delete result.hosted
  return result
}

// sets res.gitCommittish, res.gitRange, and res.gitSubdir
function setGitAttrs (res, committish) {
  if (!committish) {
    res.gitCommittish = null
    return
  }

  // for each :: separated item:
  for (const part of committish.split('::')) {
    // if the item has no : the n it is a commit-ish
    if (!part.includes(':')) {
      if (res.gitRange) {
        throw new Error('cannot override existing semver range with a committish')
      }
      if (res.gitCommittish) {
        throw new Error('cannot override existing committish with a second committish')
      }
      res.gitCommittish = part
      continue
    }
    // split on name:value
    const [name, value] = part.split(':')
    // if name is semver do semver lookup of ref or tag
    if (name === 'semver') {
      if (res.gitCommittish) {
        throw new Error('cannot override existing committish with a semver range')
      }
      if (res.gitRange) {
        throw new Error('cannot override existing semver range with a second semver range')
      }
      res.gitRange = decodeURIComponent(value)
      continue
    }
    if (name === 'path') {
      if (res.gitSubdir) {
        throw new Error('cannot override existing path with a second path')
      }
      res.gitSubdir = `/${value}`
      continue
    }
    log.warn('npm-package-arg', `ignoring unknown key "${name}"`)
  }
}

function fromFile (res, where) {
  if (!where) {
    where = process.cwd()
  }
  res.type = isFilename.test(res.rawSpec) ? 'file' : 'directory'
  res.where = where

  // always put the '/' on where when resolving urls, or else
  // file:foo from /path/to/bar goes to /path/to/foo, when we want
  // it to be /path/to/bar/foo

  let specUrl
  let resolvedUrl
  const prefix = (!/^file:/.test(res.rawSpec) ? 'file:' : '')
  const rawWithPrefix = prefix + res.rawSpec
  let rawNoPrefix = rawWithPrefix.replace(/^file:/, '')
  try {
    resolvedUrl = new URL(rawWithPrefix, `file://${path.resolve(where)}/`)
    specUrl = new URL(rawWithPrefix)
  } catch (originalError) {
    const er = new Error('Invalid file: URL, must comply with RFC 8089')
    throw Object.assign(er, {
      raw: res.rawSpec,
      spec: res,
      where,
      originalError,
    })
  }

  // XXX backwards compatibility lack of compliance with RFC 8089
  if (resolvedUrl.host && resolvedUrl.host !== 'localhost') {
    const rawSpec = res.rawSpec.replace(/^file:\/\//, 'file:///')
    resolvedUrl = new URL(rawSpec, `file://${path.resolve(where)}/`)
    specUrl = new URL(rawSpec)
    rawNoPrefix = rawSpec.replace(/^file:/, '')
  }
  // turn file:/../foo into file:../foo
  // for 1, 2 or 3 leading slashes since we attempted
  // in the previous step to make it a file protocol url with a leading slash
  if (/^\/{1,3}\.\.?(\/|$)/.test(rawNoPrefix)) {
    const rawSpec = res.rawSpec.replace(/^file:\/{1,3}/, 'file:')
    resolvedUrl = new URL(rawSpec, `file://${path.resolve(where)}/`)
    specUrl = new URL(rawSpec)
    rawNoPrefix = rawSpec.replace(/^file:/, '')
  }
  // XXX end RFC 8089 violation backwards compatibility section

  // turn /C:/blah into just C:/blah on windows
  let specPath = decodeURIComponent(specUrl.pathname)
  let resolvedPath = decodeURIComponent(resolvedUrl.pathname)
  if (isWindows) {
    specPath = specPath.replace(/^\/+([a-z]:\/)/i, '$1')
    resolvedPath = resolvedPath.replace(/^\/+([a-z]:\/)/i, '$1')
  }

  // replace ~ with homedir, but keep the ~ in the saveSpec
  // otherwise, make it relative to where param
  if (/^\/~(\/|$)/.test(specPath)) {
    res.saveSpec = `file:${specPath.substr(1)}`
    resolvedPath = path.resolve(homedir(), specPath.substr(3))
  } else if (!path.isAbsolute(rawNoPrefix)) {
    res.saveSpec = `file:${path.relative(where, resolvedPath)}`
  } else {
    res.saveSpec = `file:${path.resolve(resolvedPath)}`
  }

  res.fetchSpec = path.resolve(where, resolvedPath)
  return res
}

function fromHostedGit (res, hosted) {
  res.type = 'git'
  res.hosted = hosted
  res.saveSpec = hosted.toString({ noGitPlus: false, noCommittish: false })
  res.fetchSpec = hosted.getDefaultRepresentation() === 'shortcut' ? null : hosted.toString()
  setGitAttrs(res, hosted.committish)
  return res
}

function unsupportedURLType (protocol, spec) {
  const err = new Error(`Unsupported URL Type "${protocol}": ${spec}`)
  err.code = 'EUNSUPPORTEDPROTOCOL'
  return err
}

function fromURL (res) {
  let rawSpec = res.rawSpec
  res.saveSpec = rawSpec
  if (rawSpec.startsWith('git+ssh:')) {
    // git ssh specifiers are overloaded to also use scp-style git
    // specifiers, so we have to parse those out and treat them special.
    // They are NOT true URIs, so we can't hand them to URL.

    // This regex looks for things that look like:
    // git+ssh://git@my.custom.git.com:username/project.git#deadbeef
    // ...and various combinations. The username in the beginning is *required*.
    const matched = rawSpec.match(/^git\+ssh:\/\/([^:#]+:[^#]+(?:\.git)?)(?:#(.*))?$/i)
    if (matched && !matched[1].match(/:[0-9]+\/?.*$/i)) {
      res.type = 'git'
      setGitAttrs(res, matched[2])
      res.fetchSpec = matched[1]
      return res
    }
  } else if (rawSpec.startsWith('git+file://')) {
    // URL can't handle windows paths
    rawSpec = rawSpec.replace(/\\/g, '/')
  }
  const parsedUrl = new URL(rawSpec)
  // check the protocol, and then see if it's git or not
  switch (parsedUrl.protocol) {
    case 'git:':
    case 'git+http:':
    case 'git+https:':
    case 'git+rsync:':
    case 'git+ftp:':
    case 'git+file:':
    case 'git+ssh:':
      res.type = 'git'
      setGitAttrs(res, parsedUrl.hash.slice(1))
      if (parsedUrl.protocol === 'git+file:' && /^git\+file:\/\/[a-z]:/i.test(rawSpec)) {
        // URL can't handle drive letters on windows file paths, the host can't contain a :
        res.fetchSpec = `git+file://${parsedUrl.host.toLowerCase()}:${parsedUrl.pathname}`
      } else {
        parsedUrl.hash = ''
        res.fetchSpec = parsedUrl.toString()
      }
      if (res.fetchSpec.startsWith('git+')) {
        res.fetchSpec = res.fetchSpec.slice(4)
      }
      break
    case 'http:':
    case 'https:':
      res.type = 'remote'
      res.fetchSpec = res.saveSpec
      break

    default:
      throw unsupportedURLType(parsedUrl.protocol, rawSpec)
  }

  return res
}

function fromAlias (res, where) {
  const subSpec = npa(res.rawSpec.substr(4), where)
  if (subSpec.type === 'alias') {
    throw new Error('nested aliases not supported')
  }

  if (!subSpec.registry) {
    throw new Error('aliases only work for registry deps')
  }

  res.subSpec = subSpec
  res.registry = true
  res.type = 'alias'
  res.saveSpec = null
  res.fetchSpec = null
  return res
}

function fromRegistry (res) {
  res.registry = true
  const spec = res.rawSpec.trim()
  // no save spec for registry components as we save based on the fetched
  // version, not on the argument so this can't compute that.
  res.saveSpec = null
  res.fetchSpec = spec
  const version = semver.valid(spec, true)
  const range = semver.validRange(spec, true)
  if (version) {
    res.type = 'version'
  } else if (range) {
    res.type = 'range'
  } else {
    if (encodeURIComponent(spec) !== spec) {
      throw invalidTagName(spec, res.raw)
    }
    res.type = 'tag'
  }
  return res
}
PK~\.9npm-package-arg/LICENSEnu[The ISC License

Copyright (c) npm, Inc.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
PK~\ٿwhich/package.jsonnu[{
  "_id": "which@4.0.0",
  "_inBundle": true,
  "_location": "/npm/which",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm",
    "/npm/@npmcli/git",
    "/npm/@npmcli/promise-spawn",
    "/npm/@npmcli/run-script",
    "/npm/node-gyp"
  ],
  "author": {
    "name": "GitHub Inc."
  },
  "bin": {
    "node-which": "bin/which.js"
  },
  "bugs": {
    "url": "https://github.com/npm/node-which/issues"
  },
  "dependencies": {
    "isexe": "^3.1.1"
  },
  "description": "Like which(1) unix command. Find the first instance of an executable in the PATH.",
  "devDependencies": {
    "@npmcli/eslint-config": "^4.0.0",
    "@npmcli/template-oss": "4.18.0",
    "tap": "^16.3.0"
  },
  "engines": {
    "node": "^16.13.0 || >=18.0.0"
  },
  "files": [
    "bin/",
    "lib/"
  ],
  "homepage": "https://github.com/npm/node-which#readme",
  "license": "ISC",
  "main": "lib/index.js",
  "name": "which",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/node-which.git"
  },
  "scripts": {
    "lint": "eslint \"**/*.js\"",
    "lintfix": "npm run lint -- --fix",
    "postlint": "template-oss-check",
    "posttest": "npm run lint",
    "snap": "tap",
    "template-oss-apply": "template-oss-apply --force",
    "test": "tap"
  },
  "tap": {
    "check-coverage": true,
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "ciVersions": [
      "16.13.0",
      "16.x",
      "18.0.0",
      "18.x"
    ],
    "version": "4.18.0",
    "publish": "true"
  },
  "version": "4.0.0"
}
PK~\lZ

%which/node_modules/isexe/package.jsonnu[{
  "_id": "isexe@3.1.1",
  "_inBundle": true,
  "_location": "/npm/which/isexe",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm/which"
  ],
  "author": {
    "name": "Isaac Z. Schlueter",
    "email": "i@izs.me",
    "url": "http://blog.izs.me/"
  },
  "bugs": {
    "url": "https://github.com/isaacs/isexe/issues"
  },
  "description": "Minimal module to check if a file is executable.",
  "devDependencies": {
    "@types/node": "^20.4.5",
    "@types/tap": "^15.0.8",
    "c8": "^8.0.1",
    "mkdirp": "^0.5.1",
    "prettier": "^2.8.8",
    "rimraf": "^2.5.0",
    "sync-content": "^1.0.2",
    "tap": "^16.3.8",
    "ts-node": "^10.9.1",
    "typedoc": "^0.24.8",
    "typescript": "^5.1.6"
  },
  "engines": {
    "node": ">=16"
  },
  "exports": {
    ".": {
      "import": {
        "types": "./dist/mjs/index.d.ts",
        "default": "./dist/mjs/index.js"
      },
      "require": {
        "types": "./dist/cjs/index.d.ts",
        "default": "./dist/cjs/index.js"
      }
    },
    "./posix": {
      "import": {
        "types": "./dist/mjs/posix.d.ts",
        "default": "./dist/mjs/posix.js"
      },
      "require": {
        "types": "./dist/cjs/posix.d.ts",
        "default": "./dist/cjs/posix.js"
      }
    },
    "./win32": {
      "import": {
        "types": "./dist/mjs/win32.d.ts",
        "default": "./dist/mjs/win32.js"
      },
      "require": {
        "types": "./dist/cjs/win32.d.ts",
        "default": "./dist/cjs/win32.js"
      }
    },
    "./package.json": "./package.json"
  },
  "files": [
    "dist"
  ],
  "homepage": "https://github.com/isaacs/isexe#readme",
  "license": "ISC",
  "main": "./dist/cjs/index.js",
  "module": "./dist/mjs/index.js",
  "name": "isexe",
  "prettier": {
    "semi": false,
    "printWidth": 75,
    "tabWidth": 2,
    "useTabs": false,
    "singleQuote": true,
    "jsxSingleQuote": false,
    "bracketSameLine": true,
    "arrowParens": "avoid",
    "endOfLine": "lf"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/isaacs/isexe.git"
  },
  "scripts": {
    "format": "prettier --write . --loglevel warn --ignore-path ../../.prettierignore --cache",
    "postversion": "npm publish",
    "prepare": "tsc -p tsconfig/cjs.json && tsc -p tsconfig/esm.json && bash ./scripts/fixup.sh",
    "prepublishOnly": "git push origin --follow-tags",
    "presnap": "npm run prepare",
    "pretest": "npm run prepare",
    "preversion": "npm test",
    "snap": "c8 tap",
    "test": "c8 tap",
    "typedoc": "typedoc --tsconfig tsconfig/esm.json ./src/*.ts"
  },
  "tap": {
    "coverage": false,
    "node-arg": [
      "--enable-source-maps",
      "--no-warnings",
      "--loader",
      "ts-node/esm"
    ],
    "ts": false
  },
  "types": "./dist/cjs/index.js",
  "version": "3.1.1"
}
PK~\? which/node_modules/isexe/LICENSEnu[The ISC License

Copyright (c) 2016-2022 Isaac Z. Schlueter and Contributors

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
PK~\x.which/node_modules/isexe/dist/mjs/package.jsonnu[{
  "type": "module"
}
PK~\񯵇*which/node_modules/isexe/dist/mjs/index.jsnu[import * as posix from './posix.js';
import * as win32 from './win32.js';
export * from './options.js';
export { win32, posix };
const platform = process.env._ISEXE_TEST_PLATFORM_ || process.platform;
const impl = platform === 'win32' ? win32 : posix;
/**
 * Determine whether a path is executable on the current platform.
 */
export const isexe = impl.isexe;
/**
 * Synchronously determine whether a path is executable on the
 * current platform.
 */
export const sync = impl.sync;
//# sourceMappingURL=index.js.mapPK~\尃hh*which/node_modules/isexe/dist/mjs/posix.jsnu[/**
 * This is the Posix implementation of isexe, which uses the file
 * mode and uid/gid values.
 *
 * @module
 */
import { statSync } from 'fs';
import { stat } from 'fs/promises';
/**
 * Determine whether a path is executable according to the mode and
 * current (or specified) user and group IDs.
 */
export const isexe = async (path, options = {}) => {
    const { ignoreErrors = false } = options;
    try {
        return checkStat(await stat(path), options);
    }
    catch (e) {
        const er = e;
        if (ignoreErrors || er.code === 'EACCES')
            return false;
        throw er;
    }
};
/**
 * Synchronously determine whether a path is executable according to
 * the mode and current (or specified) user and group IDs.
 */
export const sync = (path, options = {}) => {
    const { ignoreErrors = false } = options;
    try {
        return checkStat(statSync(path), options);
    }
    catch (e) {
        const er = e;
        if (ignoreErrors || er.code === 'EACCES')
            return false;
        throw er;
    }
};
const checkStat = (stat, options) => stat.isFile() && checkMode(stat, options);
const checkMode = (stat, options) => {
    const myUid = options.uid ?? process.getuid?.();
    const myGroups = options.groups ?? process.getgroups?.() ?? [];
    const myGid = options.gid ?? process.getgid?.() ?? myGroups[0];
    if (myUid === undefined || myGid === undefined) {
        throw new Error('cannot get uid or gid');
    }
    const groups = new Set([myGid, ...myGroups]);
    const mod = stat.mode;
    const uid = stat.uid;
    const gid = stat.gid;
    const u = parseInt('100', 8);
    const g = parseInt('010', 8);
    const o = parseInt('001', 8);
    const ug = u | g;
    return !!(mod & o ||
        (mod & g && groups.has(gid)) ||
        (mod & u && uid === myUid) ||
        (mod & ug && myUid === 0));
};
//# sourceMappingURL=posix.js.mapPK~\..,which/node_modules/isexe/dist/mjs/options.jsnu[export {};
//# sourceMappingURL=options.js.mapPK~\5Yj>*which/node_modules/isexe/dist/mjs/win32.jsnu[/**
 * This is the Windows implementation of isexe, which uses the file
 * extension and PATHEXT setting.
 *
 * @module
 */
import { statSync } from 'fs';
import { stat } from 'fs/promises';
/**
 * Determine whether a path is executable based on the file extension
 * and PATHEXT environment variable (or specified pathExt option)
 */
export const isexe = async (path, options = {}) => {
    const { ignoreErrors = false } = options;
    try {
        return checkStat(await stat(path), path, options);
    }
    catch (e) {
        const er = e;
        if (ignoreErrors || er.code === 'EACCES')
            return false;
        throw er;
    }
};
/**
 * Synchronously determine whether a path is executable based on the file
 * extension and PATHEXT environment variable (or specified pathExt option)
 */
export const sync = (path, options = {}) => {
    const { ignoreErrors = false } = options;
    try {
        return checkStat(statSync(path), path, options);
    }
    catch (e) {
        const er = e;
        if (ignoreErrors || er.code === 'EACCES')
            return false;
        throw er;
    }
};
const checkPathExt = (path, options) => {
    const { pathExt = process.env.PATHEXT || '' } = options;
    const peSplit = pathExt.split(';');
    if (peSplit.indexOf('') !== -1) {
        return true;
    }
    for (let i = 0; i < peSplit.length; i++) {
        const p = peSplit[i].toLowerCase();
        const ext = path.substring(path.length - p.length).toLowerCase();
        if (p && ext === p) {
            return true;
        }
    }
    return false;
};
const checkStat = (stat, path, options) => stat.isFile() && checkPathExt(path, options);
//# sourceMappingURL=win32.js.mapPK~\>.which/node_modules/isexe/dist/cjs/package.jsonnu[{
  "type": "commonjs"
}
PK~\pi
*which/node_modules/isexe/dist/cjs/index.jsnu["use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sync = exports.isexe = exports.posix = exports.win32 = void 0;
const posix = __importStar(require("./posix.js"));
exports.posix = posix;
const win32 = __importStar(require("./win32.js"));
exports.win32 = win32;
__exportStar(require("./options.js"), exports);
const platform = process.env._ISEXE_TEST_PLATFORM_ || process.platform;
const impl = platform === 'win32' ? win32 : posix;
/**
 * Determine whether a path is executable on the current platform.
 */
exports.isexe = impl.isexe;
/**
 * Synchronously determine whether a path is executable on the
 * current platform.
 */
exports.sync = impl.sync;
//# sourceMappingURL=index.js.mapPK~\*which/node_modules/isexe/dist/cjs/posix.jsnu["use strict";
/**
 * This is the Posix implementation of isexe, which uses the file
 * mode and uid/gid values.
 *
 * @module
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.sync = exports.isexe = void 0;
const fs_1 = require("fs");
const promises_1 = require("fs/promises");
/**
 * Determine whether a path is executable according to the mode and
 * current (or specified) user and group IDs.
 */
const isexe = async (path, options = {}) => {
    const { ignoreErrors = false } = options;
    try {
        return checkStat(await (0, promises_1.stat)(path), options);
    }
    catch (e) {
        const er = e;
        if (ignoreErrors || er.code === 'EACCES')
            return false;
        throw er;
    }
};
exports.isexe = isexe;
/**
 * Synchronously determine whether a path is executable according to
 * the mode and current (or specified) user and group IDs.
 */
const sync = (path, options = {}) => {
    const { ignoreErrors = false } = options;
    try {
        return checkStat((0, fs_1.statSync)(path), options);
    }
    catch (e) {
        const er = e;
        if (ignoreErrors || er.code === 'EACCES')
            return false;
        throw er;
    }
};
exports.sync = sync;
const checkStat = (stat, options) => stat.isFile() && checkMode(stat, options);
const checkMode = (stat, options) => {
    const myUid = options.uid ?? process.getuid?.();
    const myGroups = options.groups ?? process.getgroups?.() ?? [];
    const myGid = options.gid ?? process.getgid?.() ?? myGroups[0];
    if (myUid === undefined || myGid === undefined) {
        throw new Error('cannot get uid or gid');
    }
    const groups = new Set([myGid, ...myGroups]);
    const mod = stat.mode;
    const uid = stat.uid;
    const gid = stat.gid;
    const u = parseInt('100', 8);
    const g = parseInt('010', 8);
    const o = parseInt('001', 8);
    const ug = u | g;
    return !!(mod & o ||
        (mod & g && groups.has(gid)) ||
        (mod & u && uid === myUid) ||
        (mod & ug && myUid === 0));
};
//# sourceMappingURL=posix.js.mapPK~\pfpp,which/node_modules/isexe/dist/cjs/options.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=options.js.mapPK~\UU*which/node_modules/isexe/dist/cjs/win32.jsnu["use strict";
/**
 * This is the Windows implementation of isexe, which uses the file
 * extension and PATHEXT setting.
 *
 * @module
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.sync = exports.isexe = void 0;
const fs_1 = require("fs");
const promises_1 = require("fs/promises");
/**
 * Determine whether a path is executable based on the file extension
 * and PATHEXT environment variable (or specified pathExt option)
 */
const isexe = async (path, options = {}) => {
    const { ignoreErrors = false } = options;
    try {
        return checkStat(await (0, promises_1.stat)(path), path, options);
    }
    catch (e) {
        const er = e;
        if (ignoreErrors || er.code === 'EACCES')
            return false;
        throw er;
    }
};
exports.isexe = isexe;
/**
 * Synchronously determine whether a path is executable based on the file
 * extension and PATHEXT environment variable (or specified pathExt option)
 */
const sync = (path, options = {}) => {
    const { ignoreErrors = false } = options;
    try {
        return checkStat((0, fs_1.statSync)(path), path, options);
    }
    catch (e) {
        const er = e;
        if (ignoreErrors || er.code === 'EACCES')
            return false;
        throw er;
    }
};
exports.sync = sync;
const checkPathExt = (path, options) => {
    const { pathExt = process.env.PATHEXT || '' } = options;
    const peSplit = pathExt.split(';');
    if (peSplit.indexOf('') !== -1) {
        return true;
    }
    for (let i = 0; i < peSplit.length; i++) {
        const p = peSplit[i].toLowerCase();
        const ext = path.substring(path.length - p.length).toLowerCase();
        if (p && ext === p) {
            return true;
        }
    }
    return false;
};
const checkStat = (stat, path, options) => stat.isFile() && checkPathExt(path, options);
//# sourceMappingURL=win32.js.mapPK~\sQ99which/lib/index.jsnu[const { isexe, sync: isexeSync } = require('isexe')
const { join, delimiter, sep, posix } = require('path')

const isWindows = process.platform === 'win32'

// used to check for slashed in commands passed in. always checks for the posix
// seperator on all platforms, and checks for the current separator when not on
// a posix platform. don't use the isWindows check for this since that is mocked
// in tests but we still need the code to actually work when called. that is also
// why it is ignored from coverage.
/* istanbul ignore next */
const rSlash = new RegExp(`[${posix.sep}${sep === posix.sep ? '' : sep}]`.replace(/(\\)/g, '\\$1'))
const rRel = new RegExp(`^\\.${rSlash.source}`)

const getNotFoundError = (cmd) =>
  Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' })

const getPathInfo = (cmd, {
  path: optPath = process.env.PATH,
  pathExt: optPathExt = process.env.PATHEXT,
  delimiter: optDelimiter = delimiter,
}) => {
  // If it has a slash, then we don't bother searching the pathenv.
  // just check the file itself, and that's it.
  const pathEnv = cmd.match(rSlash) ? [''] : [
    // windows always checks the cwd first
    ...(isWindows ? [process.cwd()] : []),
    ...(optPath || /* istanbul ignore next: very unusual */ '').split(optDelimiter),
  ]

  if (isWindows) {
    const pathExtExe = optPathExt ||
      ['.EXE', '.CMD', '.BAT', '.COM'].join(optDelimiter)
    const pathExt = pathExtExe.split(optDelimiter).flatMap((item) => [item, item.toLowerCase()])
    if (cmd.includes('.') && pathExt[0] !== '') {
      pathExt.unshift('')
    }
    return { pathEnv, pathExt, pathExtExe }
  }

  return { pathEnv, pathExt: [''] }
}

const getPathPart = (raw, cmd) => {
  const pathPart = /^".*"$/.test(raw) ? raw.slice(1, -1) : raw
  const prefix = !pathPart && rRel.test(cmd) ? cmd.slice(0, 2) : ''
  return prefix + join(pathPart, cmd)
}

const which = async (cmd, opt = {}) => {
  const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)
  const found = []

  for (const envPart of pathEnv) {
    const p = getPathPart(envPart, cmd)

    for (const ext of pathExt) {
      const withExt = p + ext
      const is = await isexe(withExt, { pathExt: pathExtExe, ignoreErrors: true })
      if (is) {
        if (!opt.all) {
          return withExt
        }
        found.push(withExt)
      }
    }
  }

  if (opt.all && found.length) {
    return found
  }

  if (opt.nothrow) {
    return null
  }

  throw getNotFoundError(cmd)
}

const whichSync = (cmd, opt = {}) => {
  const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)
  const found = []

  for (const pathEnvPart of pathEnv) {
    const p = getPathPart(pathEnvPart, cmd)

    for (const ext of pathExt) {
      const withExt = p + ext
      const is = isexeSync(withExt, { pathExt: pathExtExe, ignoreErrors: true })
      if (is) {
        if (!opt.all) {
          return withExt
        }
        found.push(withExt)
      }
    }
  }

  if (opt.all && found.length) {
    return found
  }

  if (opt.nothrow) {
    return null
  }

  throw getNotFoundError(cmd)
}

module.exports = which
which.sync = whichSync
PK~\aGW
which/LICENSEnu[The ISC License

Copyright (c) Isaac Z. Schlueter and Contributors

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
PK~\$ which/bin/which.jsnu[#!/usr/bin/env node

const which = require('../lib')
const argv = process.argv.slice(2)

const usage = (err) => {
  if (err) {
    console.error(`which: ${err}`)
  }
  console.error('usage: which [-as] program ...')
  process.exit(1)
}

if (!argv.length) {
  return usage()
}

let dashdash = false
const [commands, flags] = argv.reduce((acc, arg) => {
  if (dashdash || arg === '--') {
    dashdash = true
    return acc
  }

  if (!/^-/.test(arg)) {
    acc[0].push(arg)
    return acc
  }

  for (const flag of arg.slice(1).split('')) {
    if (flag === 's') {
      acc[1].silent = true
    } else if (flag === 'a') {
      acc[1].all = true
    } else {
      usage(`illegal option -- ${flag}`)
    }
  }

  return acc
}, [[], {}])

for (const command of commands) {
  try {
    const res = which.sync(command, { all: flags.all })
    if (!flags.silent) {
      console.log([].concat(res).join('\n'))
    }
  } catch (err) {
    process.exitCode = 1
  }
}
PK~\= this.total
    process.emit('progress', this.key, {
      ...metadata,
      name: this.name,
      key: this.key,
      value,
      total,
      done,
    })
    if (done) {
      this.done = true
      this.emit('done')
    }
  }
}
module.exports = Tracker
PK~\,|)proggy/lib/index.jsnu[exports.Client = require('./client.js')
exports.Tracker = require('./tracker.js')

const trackers = new Map()
exports.createTracker = (name, key, total) => {
  const tracker = new exports.Tracker(name, key, total)
  if (trackers.has(tracker.key)) {
    const msg = `proggy: duplicate progress id ${JSON.stringify(tracker.key)}`
    throw new Error(msg)
  }
  trackers.set(tracker.key, tracker)
  tracker.on('done', () => trackers.delete(tracker.key))
  return tracker
}
exports.createClient = (options = {}) => new exports.Client(options)
PK~\X

proggy/lib/client.jsnu[const EE = require('events')
const onProgress = Symbol('onProgress')
const bars = Symbol('bars')
const listener = Symbol('listener')
const normData = Symbol('normData')
class Client extends EE {
  constructor ({ normalize = false, stopOnDone = false } = {}) {
    super()
    this.normalize = !!normalize
    this.stopOnDone = !!stopOnDone
    this[bars] = new Map()
    this[listener] = null
  }

  get size () {
    return this[bars].size
  }

  get listening () {
    return !!this[listener]
  }

  addListener (...args) {
    return this.on(...args)
  }

  on (ev, ...args) {
    if (ev === 'progress' && !this[listener]) {
      this.start()
    }
    return super.on(ev, ...args)
  }

  off (ev, ...args) {
    return this.removeListener(ev, ...args)
  }

  removeListener (ev, ...args) {
    const ret = super.removeListener(ev, ...args)
    if (ev === 'progress' && this.listeners(ev).length === 0) {
      this.stop()
    }
    return ret
  }

  stop () {
    if (this[listener]) {
      process.removeListener('progress', this[listener])
      this[listener] = null
    }
  }

  start () {
    if (!this[listener]) {
      this[listener] = (...args) => this[onProgress](...args)
      process.on('progress', this[listener])
    }
  }

  [onProgress] (key, data) {
    data = this[normData](key, data)
    if (!this[bars].has(key)) {
      this.emit('bar', key, data)
    }
    this[bars].set(key, data)
    this.emit('progress', key, data)
    if (data.done) {
      this[bars].delete(key)
      this.emit('barDone', key, data)
      if (this.size === 0) {
        if (this.stopOnDone) {
          this.stop()
        }
        this.emit('done')
      }
    }
  }

  [normData] (key, data) {
    const actualValue = data.value
    const actualTotal = data.total
    let value = actualValue
    let total = actualTotal
    const done = data.done || value >= total
    if (this.normalize) {
      const bar = this[bars].get(key)
      total = 100
      if (done) {
        value = 100
      } else {
        // show value as a portion of 100
        const pct = 100 * actualValue / actualTotal
        if (bar) {
          // don't ever go backwards, and don't stand still
          // move at least 1% of the remaining value if it wouldn't move.
          value = (pct > bar.value) ? pct
            : (100 - bar.value) / 100 + bar.value
        }
      }
    }
    // include the key
    return {
      ...data,
      key,
      name: data.name || key,
      value,
      total,
      actualValue,
      actualTotal,
      done,
    }
  }
}
module.exports = Client
PK~\acproggy/package.jsonnu[{
  "_id": "proggy@2.0.0",
  "_inBundle": true,
  "_location": "/npm/proggy",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm/@npmcli/arborist"
  ],
  "author": {
    "name": "GitHub Inc."
  },
  "bugs": {
    "url": "https://github.com/npm/proggy/issues"
  },
  "description": "Progress bar updates at a distance",
  "devDependencies": {
    "@npmcli/eslint-config": "^3.0.1",
    "@npmcli/template-oss": "4.5.1",
    "chalk": "^4.1.2",
    "cli-progress": "^3.10.0",
    "npmlog": "^6.0.1",
    "tap": "^16.0.1"
  },
  "engines": {
    "node": "^14.17.0 || ^16.13.0 || >=18.0.0"
  },
  "files": [
    "bin/",
    "lib/"
  ],
  "homepage": "https://github.com/npm/proggy#readme",
  "license": "ISC",
  "main": "lib/index.js",
  "name": "proggy",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/proggy.git"
  },
  "scripts": {
    "lint": "eslint \"**/*.js\"",
    "lintfix": "npm run lint -- --fix",
    "postlint": "template-oss-check",
    "postsnap": "eslint lib test --fix",
    "posttest": "npm run lint",
    "snap": "tap",
    "template-oss-apply": "template-oss-apply --force",
    "test": "tap"
  },
  "tap": {
    "coverage-map": "map.js",
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.5.1"
  },
  "version": "2.0.0"
}
PK~\<proggy/LICENSEnu[The ISC License

Copyright (c) GitHub, Inc.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
PK~\A77#read-package-json-fast/package.jsonnu[{
  "_id": "read-package-json-fast@3.0.2",
  "_inBundle": true,
  "_location": "/npm/read-package-json-fast",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm/@npmcli/arborist",
    "/npm/@npmcli/config",
    "/npm/@npmcli/map-workspaces",
    "/npm/libnpmexec"
  ],
  "author": {
    "name": "GitHub Inc."
  },
  "bugs": {
    "url": "https://github.com/npm/read-package-json-fast/issues"
  },
  "dependencies": {
    "json-parse-even-better-errors": "^3.0.0",
    "npm-normalize-package-bin": "^3.0.0"
  },
  "description": "Like read-package-json, but faster",
  "devDependencies": {
    "@npmcli/eslint-config": "^4.0.0",
    "@npmcli/template-oss": "4.11.0",
    "tap": "^16.3.0"
  },
  "engines": {
    "node": "^14.17.0 || ^16.13.0 || >=18.0.0"
  },
  "files": [
    "bin/",
    "lib/"
  ],
  "homepage": "https://github.com/npm/read-package-json-fast#readme",
  "license": "ISC",
  "main": "lib/index.js",
  "name": "read-package-json-fast",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/read-package-json-fast.git"
  },
  "scripts": {
    "lint": "eslint \"**/*.js\"",
    "lintfix": "npm run lint -- --fix",
    "postlint": "template-oss-check",
    "posttest": "npm run lint",
    "snap": "tap",
    "template-oss-apply": "template-oss-apply --force",
    "test": "tap"
  },
  "tap": {
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.11.0"
  },
  "version": "3.0.2"
}
PK~\nbDD#read-package-json-fast/lib/index.jsnu[const { readFile, lstat, readdir } = require('fs/promises')
const parse = require('json-parse-even-better-errors')
const normalizePackageBin = require('npm-normalize-package-bin')
const { resolve, dirname, join, relative } = require('path')

const rpj = path => readFile(path, 'utf8')
  .then(data => readBinDir(path, normalize(stripUnderscores(parse(data)))))
  .catch(er => {
    er.path = path
    throw er
  })

// load the directories.bin folder as a 'bin' object
const readBinDir = async (path, data) => {
  if (data.bin) {
    return data
  }

  const m = data.directories && data.directories.bin
  if (!m || typeof m !== 'string') {
    return data
  }

  // cut off any monkey business, like setting directories.bin
  // to ../../../etc/passwd or /etc/passwd or something like that.
  const root = dirname(path)
  const dir = join('.', join('/', m))
  data.bin = await walkBinDir(root, dir, {})
  return data
}

const walkBinDir = async (root, dir, obj) => {
  const entries = await readdir(resolve(root, dir)).catch(() => [])
  for (const entry of entries) {
    if (entry.charAt(0) === '.') {
      continue
    }
    const f = resolve(root, dir, entry)
    // ignore stat errors, weird file types, symlinks, etc.
    const st = await lstat(f).catch(() => null)
    if (!st) {
      continue
    } else if (st.isFile()) {
      obj[entry] = relative(root, f)
    } else if (st.isDirectory()) {
      await walkBinDir(root, join(dir, entry), obj)
    }
  }
  return obj
}

// do not preserve _fields set in files, they are sus
const stripUnderscores = data => {
  for (const key of Object.keys(data).filter(k => /^_/.test(k))) {
    delete data[key]
  }
  return data
}

const normalize = data => {
  addId(data)
  fixBundled(data)
  pruneRepeatedOptionals(data)
  fixScripts(data)
  fixFunding(data)
  normalizePackageBin(data)
  return data
}

rpj.normalize = normalize

const addId = data => {
  if (data.name && data.version) {
    data._id = `${data.name}@${data.version}`
  }
  return data
}

// it was once common practice to list deps both in optionalDependencies
// and in dependencies, to support npm versions that did not know abbout
// optionalDependencies.  This is no longer a relevant need, so duplicating
// the deps in two places is unnecessary and excessive.
const pruneRepeatedOptionals = data => {
  const od = data.optionalDependencies
  const dd = data.dependencies || {}
  if (od && typeof od === 'object') {
    for (const name of Object.keys(od)) {
      delete dd[name]
    }
  }
  if (Object.keys(dd).length === 0) {
    delete data.dependencies
  }
  return data
}

const fixBundled = data => {
  const bdd = data.bundledDependencies
  const bd = data.bundleDependencies === undefined ? bdd
    : data.bundleDependencies

  if (bd === false) {
    data.bundleDependencies = []
  } else if (bd === true) {
    data.bundleDependencies = Object.keys(data.dependencies || {})
  } else if (bd && typeof bd === 'object') {
    if (!Array.isArray(bd)) {
      data.bundleDependencies = Object.keys(bd)
    } else {
      data.bundleDependencies = bd
    }
  } else {
    delete data.bundleDependencies
  }

  delete data.bundledDependencies
  return data
}

const fixScripts = data => {
  if (!data.scripts || typeof data.scripts !== 'object') {
    delete data.scripts
    return data
  }

  for (const [name, script] of Object.entries(data.scripts)) {
    if (typeof script !== 'string') {
      delete data.scripts[name]
    }
  }
  return data
}

const fixFunding = data => {
  if (data.funding && typeof data.funding === 'string') {
    data.funding = { url: data.funding }
  }
  return data
}

module.exports = rpj
PK~\!read-package-json-fast/LICENSEnu[The ISC License

Copyright (c) npm, Inc. and Contributors

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
PK~\$is-fullwidth-code-point/package.jsonnu[{
  "_id": "is-fullwidth-code-point@3.0.0",
  "_inBundle": true,
  "_location": "/npm/is-fullwidth-code-point",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm/string-width",
    "/npm/string-width-cjs"
  ],
  "author": {
    "name": "Sindre Sorhus",
    "email": "sindresorhus@gmail.com",
    "url": "sindresorhus.com"
  },
  "bugs": {
    "url": "https://github.com/sindresorhus/is-fullwidth-code-point/issues"
  },
  "description": "Check if the character represented by a given Unicode code point is fullwidth",
  "devDependencies": {
    "ava": "^1.3.1",
    "tsd-check": "^0.5.0",
    "xo": "^0.24.0"
  },
  "engines": {
    "node": ">=8"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "homepage": "https://github.com/sindresorhus/is-fullwidth-code-point#readme",
  "keywords": [
    "fullwidth",
    "full-width",
    "full",
    "width",
    "unicode",
    "character",
    "string",
    "codepoint",
    "code",
    "point",
    "is",
    "detect",
    "check"
  ],
  "license": "MIT",
  "name": "is-fullwidth-code-point",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/sindresorhus/is-fullwidth-code-point.git"
  },
  "scripts": {
    "test": "xo && ava && tsd-check"
  },
  "version": "3.0.0"
}
PK~\+ is-fullwidth-code-point/index.jsnu[/* eslint-disable yoda */
'use strict';

const isFullwidthCodePoint = codePoint => {
	if (Number.isNaN(codePoint)) {
		return false;
	}

	// Code points are derived from:
	// http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt
	if (
		codePoint >= 0x1100 && (
			codePoint <= 0x115F || // Hangul Jamo
			codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET
			codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET
			// CJK Radicals Supplement .. Enclosed CJK Letters and Months
			(0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F) ||
			// Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
			(0x3250 <= codePoint && codePoint <= 0x4DBF) ||
			// CJK Unified Ideographs .. Yi Radicals
			(0x4E00 <= codePoint && codePoint <= 0xA4C6) ||
			// Hangul Jamo Extended-A
			(0xA960 <= codePoint && codePoint <= 0xA97C) ||
			// Hangul Syllables
			(0xAC00 <= codePoint && codePoint <= 0xD7A3) ||
			// CJK Compatibility Ideographs
			(0xF900 <= codePoint && codePoint <= 0xFAFF) ||
			// Vertical Forms
			(0xFE10 <= codePoint && codePoint <= 0xFE19) ||
			// CJK Compatibility Forms .. Small Form Variants
			(0xFE30 <= codePoint && codePoint <= 0xFE6B) ||
			// Halfwidth and Fullwidth Forms
			(0xFF01 <= codePoint && codePoint <= 0xFF60) ||
			(0xFFE0 <= codePoint && codePoint <= 0xFFE6) ||
			// Kana Supplement
			(0x1B000 <= codePoint && codePoint <= 0x1B001) ||
			// Enclosed Ideographic Supplement
			(0x1F200 <= codePoint && codePoint <= 0x1F251) ||
			// CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
			(0x20000 <= codePoint && codePoint <= 0x3FFFD)
		)
	) {
		return true;
	}

	return false;
};

module.exports = isFullwidthCodePoint;
module.exports.default = isFullwidthCodePoint;
PK~\E}UUis-fullwidth-code-point/licensenu[MIT License

Copyright (c) Sindre Sorhus  (sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
PK~\{༕glob/package.jsonnu[{
  "_id": "glob@10.4.1",
  "_inBundle": true,
  "_location": "/npm/glob",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm",
    "/npm/@npmcli/map-workspaces",
    "/npm/@npmcli/package-json",
    "/npm/cacache",
    "/npm/node-gyp"
  ],
  "author": {
    "name": "Isaac Z. Schlueter",
    "email": "i@izs.me",
    "url": "https://blog.izs.me/"
  },
  "bin": {
    "glob": "dist/esm/bin.mjs"
  },
  "bugs": {
    "url": "https://github.com/isaacs/node-glob/issues"
  },
  "dependencies": {
    "foreground-child": "^3.1.0",
    "jackspeak": "^3.1.2",
    "minimatch": "^9.0.4",
    "minipass": "^7.1.2",
    "path-scurry": "^1.11.1"
  },
  "description": "the most correct and second fastest glob implementation in JavaScript",
  "devDependencies": {
    "@types/node": "^20.11.30",
    "memfs": "^3.4.13",
    "mkdirp": "^3.0.1",
    "prettier": "^3.2.5",
    "rimraf": "^5.0.7",
    "sync-content": "^1.0.2",
    "tap": "^19.0.0",
    "tshy": "^1.14.0",
    "typedoc": "^0.25.12"
  },
  "engines": {
    "node": ">=16 || 14 >=14.18"
  },
  "exports": {
    "./package.json": "./package.json",
    ".": {
      "import": {
        "types": "./dist/esm/index.d.ts",
        "default": "./dist/esm/index.js"
      },
      "require": {
        "types": "./dist/commonjs/index.d.ts",
        "default": "./dist/commonjs/index.js"
      }
    }
  },
  "files": [
    "dist"
  ],
  "funding": {
    "url": "https://github.com/sponsors/isaacs"
  },
  "homepage": "https://github.com/isaacs/node-glob#readme",
  "license": "ISC",
  "main": "./dist/commonjs/index.js",
  "name": "glob",
  "prettier": {
    "experimentalTernaries": true,
    "semi": false,
    "printWidth": 75,
    "tabWidth": 2,
    "useTabs": false,
    "singleQuote": true,
    "jsxSingleQuote": false,
    "bracketSameLine": true,
    "arrowParens": "avoid",
    "endOfLine": "lf"
  },
  "repository": {
    "type": "git",
    "url": "git://github.com/isaacs/node-glob.git"
  },
  "scripts": {
    "bench": "bash benchmark.sh",
    "benchclean": "node benchclean.cjs",
    "format": "prettier --write . --log-level warn",
    "postversion": "npm publish",
    "prebench": "npm run prepare",
    "prepare": "tshy",
    "preprof": "npm run prepare",
    "prepublish": "npm run benchclean",
    "prepublishOnly": "git push origin --follow-tags",
    "presnap": "npm run prepare",
    "pretest": "npm run prepare",
    "preversion": "npm test",
    "prof": "bash prof.sh",
    "profclean": "rm -f v8.log profile.txt",
    "snap": "tap",
    "test": "tap",
    "test-regen": "npm run profclean && TEST_REGEN=1 node --no-warnings --loader ts-node/esm test/00-setup.ts",
    "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts"
  },
  "tap": {
    "before": "test/00-setup.ts"
  },
  "tshy": {
    "main": true,
    "exports": {
      "./package.json": "./package.json",
      ".": "./src/index.ts"
    }
  },
  "type": "module",
  "types": "./dist/commonjs/index.d.ts",
  "version": "10.4.1"
}
PK~\6bglob/LICENSEnu[The ISC License

Copyright (c) 2009-2023 Isaac Z. Schlueter and Contributors

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
PK~\dd"glob/dist/commonjs/walker.d.ts.mapnu[{"version":3,"file":"walker.d.ts","sourceRoot":"","sources":["../../src/walker.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AACnC,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,EAAU,UAAU,EAAE,MAAM,aAAa,CAAA;AAOhD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AACtC,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAE1C,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,kBAAkB,CAAC,EAAE,OAAO,CAAA;IAC5B,GAAG,CAAC,EAAE,MAAM,GAAG,GAAG,CAAA;IAClB,GAAG,CAAC,EAAE,OAAO,CAAA;IACb,WAAW,CAAC,EAAE,OAAO,CAAA;IACrB,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,UAAU,CAAA;IACvC,IAAI,CAAC,E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,IAAI,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;IAiBrC,QAAQ,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;CAW3B;AAED,qBAAa,UAAU,CACrB,CAAC,SAAS,cAAc,GAAG,cAAc,CACzC,SAAQ,QAAQ,CAAC,CAAC,CAAC;IACnB,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,CAAA;gBAE3B,QAAQ,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IAUpD,SAAS,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,GAAG,IAAI;IAK7B,MAAM,IAAI,WAAW,CAAC,CAAC,CAAC;IAYxB,UAAU,IAAI,WAAW,CAAC,CAAC,CAAC;CAO7B"}PK~\>glob/dist/commonjs/package.jsonnu[{
  "type": "commonjs"
}
PK~\I#glob/dist/commonjs/has-magic.js.mapnu[{"version":3,"file":"has-magic.js","sourceRoot":"","sources":["../../src/has-magic.ts"],"names":[],"mappings":";;;AAAA,yCAAqC;AAGrC;;;;;;;;;;GAUG;AACI,MAAM,QAAQ,GAAG,CACtB,OAA0B,EAC1B,UAAuB,EAAE,EAChB,EAAE;IACX,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QAC5B,OAAO,GAAG,CAAC,OAAO,CAAC,CAAA;IACrB,CAAC;IACD,KAAK,MAAM,CAAC,IAAI,OAAO,EAAE,CAAC;QACxB,IAAI,IAAI,qBAAS,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,QAAQ,EAAE;YAAE,OAAO,IAAI,CAAA;IACvD,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC,CAAA;AAXY,QAAA,QAAQ,YAWpB","sourcesContent":["import { Minimatch } from 'minimatch'\nimport { GlobOptions } from './glob.js'\n\n/**\n * Return true if the patterns provided contain any magic glob characters,\n * given the options provided.\n *\n * Brace expansion is not considered \"magic\" unless the `magicalBraces` option\n * is set, as brace expansion just turns one string into an array of strings.\n * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and\n * `'xby'` both do not contain any magic glob characters, and it's treated the\n * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true`\n * is in the options, brace expansion _is_ treated as a pattern having magic.\n */\nexport const hasMagic = (\n  pattern: string | string[],\n  options: GlobOptions = {},\n): boolean => {\n  if (!Array.isArray(pattern)) {\n    pattern = [pattern]\n  }\n  for (const p of pattern) {\n    if (new Minimatch(p, options).hasMagic()) return true\n  }\n  return false\n}\n"]}PK~\o!glob/dist/commonjs/index.d.ts.mapnu[{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AACnC,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,KAAK,EACV,WAAW,EACX,6BAA6B,EAC7B,4BAA4B,EAC5B,6BAA6B,EAC9B,MAAM,WAAW,CAAA;AAClB,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAGhC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AAC5C,YAAY,EACV,QAAQ,EACR,IAAI,EACJ,WAAW,EACX,4BAA4B,EAC5B,6BAA6B,GAC9B,MAAM,aAAa,CAAA;AACpB,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,YAAY,EACV,WAAW,EACX,6BAA6B,EAC7B,4BAA4B,EAC5B,6BAA6B,GAC9B,MAAM,WAAW,CAAA;AAClB,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAA;AACzC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACpC,YAAY,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAC7C,YAAY,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aAAM,CAAC;YACN,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,CAAA;QAC5B,CAAC;IACH,CAAC;CACF;AA9ND,8BA8NC","sourcesContent":["// synchronous utility for filtering entries and calculating subwalks\n\nimport { GLOBSTAR, MMRegExp } from 'minimatch'\nimport { Path } from 'path-scurry'\nimport { MMPattern, Pattern } from './pattern.js'\nimport { GlobWalkerOpts } from './walker.js'\n\n/**\n * A cache of which patterns have been processed for a given Path\n */\nexport class HasWalkedCache {\n  store: Map>\n  constructor(store: Map> = new Map()) {\n    this.store = store\n  }\n  copy() {\n    return new HasWalkedCache(new Map(this.store))\n  }\n  hasWalked(target: Path, pattern: Pattern) {\n    return this.store.get(target.fullpath())?.has(pattern.globString())\n  }\n  storeWalked(target: Path, pattern: Pattern) {\n    const fullpath = target.fullpath()\n    const cached = this.store.get(fullpath)\n    if (cached) cached.add(pattern.globString())\n    else this.store.set(fullpath, new Set([pattern.globString()]))\n  }\n}\n\n/**\n * A record of which paths have been matched in a given walk step,\n * and whether they only are considered a match if they are a directory,\n * and whether their absolute or relative path should be returned.\n */\nexport class MatchRecord {\n  store: Map = new Map()\n  add(target: Path, absolute: boolean, ifDir: boolean) {\n    const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0)\n    const current = this.store.get(target)\n    this.store.set(target, current === undefined ? n : n & current)\n  }\n  // match, absolute, ifdir\n  entries(): [Path, boolean, boolean][] {\n    return [...this.store.entries()].map(([path, n]) => [\n      path,\n      !!(n & 2),\n      !!(n & 1),\n    ])\n  }\n}\n\n/**\n * A collection of patterns that must be processed in a subsequent step\n * for a given path.\n */\nexport class SubWalks {\n  store: Map = new Map()\n  add(target: Path, pattern: Pattern) {\n    if (!target.canReaddir()) {\n      return\n    }\n    const subs = this.store.get(target)\n    if (subs) {\n      if (!subs.find(p => p.globString() === pattern.globString())) {\n        subs.push(pattern)\n      }\n    } else this.store.set(target, [pattern])\n  }\n  get(target: Path): Pattern[] {\n    const subs = this.store.get(target)\n    /* c8 ignore start */\n    if (!subs) {\n      throw new Error('attempting to walk unknown path')\n    }\n    /* c8 ignore stop */\n    return subs\n  }\n  entries(): [Path, Pattern[]][] {\n    return this.keys().map(k => [k, this.store.get(k) as Pattern[]])\n  }\n  keys(): Path[] {\n    return [...this.store.keys()].filter(t => t.canReaddir())\n  }\n}\n\n/**\n * The class that processes patterns for a given path.\n *\n * Handles child entry filtering, and determining whether a path's\n * directory contents must be read.\n */\nexport class Processor {\n  hasWalkedCache: HasWalkedCache\n  matches = new MatchRecord()\n  subwalks = new SubWalks()\n  patterns?: Pattern[]\n  follow: boolean\n  dot: boolean\n  opts: GlobWalkerOpts\n\n  constructor(opts: GlobWalkerOpts, hasWalkedCache?: HasWalkedCache) {\n    this.opts = opts\n    this.follow = !!opts.follow\n    this.dot = !!opts.dot\n    this.hasWalkedCache =\n      hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache()\n  }\n\n  processPatterns(target: Path, patterns: Pattern[]) {\n    this.patterns = patterns\n    const processingSet: [Path, Pattern][] = patterns.map(p => [target, p])\n\n    // map of paths to the magic-starting subwalks they need to walk\n    // first item in patterns is the filter\n\n    for (let [t, pattern] of processingSet) {\n      this.hasWalkedCache.storeWalked(t, pattern)\n\n      const root = pattern.root()\n      const absolute = pattern.isAbsolute() && this.opts.absolute !== false\n\n      // start absolute patterns at root\n      if (root) {\n        t = t.resolve(\n          root === '/' && this.opts.root !== undefined ?\n            this.opts.root\n          : root,\n        )\n        const rest = pattern.rest()\n        if (!rest) {\n          this.matches.add(t, true, false)\n          continue\n        } else {\n          pattern = rest\n        }\n      }\n\n      if (t.isENOENT()) continue\n\n      let p: MMPattern\n      let rest: Pattern | null\n      let changed = false\n      while (\n        typeof (p = pattern.pattern()) === 'string' &&\n        (rest = pattern.rest())\n      ) {\n        const c = t.resolve(p)\n        t = c\n        pattern = rest\n        changed = true\n      }\n      p = pattern.pattern()\n      rest = pattern.rest()\n      if (changed) {\n        if (this.hasWalkedCache.hasWalked(t, pattern)) continue\n        this.hasWalkedCache.storeWalked(t, pattern)\n      }\n\n      // now we have either a final string for a known entry,\n      // more strings for an unknown entry,\n      // or a pattern starting with magic, mounted on t.\n      if (typeof p === 'string') {\n        // must not be final entry, otherwise we would have\n        // concatenated it earlier.\n        const ifDir = p === '..' || p === '' || p === '.'\n        this.matches.add(t.resolve(p), absolute, ifDir)\n        continue\n      } else if (p === GLOBSTAR) {\n        // if no rest, match and subwalk pattern\n        // if rest, process rest and subwalk pattern\n        // if it's a symlink, but we didn't get here by way of a\n        // globstar match (meaning it's the first time THIS globstar\n        // has traversed a symlink), then we follow it. Otherwise, stop.\n        if (\n          !t.isSymbolicLink() ||\n          this.follow ||\n          pattern.checkFollowGlobstar()\n        ) {\n          this.subwalks.add(t, pattern)\n        }\n        const rp = rest?.pattern()\n        const rrest = rest?.rest()\n        if (!rest || ((rp === '' || rp === '.') && !rrest)) {\n          // only HAS to be a dir if it ends in **/ or **/.\n          // but ending in ** will match files as well.\n          this.matches.add(t, absolute, rp === '' || rp === '.')\n        } else {\n          if (rp === '..') {\n            // this would mean you're matching **/.. at the fs root,\n            // and no thanks, I'm not gonna test that specific case.\n            /* c8 ignore start */\n            const tp = t.parent || t\n            /* c8 ignore stop */\n            if (!rrest) this.matches.add(tp, absolute, true)\n            else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {\n              this.subwalks.add(tp, rrest)\n            }\n          }\n        }\n      } else if (p instanceof RegExp) {\n        this.subwalks.add(t, pattern)\n      }\n    }\n\n    return this\n  }\n\n  subwalkTargets(): Path[] {\n    return this.subwalks.keys()\n  }\n\n  child() {\n    return new Processor(this.opts, this.hasWalkedCache)\n  }\n\n  // return a new Processor containing the subwalks for each\n  // child entry, and a set of matches, and\n  // a hasWalkedCache that's a copy of this one\n  // then we're going to call\n  filterEntries(parent: Path, entries: Path[]): Processor {\n    const patterns = this.subwalks.get(parent)\n    // put matches and entry walks into the results processor\n    const results = this.child()\n    for (const e of entries) {\n      for (const pattern of patterns) {\n        const absolute = pattern.isAbsolute()\n        const p = pattern.pattern()\n        const rest = pattern.rest()\n        if (p === GLOBSTAR) {\n          results.testGlobstar(e, pattern, rest, absolute)\n        } else if (p instanceof RegExp) {\n          results.testRegExp(e, p, rest, absolute)\n        } else {\n          results.testString(e, p, rest, absolute)\n        }\n      }\n    }\n    return results\n  }\n\n  testGlobstar(\n    e: Path,\n    pattern: Pattern,\n    rest: Pattern | null,\n    absolute: boolean,\n  ) {\n    if (this.dot || !e.name.startsWith('.')) {\n      if (!pattern.hasMore()) {\n        this.matches.add(e, absolute, false)\n      }\n      if (e.canReaddir()) {\n        // if we're in follow mode or it's not a symlink, just keep\n        // testing the same pattern. If there's more after the globstar,\n        // then this symlink consumes the globstar. If not, then we can\n        // follow at most ONE symlink along the way, so we mark it, which\n        // also checks to ensure that it wasn't already marked.\n        if (this.follow || !e.isSymbolicLink()) {\n          this.subwalks.add(e, pattern)\n        } else if (e.isSymbolicLink()) {\n          if (rest && pattern.checkFollowGlobstar()) {\n            this.subwalks.add(e, rest)\n          } else if (pattern.markFollowGlobstar()) {\n            this.subwalks.add(e, pattern)\n          }\n        }\n      }\n    }\n    // if the NEXT thing matches this entry, then also add\n    // the rest.\n    if (rest) {\n      const rp = rest.pattern()\n      if (\n        typeof rp === 'string' &&\n        // dots and empty were handled already\n        rp !== '..' &&\n        rp !== '' &&\n        rp !== '.'\n      ) {\n        this.testString(e, rp, rest.rest(), absolute)\n      } else if (rp === '..') {\n        /* c8 ignore start */\n        const ep = e.parent || e\n        /* c8 ignore stop */\n        this.subwalks.add(ep, rest)\n      } else if (rp instanceof RegExp) {\n        this.testRegExp(e, rp, rest.rest(), absolute)\n      }\n    }\n  }\n\n  testRegExp(\n    e: Path,\n    p: MMRegExp,\n    rest: Pattern | null,\n    absolute: boolean,\n  ) {\n    if (!p.test(e.name)) return\n    if (!rest) {\n      this.matches.add(e, absolute, false)\n    } else {\n      this.subwalks.add(e, rest)\n    }\n  }\n\n  testString(e: Path, p: string, rest: Pattern | null, absolute: boolean) {\n    // should never happen?\n    if (!e.isNamed(p)) return\n    if (!rest) {\n      this.matches.add(e, absolute, false)\n    } else {\n      this.subwalks.add(e, rest)\n    }\n  }\n}\n"]}PK~\Lglob/dist/commonjs/walker.d.tsnu[/// 
/**
 * Single-use utility classes to provide functionality to the {@link Glob}
 * methods.
 *
 * @module
 */
import { Minipass } from 'minipass';
import { Path } from 'path-scurry';
import { IgnoreLike } from './ignore.js';
import { Pattern } from './pattern.js';
import { Processor } from './processor.js';
export interface GlobWalkerOpts {
    absolute?: boolean;
    allowWindowsEscape?: boolean;
    cwd?: string | URL;
    dot?: boolean;
    dotRelative?: boolean;
    follow?: boolean;
    ignore?: string | string[] | IgnoreLike;
    mark?: boolean;
    matchBase?: boolean;
    maxDepth?: number;
    nobrace?: boolean;
    nocase?: boolean;
    nodir?: boolean;
    noext?: boolean;
    noglobstar?: boolean;
    platform?: NodeJS.Platform;
    posix?: boolean;
    realpath?: boolean;
    root?: string;
    stat?: boolean;
    signal?: AbortSignal;
    windowsPathsNoEscape?: boolean;
    withFileTypes?: boolean;
    includeChildMatches?: boolean;
}
export type GWOFileTypesTrue = GlobWalkerOpts & {
    withFileTypes: true;
};
export type GWOFileTypesFalse = GlobWalkerOpts & {
    withFileTypes: false;
};
export type GWOFileTypesUnset = GlobWalkerOpts & {
    withFileTypes?: undefined;
};
export type Result = O extends GWOFileTypesTrue ? Path : O extends GWOFileTypesFalse ? string : O extends GWOFileTypesUnset ? string : Path | string;
export type Matches = O extends GWOFileTypesTrue ? Set : O extends GWOFileTypesFalse ? Set : O extends GWOFileTypesUnset ? Set : Set;
export type MatchStream = Minipass, Result>;
/**
 * basic walking utilities that all the glob walker types use
 */
export declare abstract class GlobUtil {
    #private;
    path: Path;
    patterns: Pattern[];
    opts: O;
    seen: Set;
    paused: boolean;
    aborted: boolean;
    signal?: AbortSignal;
    maxDepth: number;
    includeChildMatches: boolean;
    constructor(patterns: Pattern[], path: Path, opts: O);
    pause(): void;
    resume(): void;
    onResume(fn: () => any): void;
    matchCheck(e: Path, ifDir: boolean): Promise;
    matchCheckTest(e: Path | undefined, ifDir: boolean): Path | undefined;
    matchCheckSync(e: Path, ifDir: boolean): Path | undefined;
    abstract matchEmit(p: Result): void;
    abstract matchEmit(p: string | Path): void;
    matchFinish(e: Path, absolute: boolean): void;
    match(e: Path, absolute: boolean, ifDir: boolean): Promise;
    matchSync(e: Path, absolute: boolean, ifDir: boolean): void;
    walkCB(target: Path, patterns: Pattern[], cb: () => any): void;
    walkCB2(target: Path, patterns: Pattern[], processor: Processor, cb: () => any): any;
    walkCB3(target: Path, entries: Path[], processor: Processor, cb: () => any): void;
    walkCBSync(target: Path, patterns: Pattern[], cb: () => any): void;
    walkCB2Sync(target: Path, patterns: Pattern[], processor: Processor, cb: () => any): any;
    walkCB3Sync(target: Path, entries: Path[], processor: Processor, cb: () => any): void;
}
export declare class GlobWalker extends GlobUtil {
    matches: Set>;
    constructor(patterns: Pattern[], path: Path, opts: O);
    matchEmit(e: Result): void;
    walk(): Promise>>;
    walkSync(): Set>;
}
export declare class GlobStream extends GlobUtil {
    results: Minipass, Result>;
    constructor(patterns: Pattern[], path: Path, opts: O);
    matchEmit(e: Result): void;
    stream(): MatchStream;
    streamSync(): MatchStream;
}
//# sourceMappingURL=walker.d.ts.mapPK~\tY""glob/dist/commonjs/has-magic.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.hasMagic = void 0;
const minimatch_1 = require("minimatch");
/**
 * Return true if the patterns provided contain any magic glob characters,
 * given the options provided.
 *
 * Brace expansion is not considered "magic" unless the `magicalBraces` option
 * is set, as brace expansion just turns one string into an array of strings.
 * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and
 * `'xby'` both do not contain any magic glob characters, and it's treated the
 * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true`
 * is in the options, brace expansion _is_ treated as a pattern having magic.
 */
const hasMagic = (pattern, options = {}) => {
    if (!Array.isArray(pattern)) {
        pattern = [pattern];
    }
    for (const p of pattern) {
        if (new minimatch_1.Minimatch(p, options).hasMagic())
            return true;
    }
    return false;
};
exports.hasMagic = hasMagic;
//# sourceMappingURL=has-magic.js.mapPK~\25ww"glob/dist/commonjs/ignore.d.ts.mapnu[{"version":3,"file":"ignore.d.ts","sourceRoot":"","sources":["../../src/ignore.ts"],"names":[],"mappings":";AAKA,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAA;AACvD,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAElC,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAE5C,MAAM,WAAW,UAAU;IACzB,OAAO,CAAC,EAAE,CAAC,CAAC,EAAE,IAAI,KAAK,OAAO,CAAA;IAC9B,eAAe,CAAC,EAAE,CAAC,CAAC,EAAE,IAAI,KAAK,OAAO,CAAA;IACtC,GAAG,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,CAAA;CAC/B;AAWD;;GAEG;AACH,qBAAa,MAAO,YAAW,UAAU;IACvC,QAAQ,EAAE,SAAS,EAAE,CAAA;IACrB,gBAAgB,EAAE,SAAS,EAAE,CAAA;IAC7B,QAAQ,EAAE,SAAS,EAAE,CAAA;IACrB,gBAAgB,EAAE,SAAS,EAAE,CAAA;IAC7B,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAA;IACzB,MAAM,EAAE,gBAAgB,CAAA;gBAGtB,OAAO,EAAE,MAAM,EAAE,EACjB,EACE,OAAO,EACP,MAAM,EACN,KAAK,EACL,UAAU,EACV,QAA0B,GAC3B,EAAE,cAAc;IAqBnB,GAAG,CAAC,GAAG,EAAE,MAAM;IAyCf,OAAO,CAAC,CAAC,EAAE,IAAI,GAAG,OAAO;IAczB,eAAe,CAAC,CAAC,EAAE,IAAI,GAAG,OAAO;CAWlC"}PK~\u
vddglob/dist/commonjs/pattern.d.tsnu[/// 
import { GLOBSTAR } from 'minimatch';
export type MMPattern = string | RegExp | typeof GLOBSTAR;
export type PatternList = [p: MMPattern, ...rest: MMPattern[]];
export type UNCPatternList = [
    p0: '',
    p1: '',
    p2: string,
    p3: string,
    ...rest: MMPattern[]
];
export type DrivePatternList = [p0: string, ...rest: MMPattern[]];
export type AbsolutePatternList = [p0: '', ...rest: MMPattern[]];
export type GlobList = [p: string, ...rest: string[]];
/**
 * An immutable-ish view on an array of glob parts and their parsed
 * results
 */
export declare class Pattern {
    #private;
    readonly length: number;
    constructor(patternList: MMPattern[], globList: string[], index: number, platform: NodeJS.Platform);
    /**
     * The first entry in the parsed list of patterns
     */
    pattern(): MMPattern;
    /**
     * true of if pattern() returns a string
     */
    isString(): boolean;
    /**
     * true of if pattern() returns GLOBSTAR
     */
    isGlobstar(): boolean;
    /**
     * true if pattern() returns a regexp
     */
    isRegExp(): boolean;
    /**
     * The /-joined set of glob parts that make up this pattern
     */
    globString(): string;
    /**
     * true if there are more pattern parts after this one
     */
    hasMore(): boolean;
    /**
     * The rest of the pattern after this part, or null if this is the end
     */
    rest(): Pattern | null;
    /**
     * true if the pattern represents a //unc/path/ on windows
     */
    isUNC(): boolean;
    /**
     * True if the pattern starts with a drive letter on Windows
     */
    isDrive(): boolean;
    /**
     * True if the pattern is rooted on an absolute path
     */
    isAbsolute(): boolean;
    /**
     * consume the root of the pattern, and return it
     */
    root(): string;
    /**
     * Check to see if the current globstar pattern is allowed to follow
     * a symbolic link.
     */
    checkFollowGlobstar(): boolean;
    /**
     * Mark that the current globstar pattern is following a symbolic link
     */
    markFollowGlobstar(): boolean;
}
//# sourceMappingURL=pattern.d.ts.mapPK~\vN!glob/dist/commonjs/has-magic.d.tsnu[import { GlobOptions } from './glob.js';
/**
 * Return true if the patterns provided contain any magic glob characters,
 * given the options provided.
 *
 * Brace expansion is not considered "magic" unless the `magicalBraces` option
 * is set, as brace expansion just turns one string into an array of strings.
 * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and
 * `'xby'` both do not contain any magic glob characters, and it's treated the
 * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true`
 * is in the options, brace expansion _is_ treated as a pattern having magic.
 */
export declare const hasMagic: (pattern: string | string[], options?: GlobOptions) => boolean;
//# sourceMappingURL=has-magic.d.ts.mapPK~\`8_%glob/dist/commonjs/processor.d.ts.mapnu[{"version":3,"file":"processor.d.ts","sourceRoot":"","sources":["../../src/processor.ts"],"names":[],"mappings":"AAEA,OAAO,EAAY,QAAQ,EAAE,MAAM,WAAW,CAAA;AAC9C,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,EAAa,OAAO,EAAE,MAAM,cAAc,CAAA;AACjD,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAE5C;;GAEG;AACH,qBAAa,cAAc;IACzB,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAA;gBACnB,KAAK,GAAE,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAa;IAGvD,IAAI;IAGJ,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO;IAGxC,WAAW,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO;CAM3C;AAED;;;;GAIG;AACH,qBAAa,WAAW;IACtB,KAAK,EAAE,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,CAAY;IACpC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO;IAMnD,OAAO,IAAI,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE;CAOtC;AAED;;;GAGG;AACH,qBAAa,QAAQ;IACnB,KAAK,EAAE,GAAG,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,CAAY;IACvC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO;IAWlC,GAAG,CAAC,MAAM,EAAE,IAAI,GAAG,OAAO,EAAE;IAS5B,OAAO,IAAI,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE;IAG9B,IAAI,IAAI,IAAI,EAAE;CAGf;AAED;;;;;GAKG;AACH,qBAAa,SAAS;IACpB,cAAc,EAAE,cAAc,CAAA;IAC9B,OAAO,cAAoB;IAC3B,QAAQ,WAAiB;IACzB,QAAQ,CAAC,EAAE,OAAO,EAAE,CAAA;IACpB,MAAM,EAAE,OAAO,CAAA;IACf,GAAG,EAAE,OAAO,CAAA;IACZ,IAAI,EAAE,cAAc,CAAA;gBAER,IAAI,EAAE,cAAc,EAAE,cAAc,CAAC,EAAE,cAAc;IAQjE,eAAe,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE;IAmGjD,cAAc,IAAI,IAAI,EAAE;IAIxB,KAAK;IAQL,aAAa,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,SAAS;IAqBvD,YAAY,CACV,CAAC,EAAE,IAAI,EACP,OAAO,EAAE,OAAO,EAChB,IAAI,EAAE,OAAO,GAAG,IAAI,EACpB,QAAQ,EAAE,OAAO;IA8CnB,UAAU,CACR,CAAC,EAAE,IAAI,EACP,CAAC,EAAE,QAAQ,EACX,IAAI,EAAE,OAAO,GAAG,IAAI,EACpB,QAAQ,EAAE,OAAO;IAUnB,UAAU,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,IAAI,EAAE,QAAQ,EAAE,OAAO;CASvE"}PK~\m
)99glob/dist/commonjs/glob.d.tsnu[/// 
import { Minimatch } from 'minimatch';
import { Minipass } from 'minipass';
import { FSOption, Path, PathScurry } from 'path-scurry';
import { IgnoreLike } from './ignore.js';
import { Pattern } from './pattern.js';
export type MatchSet = Minimatch['set'];
export type GlobParts = Exclude;
/**
 * A `GlobOptions` object may be provided to any of the exported methods, and
 * must be provided to the `Glob` constructor.
 *
 * All options are optional, boolean, and false by default, unless otherwise
 * noted.
 *
 * All resolved options are added to the Glob object as properties.
 *
 * If you are running many `glob` operations, you can pass a Glob object as the
 * `options` argument to a subsequent operation to share the previously loaded
 * cache.
 */
export interface GlobOptions {
    /**
     * Set to `true` to always receive absolute paths for
     * matched files. Set to `false` to always return relative paths.
     *
     * When this option is not set, absolute paths are returned for patterns
     * that are absolute, and otherwise paths are returned that are relative
     * to the `cwd` setting.
     *
     * This does _not_ make an extra system call to get
     * the realpath, it only does string path resolution.
     *
     * Conflicts with {@link withFileTypes}
     */
    absolute?: boolean;
    /**
     * Set to false to enable {@link windowsPathsNoEscape}
     *
     * @deprecated
     */
    allowWindowsEscape?: boolean;
    /**
     * The current working directory in which to search. Defaults to
     * `process.cwd()`.
     *
     * May be eiher a string path or a `file://` URL object or string.
     */
    cwd?: string | URL;
    /**
     * Include `.dot` files in normal matches and `globstar`
     * matches. Note that an explicit dot in a portion of the pattern
     * will always match dot files.
     */
    dot?: boolean;
    /**
     * Prepend all relative path strings with `./` (or `.\` on Windows).
     *
     * Without this option, returned relative paths are "bare", so instead of
     * returning `'./foo/bar'`, they are returned as `'foo/bar'`.
     *
     * Relative patterns starting with `'../'` are not prepended with `./`, even
     * if this option is set.
     */
    dotRelative?: boolean;
    /**
     * Follow symlinked directories when expanding `**`
     * patterns. This can result in a lot of duplicate references in
     * the presence of cyclic links, and make performance quite bad.
     *
     * By default, a `**` in a pattern will follow 1 symbolic link if
     * it is not the first item in the pattern, or none if it is the
     * first item in the pattern, following the same behavior as Bash.
     */
    follow?: boolean;
    /**
     * string or string[], or an object with `ignore` and `ignoreChildren`
     * methods.
     *
     * If a string or string[] is provided, then this is treated as a glob
     * pattern or array of glob patterns to exclude from matches. To ignore all
     * children within a directory, as well as the entry itself, append `'/**'`
     * to the ignore pattern.
     *
     * **Note** `ignore` patterns are _always_ in `dot:true` mode, regardless of
     * any other settings.
     *
     * If an object is provided that has `ignored(path)` and/or
     * `childrenIgnored(path)` methods, then these methods will be called to
     * determine whether any Path is a match or if its children should be
     * traversed, respectively.
     */
    ignore?: string | string[] | IgnoreLike;
    /**
     * Treat brace expansion like `{a,b}` as a "magic" pattern. Has no
     * effect if {@link nobrace} is set.
     *
     * Only has effect on the {@link hasMagic} function.
     */
    magicalBraces?: boolean;
    /**
     * Add a `/` character to directory matches. Note that this requires
     * additional stat calls in some cases.
     */
    mark?: boolean;
    /**
     * Perform a basename-only match if the pattern does not contain any slash
     * characters. That is, `*.js` would be treated as equivalent to
     * `**\/*.js`, matching all js files in all directories.
     */
    matchBase?: boolean;
    /**
     * Limit the directory traversal to a given depth below the cwd.
     * Note that this does NOT prevent traversal to sibling folders,
     * root patterns, and so on. It only limits the maximum folder depth
     * that the walk will descend, relative to the cwd.
     */
    maxDepth?: number;
    /**
     * Do not expand `{a,b}` and `{1..3}` brace sets.
     */
    nobrace?: boolean;
    /**
     * Perform a case-insensitive match. This defaults to `true` on macOS and
     * Windows systems, and `false` on all others.
     *
     * **Note** `nocase` should only be explicitly set when it is
     * known that the filesystem's case sensitivity differs from the
     * platform default. If set `true` on case-sensitive file
     * systems, or `false` on case-insensitive file systems, then the
     * walk may return more or less results than expected.
     */
    nocase?: boolean;
    /**
     * Do not match directories, only files. (Note: to match
     * _only_ directories, put a `/` at the end of the pattern.)
     */
    nodir?: boolean;
    /**
     * Do not match "extglob" patterns such as `+(a|b)`.
     */
    noext?: boolean;
    /**
     * Do not match `**` against multiple filenames. (Ie, treat it as a normal
     * `*` instead.)
     *
     * Conflicts with {@link matchBase}
     */
    noglobstar?: boolean;
    /**
     * Defaults to value of `process.platform` if available, or `'linux'` if
     * not. Setting `platform:'win32'` on non-Windows systems may cause strange
     * behavior.
     */
    platform?: NodeJS.Platform;
    /**
     * Set to true to call `fs.realpath` on all of the
     * results. In the case of an entry that cannot be resolved, the
     * entry is omitted. This incurs a slight performance penalty, of
     * course, because of the added system calls.
     */
    realpath?: boolean;
    /**
     *
     * A string path resolved against the `cwd` option, which
     * is used as the starting point for absolute patterns that start
     * with `/`, (but not drive letters or UNC paths on Windows).
     *
     * Note that this _doesn't_ necessarily limit the walk to the
     * `root` directory, and doesn't affect the cwd starting point for
     * non-absolute patterns. A pattern containing `..` will still be
     * able to traverse out of the root directory, if it is not an
     * actual root directory on the filesystem, and any non-absolute
     * patterns will be matched in the `cwd`. For example, the
     * pattern `/../*` with `{root:'/some/path'}` will return all
     * files in `/some`, not all files in `/some/path`. The pattern
     * `*` with `{root:'/some/path'}` will return all the entries in
     * the cwd, not the entries in `/some/path`.
     *
     * To start absolute and non-absolute patterns in the same
     * path, you can use `{root:''}`. However, be aware that on
     * Windows systems, a pattern like `x:/*` or `//host/share/*` will
     * _always_ start in the `x:/` or `//host/share` directory,
     * regardless of the `root` setting.
     */
    root?: string;
    /**
     * A [PathScurry](http://npm.im/path-scurry) object used
     * to traverse the file system. If the `nocase` option is set
     * explicitly, then any provided `scurry` object must match this
     * setting.
     */
    scurry?: PathScurry;
    /**
     * Call `lstat()` on all entries, whether required or not to determine
     * if it's a valid match. When used with {@link withFileTypes}, this means
     * that matches will include data such as modified time, permissions, and
     * so on.  Note that this will incur a performance cost due to the added
     * system calls.
     */
    stat?: boolean;
    /**
     * An AbortSignal which will cancel the Glob walk when
     * triggered.
     */
    signal?: AbortSignal;
    /**
     * Use `\\` as a path separator _only_, and
     *  _never_ as an escape character. If set, all `\\` characters are
     *  replaced with `/` in the pattern.
     *
     *  Note that this makes it **impossible** to match against paths
     *  containing literal glob pattern characters, but allows matching
     *  with patterns constructed using `path.join()` and
     *  `path.resolve()` on Windows platforms, mimicking the (buggy!)
     *  behavior of Glob v7 and before on Windows. Please use with
     *  caution, and be mindful of [the caveat below about Windows
     *  paths](#windows). (For legacy reasons, this is also set if
     *  `allowWindowsEscape` is set to the exact value `false`.)
     */
    windowsPathsNoEscape?: boolean;
    /**
     * Return [PathScurry](http://npm.im/path-scurry)
     * `Path` objects instead of strings. These are similar to a
     * NodeJS `Dirent` object, but with additional methods and
     * properties.
     *
     * Conflicts with {@link absolute}
     */
    withFileTypes?: boolean;
    /**
     * An fs implementation to override some or all of the defaults.  See
     * http://npm.im/path-scurry for details about what can be overridden.
     */
    fs?: FSOption;
    /**
     * Just passed along to Minimatch.  Note that this makes all pattern
     * matching operations slower and *extremely* noisy.
     */
    debug?: boolean;
    /**
     * Return `/` delimited paths, even on Windows.
     *
     * On posix systems, this has no effect.  But, on Windows, it means that
     * paths will be `/` delimited, and absolute paths will be their full
     * resolved UNC forms, eg instead of `'C:\\foo\\bar'`, it would return
     * `'//?/C:/foo/bar'`
     */
    posix?: boolean;
    /**
     * Do not match any children of any matches. For example, the pattern
     * `**\/foo` would match `a/foo`, but not `a/foo/b/foo` in this mode.
     *
     * This is especially useful for cases like "find all `node_modules`
     * folders, but not the ones in `node_modules`".
     *
     * In order to support this, the `Ignore` implementation must support an
     * `add(pattern: string)` method. If using the default `Ignore` class, then
     * this is fine, but if this is set to `false`, and a custom `Ignore` is
     * provided that does not have an `add()` method, then it will throw an
     * error.
     *
     * **Caveat** It *only* ignores matches that would be a descendant of a
     * previous match, and only if that descendant is matched *after* the
     * ancestor is encountered. Since the file system walk happens in
     * indeterminate order, it's possible that a match will already be added
     * before its ancestor, if multiple or braced patterns are used.
     *
     * For example:
     *
     * ```ts
     * const results = await glob([
     *   // likely to match first, since it's just a stat
     *   'a/b/c/d/e/f',
     *
     *   // this pattern is more complicated! It must to various readdir()
     *   // calls and test the results against a regular expression, and that
     *   // is certainly going to take a little bit longer.
     *   //
     *   // So, later on, it encounters a match at 'a/b/c/d/e', but it's too
     *   // late to ignore a/b/c/d/e/f, because it's already been emitted.
     *   'a/[bdf]/?/[a-z]/*',
     * ], { includeChildMatches: false })
     * ```
     *
     * It's best to only set this to `false` if you can be reasonably sure that
     * no components of the pattern will potentially match one another's file
     * system descendants, or if the occasional included child entry will not
     * cause problems.
     *
     * @default true
     */
    includeChildMatches?: boolean;
}
export type GlobOptionsWithFileTypesTrue = GlobOptions & {
    withFileTypes: true;
    absolute?: undefined;
    mark?: undefined;
    posix?: undefined;
};
export type GlobOptionsWithFileTypesFalse = GlobOptions & {
    withFileTypes?: false;
};
export type GlobOptionsWithFileTypesUnset = GlobOptions & {
    withFileTypes?: undefined;
};
export type Result = Opts extends GlobOptionsWithFileTypesTrue ? Path : Opts extends GlobOptionsWithFileTypesFalse ? string : Opts extends GlobOptionsWithFileTypesUnset ? string : string | Path;
export type Results = Result[];
export type FileTypes = Opts extends GlobOptionsWithFileTypesTrue ? true : Opts extends GlobOptionsWithFileTypesFalse ? false : Opts extends GlobOptionsWithFileTypesUnset ? false : boolean;
/**
 * An object that can perform glob pattern traversals.
 */
export declare class Glob implements GlobOptions {
    absolute?: boolean;
    cwd: string;
    root?: string;
    dot: boolean;
    dotRelative: boolean;
    follow: boolean;
    ignore?: string | string[] | IgnoreLike;
    magicalBraces: boolean;
    mark?: boolean;
    matchBase: boolean;
    maxDepth: number;
    nobrace: boolean;
    nocase: boolean;
    nodir: boolean;
    noext: boolean;
    noglobstar: boolean;
    pattern: string[];
    platform: NodeJS.Platform;
    realpath: boolean;
    scurry: PathScurry;
    stat: boolean;
    signal?: AbortSignal;
    windowsPathsNoEscape: boolean;
    withFileTypes: FileTypes;
    includeChildMatches: boolean;
    /**
     * The options provided to the constructor.
     */
    opts: Opts;
    /**
     * An array of parsed immutable {@link Pattern} objects.
     */
    patterns: Pattern[];
    /**
     * All options are stored as properties on the `Glob` object.
     *
     * See {@link GlobOptions} for full options descriptions.
     *
     * Note that a previous `Glob` object can be passed as the
     * `GlobOptions` to another `Glob` instantiation to re-use settings
     * and caches with a new pattern.
     *
     * Traversal functions can be called multiple times to run the walk
     * again.
     */
    constructor(pattern: string | string[], opts: Opts);
    /**
     * Returns a Promise that resolves to the results array.
     */
    walk(): Promise>;
    /**
     * synchronous {@link Glob.walk}
     */
    walkSync(): Results;
    /**
     * Stream results asynchronously.
     */
    stream(): Minipass, Result>;
    /**
     * Stream results synchronously.
     */
    streamSync(): Minipass, Result>;
    /**
     * Default sync iteration function. Returns a Generator that
     * iterates over the results.
     */
    iterateSync(): Generator, void, void>;
    [Symbol.iterator](): Generator, void, void>;
    /**
     * Default async iteration function. Returns an AsyncGenerator that
     * iterates over the results.
     */
    iterate(): AsyncGenerator, void, void>;
    [Symbol.asyncIterator](): AsyncGenerator, void, void>;
}
//# sourceMappingURL=glob.d.ts.mapPK~\ll glob/dist/commonjs/walker.js.mapnu[{"version":3,"file":"walker.js","sourceRoot":"","sources":["../../src/walker.ts"],"names":[],"mappings":";;;AAAA;;;;;GAKG;AACH,uCAAmC;AAEnC,2CAAgD;AAQhD,iDAA0C;AA0D1C,MAAM,UAAU,GAAG,CACjB,MAAsC,EACtC,IAAoB,EACR,EAAE,CACd,OAAO,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,kBAAM,CAAC,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC;IACvD,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,kBAAM,CAAC,MAAM,EAAE,IAAI,CAAC;QAClD,CAAC,CAAC,MAAM,CAAA;AAEV;;GAEG;AACH,MAAsB,QAAQ;IAC5B,IAAI,CAAM;IACV,QAAQ,CAAW;IACnB,IAAI,CAAG;IACP,IAAI,GAAc,IAAI,GAAG,EAAQ,CAAA;IACjC,MAAM,GAAY,KAAK,CAAA;IACvB,OAAO,GAAY,KAAK,CAAA;IACxB,SAAS,GAAkB,EAAE,CAAA;IAC7B,OAAO,CAAa;IACpB,IAAI,CAAY;IAChB,MAAM,CAAc;IACpB,QAAQ,CAAQ;IAChB,mBAAmB,CAAS;IAG5B,YAAY,QAAmB,EAAE,IAAU,EAAE,IAAO;QAClD,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;QACxB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;QAChB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;QAChB,IAAI,CAAC,IAAI,GAAG,CAAC,IAAI,CAA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E,EAAE,CAAC;YAC1B,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAA;QACvB,CAAC;QACD,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAA;QACnE,OAAO,IAAI,CAAC,OAAO,CAAA;IACrB,CAAC;CACF;AAvCD,gCAuCC","sourcesContent":["/**\n * Single-use utility classes to provide functionality to the {@link Glob}\n * methods.\n *\n * @module\n */\nimport { Minipass } from 'minipass'\nimport { Path } from 'path-scurry'\nimport { Ignore, IgnoreLike } from './ignore.js'\n\n// XXX can we somehow make it so that it NEVER processes a given path more than\n// once, enough that the match set tracking is no longer needed?  that'd speed\n// things up a lot.  Or maybe bring back nounique, and skip it in that case?\n\n// a single minimatch set entry with 1 or more parts\nimport { Pattern } from './pattern.js'\nimport { Processor } from './processor.js'\n\nexport interface GlobWalkerOpts {\n  absolute?: boolean\n  allowWindowsEscape?: boolean\n  cwd?: string | URL\n  dot?: boolean\n  dotRelative?: boolean\n  follow?: boolean\n  ignore?: string | string[] | IgnoreLike\n  mark?: boolean\n  matchBase?: boolean\n  // Note: maxDepth here means \"maximum actual Path.depth()\",\n  // not \"maximum depth beyond cwd\"\n  maxDepth?: number\n  nobrace?: boolean\n  nocase?: boolean\n  nodir?: boolean\n  noext?: boolean\n  noglobstar?: boolean\n  platform?: NodeJS.Platform\n  posix?: boolean\n  realpath?: boolean\n  root?: string\n  stat?: boolean\n  signal?: AbortSignal\n  windowsPathsNoEscape?: boolean\n  withFileTypes?: boolean\n  includeChildMatches?: boolean\n}\n\nexport type GWOFileTypesTrue = GlobWalkerOpts & {\n  withFileTypes: true\n}\nexport type GWOFileTypesFalse = GlobWalkerOpts & {\n  withFileTypes: false\n}\nexport type GWOFileTypesUnset = GlobWalkerOpts & {\n  withFileTypes?: undefined\n}\n\nexport type Result =\n  O extends GWOFileTypesTrue ? Path\n  : O extends GWOFileTypesFalse ? string\n  : O extends GWOFileTypesUnset ? string\n  : Path | string\n\nexport type Matches =\n  O extends GWOFileTypesTrue ? Set\n  : O extends GWOFileTypesFalse ? Set\n  : O extends GWOFileTypesUnset ? Set\n  : Set\n\nexport type MatchStream = Minipass<\n  Result,\n  Result\n>\n\nconst makeIgnore = (\n  ignore: string | string[] | IgnoreLike,\n  opts: GlobWalkerOpts,\n): IgnoreLike =>\n  typeof ignore === 'string' ? new Ignore([ignore], opts)\n  : Array.isArray(ignore) ? new Ignore(ignore, opts)\n  : ignore\n\n/**\n * basic walking utilities that all the glob walker types use\n */\nexport abstract class GlobUtil {\n  path: Path\n  patterns: Pattern[]\n  opts: O\n  seen: Set = new Set()\n  paused: boolean = false\n  aborted: boolean = false\n  #onResume: (() => any)[] = []\n  #ignore?: IgnoreLike\n  #sep: '\\\\' | '/'\n  signal?: AbortSignal\n  maxDepth: number\n  includeChildMatches: boolean\n\n  constructor(patterns: Pattern[], path: Path, opts: O)\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    this.patterns = patterns\n    this.path = path\n    this.opts = opts\n    this.#sep = !opts.posix && opts.platform === 'win32' ? '\\\\' : '/'\n    this.includeChildMatches = opts.includeChildMatches !== false\n    if (opts.ignore || !this.includeChildMatches) {\n      this.#ignore = makeIgnore(opts.ignore ?? [], opts)\n      if (\n        !this.includeChildMatches &&\n        typeof this.#ignore.add !== 'function'\n      ) {\n        const m = 'cannot ignore child matches, ignore lacks add() method.'\n        throw new Error(m)\n      }\n    }\n    // ignore, always set with maxDepth, but it's optional on the\n    // GlobOptions type\n    /* c8 ignore start */\n    this.maxDepth = opts.maxDepth || Infinity\n    /* c8 ignore stop */\n    if (opts.signal) {\n      this.signal = opts.signal\n      this.signal.addEventListener('abort', () => {\n        this.#onResume.length = 0\n      })\n    }\n  }\n\n  #ignored(path: Path): boolean {\n    return this.seen.has(path) || !!this.#ignore?.ignored?.(path)\n  }\n  #childrenIgnored(path: Path): boolean {\n    return !!this.#ignore?.childrenIgnored?.(path)\n  }\n\n  // backpressure mechanism\n  pause() {\n    this.paused = true\n  }\n  resume() {\n    /* c8 ignore start */\n    if (this.signal?.aborted) return\n    /* c8 ignore stop */\n    this.paused = false\n    let fn: (() => any) | undefined = undefined\n    while (!this.paused && (fn = this.#onResume.shift())) {\n      fn()\n    }\n  }\n  onResume(fn: () => any) {\n    if (this.signal?.aborted) return\n    /* c8 ignore start */\n    if (!this.paused) {\n      fn()\n    } else {\n      /* c8 ignore stop */\n      this.#onResume.push(fn)\n    }\n  }\n\n  // do the requisite realpath/stat checking, and return the path\n  // to add or undefined to filter it out.\n  async matchCheck(e: Path, ifDir: boolean): Promise {\n    if (ifDir && this.opts.nodir) return undefined\n    let rpc: Path | undefined\n    if (this.opts.realpath) {\n      rpc = e.realpathCached() || (await e.realpath())\n      if (!rpc) return undefined\n      e = rpc\n    }\n    const needStat = e.isUnknown() || this.opts.stat\n    const s = needStat ? await e.lstat() : e\n    if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n      const target = await s.realpath()\n      /* c8 ignore start */\n      if (target && (target.isUnknown() || this.opts.stat)) {\n        await target.lstat()\n      }\n      /* c8 ignore stop */\n    }\n    return this.matchCheckTest(s, ifDir)\n  }\n\n  matchCheckTest(e: Path | undefined, ifDir: boolean): Path | undefined {\n    return (\n        e &&\n          (this.maxDepth === Infinity || e.depth() <= this.maxDepth) &&\n          (!ifDir || e.canReaddir()) &&\n          (!this.opts.nodir || !e.isDirectory()) &&\n          (!this.opts.nodir ||\n            !this.opts.follow ||\n            !e.isSymbolicLink() ||\n            !e.realpathCached()?.isDirectory()) &&\n          !this.#ignored(e)\n      ) ?\n        e\n      : undefined\n  }\n\n  matchCheckSync(e: Path, ifDir: boolean): Path | undefined {\n    if (ifDir && this.opts.nodir) return undefined\n    let rpc: Path | undefined\n    if (this.opts.realpath) {\n      rpc = e.realpathCached() || e.realpathSync()\n      if (!rpc) return undefined\n      e = rpc\n    }\n    const needStat = e.isUnknown() || this.opts.stat\n    const s = needStat ? e.lstatSync() : e\n    if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n      const target = s.realpathSync()\n      if (target && (target?.isUnknown() || this.opts.stat)) {\n        target.lstatSync()\n      }\n    }\n    return this.matchCheckTest(s, ifDir)\n  }\n\n  abstract matchEmit(p: Result): void\n  abstract matchEmit(p: string | Path): void\n\n  matchFinish(e: Path, absolute: boolean) {\n    if (this.#ignored(e)) return\n    // we know we have an ignore if this is false, but TS doesn't\n    if (!this.includeChildMatches && this.#ignore?.add) {\n      const ign = `${e.relativePosix()}/**`\n      this.#ignore.add(ign)\n    }\n    const abs =\n      this.opts.absolute === undefined ? absolute : this.opts.absolute\n    this.seen.add(e)\n    const mark = this.opts.mark && e.isDirectory() ? this.#sep : ''\n    // ok, we have what we need!\n    if (this.opts.withFileTypes) {\n      this.matchEmit(e)\n    } else if (abs) {\n      const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath()\n      this.matchEmit(abs + mark)\n    } else {\n      const rel = this.opts.posix ? e.relativePosix() : e.relative()\n      const pre =\n        this.opts.dotRelative && !rel.startsWith('..' + this.#sep) ?\n          '.' + this.#sep\n        : ''\n      this.matchEmit(!rel ? '.' + mark : pre + rel + mark)\n    }\n  }\n\n  async match(e: Path, absolute: boolean, ifDir: boolean): Promise {\n    const p = await this.matchCheck(e, ifDir)\n    if (p) this.matchFinish(p, absolute)\n  }\n\n  matchSync(e: Path, absolute: boolean, ifDir: boolean): void {\n    const p = this.matchCheckSync(e, ifDir)\n    if (p) this.matchFinish(p, absolute)\n  }\n\n  walkCB(target: Path, patterns: Pattern[], cb: () => any) {\n    /* c8 ignore start */\n    if (this.signal?.aborted) cb()\n    /* c8 ignore stop */\n    this.walkCB2(target, patterns, new Processor(this.opts), cb)\n  }\n\n  walkCB2(\n    target: Path,\n    patterns: Pattern[],\n    processor: Processor,\n    cb: () => any,\n  ) {\n    if (this.#childrenIgnored(target)) return cb()\n    if (this.signal?.aborted) cb()\n    if (this.paused) {\n      this.onResume(() => this.walkCB2(target, patterns, processor, cb))\n      return\n    }\n    processor.processPatterns(target, patterns)\n\n    // done processing.  all of the above is sync, can be abstracted out.\n    // subwalks is a map of paths to the entry filters they need\n    // matches is a map of paths to [absolute, ifDir] tuples.\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      tasks++\n      this.match(m, absolute, ifDir).then(() => next())\n    }\n\n    for (const t of processor.subwalkTargets()) {\n      if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n        continue\n      }\n      tasks++\n      const childrenCached = t.readdirCached()\n      if (t.calledReaddir())\n        this.walkCB3(t, childrenCached, processor, next)\n      else {\n        t.readdirCB(\n          (_, entries) => this.walkCB3(t, entries, processor, next),\n          true,\n        )\n      }\n    }\n\n    next()\n  }\n\n  walkCB3(\n    target: Path,\n    entries: Path[],\n    processor: Processor,\n    cb: () => any,\n  ) {\n    processor = processor.filterEntries(target, entries)\n\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      tasks++\n      this.match(m, absolute, ifDir).then(() => next())\n    }\n    for (const [target, patterns] of processor.subwalks.entries()) {\n      tasks++\n      this.walkCB2(target, patterns, processor.child(), next)\n    }\n\n    next()\n  }\n\n  walkCBSync(target: Path, patterns: Pattern[], cb: () => any) {\n    /* c8 ignore start */\n    if (this.signal?.aborted) cb()\n    /* c8 ignore stop */\n    this.walkCB2Sync(target, patterns, new Processor(this.opts), cb)\n  }\n\n  walkCB2Sync(\n    target: Path,\n    patterns: Pattern[],\n    processor: Processor,\n    cb: () => any,\n  ) {\n    if (this.#childrenIgnored(target)) return cb()\n    if (this.signal?.aborted) cb()\n    if (this.paused) {\n      this.onResume(() =>\n        this.walkCB2Sync(target, patterns, processor, cb),\n      )\n      return\n    }\n    processor.processPatterns(target, patterns)\n\n    // done processing.  all of the above is sync, can be abstracted out.\n    // subwalks is a map of paths to the entry filters they need\n    // matches is a map of paths to [absolute, ifDir] tuples.\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      this.matchSync(m, absolute, ifDir)\n    }\n\n    for (const t of processor.subwalkTargets()) {\n      if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n        continue\n      }\n      tasks++\n      const children = t.readdirSync()\n      this.walkCB3Sync(t, children, processor, next)\n    }\n\n    next()\n  }\n\n  walkCB3Sync(\n    target: Path,\n    entries: Path[],\n    processor: Processor,\n    cb: () => any,\n  ) {\n    processor = processor.filterEntries(target, entries)\n\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      this.matchSync(m, absolute, ifDir)\n    }\n    for (const [target, patterns] of processor.subwalks.entries()) {\n      tasks++\n      this.walkCB2Sync(target, patterns, processor.child(), next)\n    }\n\n    next()\n  }\n}\n\nexport class GlobWalker<\n  O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil {\n  matches = new Set>()\n\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    super(patterns, path, opts)\n  }\n\n  matchEmit(e: Result): void {\n    this.matches.add(e)\n  }\n\n  async walk(): Promise>> {\n    if (this.signal?.aborted) throw this.signal.reason\n    if (this.path.isUnknown()) {\n      await this.path.lstat()\n    }\n    await new Promise((res, rej) => {\n      this.walkCB(this.path, this.patterns, () => {\n        if (this.signal?.aborted) {\n          rej(this.signal.reason)\n        } else {\n          res(this.matches)\n        }\n      })\n    })\n    return this.matches\n  }\n\n  walkSync(): Set> {\n    if (this.signal?.aborted) throw this.signal.reason\n    if (this.path.isUnknown()) {\n      this.path.lstatSync()\n    }\n    // nothing for the callback to do, because this never pauses\n    this.walkCBSync(this.path, this.patterns, () => {\n      if (this.signal?.aborted) throw this.signal.reason\n    })\n    return this.matches\n  }\n}\n\nexport class GlobStream<\n  O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil {\n  results: Minipass, Result>\n\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    super(patterns, path, opts)\n    this.results = new Minipass, Result>({\n      signal: this.signal,\n      objectMode: true,\n    })\n    this.results.on('drain', () => this.resume())\n    this.results.on('resume', () => this.resume())\n  }\n\n  matchEmit(e: Result): void {\n    this.results.write(e)\n    if (!this.results.flowing) this.pause()\n  }\n\n  stream(): MatchStream {\n    const target = this.path\n    if (target.isUnknown()) {\n      target.lstat().then(() => {\n        this.walkCB(target, this.patterns, () => this.results.end())\n      })\n    } else {\n      this.walkCB(target, this.patterns, () => this.results.end())\n    }\n    return this.results\n  }\n\n  streamSync(): MatchStream {\n    if (this.path.isUnknown()) {\n      this.path.lstatSync()\n    }\n    this.walkCBSync(this.path, this.patterns, () => this.results.end())\n    return this.results\n  }\n}\n"]}PK~\<=###glob/dist/commonjs/pattern.d.ts.mapnu[{"version":3,"file":"pattern.d.ts","sourceRoot":"","sources":["../../src/pattern.ts"],"names":[],"mappings":";AAEA,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AACpC,MAAM,MAAM,SAAS,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,QAAQ,CAAA;AAGzD,MAAM,MAAM,WAAW,GAAG,CAAC,CAAC,EAAE,SAAS,EAAE,GAAG,IAAI,EAAE,SAAS,EAAE,CAAC,CAAA;AAC9D,MAAM,MAAM,cAAc,GAAG;IAC3B,EAAE,EAAE,EAAE;IACN,EAAE,EAAE,EAAE;IACN,EAAE,EAAE,MAAM;IACV,EAAE,EAAE,MAAM;IACV,GAAG,IAAI,EAAE,SAAS,EAAE;CACrB,CAAA;AACD,MAAM,MAAM,gBAAgB,GAAG,CAAC,EAAE,EAAE,MAAM,EAAE,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M,CAAC,GAAG,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,CAAA;QAC9B,OAAO,CACH,OAAO,CAAC,KAAK,QAAQ,IAAI,IAAI,CAAC,UAAU,EAAE,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,CAChE,CAAC,CAAC;YACD,CAAC;YACH,CAAC,CAAC,EAAE,CAAA;IACR,CAAC;IAED;;;OAGG;IACH,mBAAmB;QACjB,OAAO,CAAC,CACN,IAAI,CAAC,MAAM,KAAK,CAAC;YACjB,CAAC,IAAI,CAAC,UAAU,EAAE;YAClB,CAAC,IAAI,CAAC,eAAe,CACtB,CAAA;IACH,CAAC;IAED;;OAEG;IACH,kBAAkB;QAChB,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,IAAI,CAAC,eAAe;YAClE,OAAO,KAAK,CAAA;QACd,IAAI,CAAC,eAAe,GAAG,KAAK,CAAA;QAC5B,OAAO,IAAI,CAAA;IACb,CAAC;CACF;AArOD,0BAqOC","sourcesContent":["// this is just a very light wrapper around 2 arrays with an offset index\n\nimport { GLOBSTAR } from 'minimatch'\nexport type MMPattern = string | RegExp | typeof GLOBSTAR\n\n// an array of length >= 1\nexport type PatternList = [p: MMPattern, ...rest: MMPattern[]]\nexport type UNCPatternList = [\n  p0: '',\n  p1: '',\n  p2: string,\n  p3: string,\n  ...rest: MMPattern[],\n]\nexport type DrivePatternList = [p0: string, ...rest: MMPattern[]]\nexport type AbsolutePatternList = [p0: '', ...rest: MMPattern[]]\nexport type GlobList = [p: string, ...rest: string[]]\n\nconst isPatternList = (pl: MMPattern[]): pl is PatternList =>\n  pl.length >= 1\nconst isGlobList = (gl: string[]): gl is GlobList => gl.length >= 1\n\n/**\n * An immutable-ish view on an array of glob parts and their parsed\n * results\n */\nexport class Pattern {\n  readonly #patternList: PatternList\n  readonly #globList: GlobList\n  readonly #index: number\n  readonly length: number\n  readonly #platform: NodeJS.Platform\n  #rest?: Pattern | null\n  #globString?: string\n  #isDrive?: boolean\n  #isUNC?: boolean\n  #isAbsolute?: boolean\n  #followGlobstar: boolean = true\n\n  constructor(\n    patternList: MMPattern[],\n    globList: string[],\n    index: number,\n    platform: NodeJS.Platform,\n  ) {\n    if (!isPatternList(patternList)) {\n      throw new TypeError('empty pattern list')\n    }\n    if (!isGlobList(globList)) {\n      throw new TypeError('empty glob list')\n    }\n    if (globList.length !== patternList.length) {\n      throw new TypeError('mismatched pattern list and glob list lengths')\n    }\n    this.length = patternList.length\n    if (index < 0 || index >= this.length) {\n      throw new TypeError('index out of range')\n    }\n    this.#patternList = patternList\n    this.#globList = globList\n    this.#index = index\n    this.#platform = platform\n\n    // normalize root entries of absolute patterns on initial creation.\n    if (this.#index === 0) {\n      // c: => ['c:/']\n      // C:/ => ['C:/']\n      // C:/x => ['C:/', 'x']\n      // //host/share => ['//host/share/']\n      // //host/share/ => ['//host/share/']\n      // //host/share/x => ['//host/share/', 'x']\n      // /etc => ['/', 'etc']\n      // / => ['/']\n      if (this.isUNC()) {\n        // '' / '' / 'host' / 'share'\n        const [p0, p1, p2, p3, ...prest] = this.#patternList\n        const [g0, g1, g2, g3, ...grest] = this.#globList\n        if (prest[0] === '') {\n          // ends in /\n          prest.shift()\n          grest.shift()\n        }\n        const p = [p0, p1, p2, p3, ''].join('/')\n        const g = [g0, g1, g2, g3, ''].join('/')\n        this.#patternList = [p, ...prest]\n        this.#globList = [g, ...grest]\n        this.length = this.#patternList.length\n      } else if (this.isDrive() || this.isAbsolute()) {\n        const [p1, ...prest] = this.#patternList\n        const [g1, ...grest] = this.#globList\n        if (prest[0] === '') {\n          // ends in /\n          prest.shift()\n          grest.shift()\n        }\n        const p = (p1 as string) + '/'\n        const g = g1 + '/'\n        this.#patternList = [p, ...prest]\n        this.#globList = [g, ...grest]\n        this.length = this.#patternList.length\n      }\n    }\n  }\n\n  /**\n   * The first entry in the parsed list of patterns\n   */\n  pattern(): MMPattern {\n    return this.#patternList[this.#index] as MMPattern\n  }\n\n  /**\n   * true of if pattern() returns a string\n   */\n  isString(): boolean {\n    return typeof this.#patternList[this.#index] === 'string'\n  }\n  /**\n   * true of if pattern() returns GLOBSTAR\n   */\n  isGlobstar(): boolean {\n    return this.#patternList[this.#index] === GLOBSTAR\n  }\n  /**\n   * true if pattern() returns a regexp\n   */\n  isRegExp(): boolean {\n    return this.#patternList[this.#index] instanceof RegExp\n  }\n\n  /**\n   * The /-joined set of glob parts that make up this pattern\n   */\n  globString(): string {\n    return (this.#globString =\n      this.#globString ||\n      (this.#index === 0 ?\n        this.isAbsolute() ?\n          this.#globList[0] + this.#globList.slice(1).join('/')\n        : this.#globList.join('/')\n      : this.#globList.slice(this.#index).join('/')))\n  }\n\n  /**\n   * true if there are more pattern parts after this one\n   */\n  hasMore(): boolean {\n    return this.length > this.#index + 1\n  }\n\n  /**\n   * The rest of the pattern after this part, or null if this is the end\n   */\n  rest(): Pattern | null {\n    if (this.#rest !== undefined) return this.#rest\n    if (!this.hasMore()) return (this.#rest = null)\n    this.#rest = new Pattern(\n      this.#patternList,\n      this.#globList,\n      this.#index + 1,\n      this.#platform,\n    )\n    this.#rest.#isAbsolute = this.#isAbsolute\n    this.#rest.#isUNC = this.#isUNC\n    this.#rest.#isDrive = this.#isDrive\n    return this.#rest\n  }\n\n  /**\n   * true if the pattern represents a //unc/path/ on windows\n   */\n  isUNC(): boolean {\n    const pl = this.#patternList\n    return this.#isUNC !== undefined ?\n        this.#isUNC\n      : (this.#isUNC =\n          this.#platform === 'win32' &&\n          this.#index === 0 &&\n          pl[0] === '' &&\n          pl[1] === '' &&\n          typeof pl[2] === 'string' &&\n          !!pl[2] &&\n          typeof pl[3] === 'string' &&\n          !!pl[3])\n  }\n\n  // pattern like C:/...\n  // split = ['C:', ...]\n  // XXX: would be nice to handle patterns like `c:*` to test the cwd\n  // in c: for *, but I don't know of a way to even figure out what that\n  // cwd is without actually chdir'ing into it?\n  /**\n   * True if the pattern starts with a drive letter on Windows\n   */\n  isDrive(): boolean {\n    const pl = this.#patternList\n    return this.#isDrive !== undefined ?\n        this.#isDrive\n      : (this.#isDrive =\n          this.#platform === 'win32' &&\n          this.#index === 0 &&\n          this.length > 1 &&\n          typeof pl[0] === 'string' &&\n          /^[a-z]:$/i.test(pl[0]))\n  }\n\n  // pattern = '/' or '/...' or '/x/...'\n  // split = ['', ''] or ['', ...] or ['', 'x', ...]\n  // Drive and UNC both considered absolute on windows\n  /**\n   * True if the pattern is rooted on an absolute path\n   */\n  isAbsolute(): boolean {\n    const pl = this.#patternList\n    return this.#isAbsolute !== undefined ?\n        this.#isAbsolute\n      : (this.#isAbsolute =\n          (pl[0] === '' && pl.length > 1) ||\n          this.isDrive() ||\n          this.isUNC())\n  }\n\n  /**\n   * consume the root of the pattern, and return it\n   */\n  root(): string {\n    const p = this.#patternList[0]\n    return (\n        typeof p === 'string' && this.isAbsolute() && this.#index === 0\n      ) ?\n        p\n      : ''\n  }\n\n  /**\n   * Check to see if the current globstar pattern is allowed to follow\n   * a symbolic link.\n   */\n  checkFollowGlobstar(): boolean {\n    return !(\n      this.#index === 0 ||\n      !this.isGlobstar() ||\n      !this.#followGlobstar\n    )\n  }\n\n  /**\n   * Mark that the current globstar pattern is following a symbolic link\n   */\n  markFollowGlobstar(): boolean {\n    if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar)\n      return false\n    this.#followGlobstar = false\n    return true\n  }\n}\n"]}PK~\	=%glob/dist/commonjs/has-magic.d.ts.mapnu[{"version":3,"file":"has-magic.d.ts","sourceRoot":"","sources":["../../src/has-magic.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AAEvC;;;;;;;;;;GAUG;AACH,eAAO,MAAM,QAAQ,YACV,MAAM,GAAG,MAAM,EAAE,YACjB,WAAW,KACnB,OAQF,CAAA"}PK~\%**glob/dist/commonjs/processor.jsnu["use strict";
// synchronous utility for filtering entries and calculating subwalks
Object.defineProperty(exports, "__esModule", { value: true });
exports.Processor = exports.SubWalks = exports.MatchRecord = exports.HasWalkedCache = void 0;
const minimatch_1 = require("minimatch");
/**
 * A cache of which patterns have been processed for a given Path
 */
class HasWalkedCache {
    store;
    constructor(store = new Map()) {
        this.store = store;
    }
    copy() {
        return new HasWalkedCache(new Map(this.store));
    }
    hasWalked(target, pattern) {
        return this.store.get(target.fullpath())?.has(pattern.globString());
    }
    storeWalked(target, pattern) {
        const fullpath = target.fullpath();
        const cached = this.store.get(fullpath);
        if (cached)
            cached.add(pattern.globString());
        else
            this.store.set(fullpath, new Set([pattern.globString()]));
    }
}
exports.HasWalkedCache = HasWalkedCache;
/**
 * A record of which paths have been matched in a given walk step,
 * and whether they only are considered a match if they are a directory,
 * and whether their absolute or relative path should be returned.
 */
class MatchRecord {
    store = new Map();
    add(target, absolute, ifDir) {
        const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0);
        const current = this.store.get(target);
        this.store.set(target, current === undefined ? n : n & current);
    }
    // match, absolute, ifdir
    entries() {
        return [...this.store.entries()].map(([path, n]) => [
            path,
            !!(n & 2),
            !!(n & 1),
        ]);
    }
}
exports.MatchRecord = MatchRecord;
/**
 * A collection of patterns that must be processed in a subsequent step
 * for a given path.
 */
class SubWalks {
    store = new Map();
    add(target, pattern) {
        if (!target.canReaddir()) {
            return;
        }
        const subs = this.store.get(target);
        if (subs) {
            if (!subs.find(p => p.globString() === pattern.globString())) {
                subs.push(pattern);
            }
        }
        else
            this.store.set(target, [pattern]);
    }
    get(target) {
        const subs = this.store.get(target);
        /* c8 ignore start */
        if (!subs) {
            throw new Error('attempting to walk unknown path');
        }
        /* c8 ignore stop */
        return subs;
    }
    entries() {
        return this.keys().map(k => [k, this.store.get(k)]);
    }
    keys() {
        return [...this.store.keys()].filter(t => t.canReaddir());
    }
}
exports.SubWalks = SubWalks;
/**
 * The class that processes patterns for a given path.
 *
 * Handles child entry filtering, and determining whether a path's
 * directory contents must be read.
 */
class Processor {
    hasWalkedCache;
    matches = new MatchRecord();
    subwalks = new SubWalks();
    patterns;
    follow;
    dot;
    opts;
    constructor(opts, hasWalkedCache) {
        this.opts = opts;
        this.follow = !!opts.follow;
        this.dot = !!opts.dot;
        this.hasWalkedCache =
            hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache();
    }
    processPatterns(target, patterns) {
        this.patterns = patterns;
        const processingSet = patterns.map(p => [target, p]);
        // map of paths to the magic-starting subwalks they need to walk
        // first item in patterns is the filter
        for (let [t, pattern] of processingSet) {
            this.hasWalkedCache.storeWalked(t, pattern);
            const root = pattern.root();
            const absolute = pattern.isAbsolute() && this.opts.absolute !== false;
            // start absolute patterns at root
            if (root) {
                t = t.resolve(root === '/' && this.opts.root !== undefined ?
                    this.opts.root
                    : root);
                const rest = pattern.rest();
                if (!rest) {
                    this.matches.add(t, true, false);
                    continue;
                }
                else {
                    pattern = rest;
                }
            }
            if (t.isENOENT())
                continue;
            let p;
            let rest;
            let changed = false;
            while (typeof (p = pattern.pattern()) === 'string' &&
                (rest = pattern.rest())) {
                const c = t.resolve(p);
                t = c;
                pattern = rest;
                changed = true;
            }
            p = pattern.pattern();
            rest = pattern.rest();
            if (changed) {
                if (this.hasWalkedCache.hasWalked(t, pattern))
                    continue;
                this.hasWalkedCache.storeWalked(t, pattern);
            }
            // now we have either a final string for a known entry,
            // more strings for an unknown entry,
            // or a pattern starting with magic, mounted on t.
            if (typeof p === 'string') {
                // must not be final entry, otherwise we would have
                // concatenated it earlier.
                const ifDir = p === '..' || p === '' || p === '.';
                this.matches.add(t.resolve(p), absolute, ifDir);
                continue;
            }
            else if (p === minimatch_1.GLOBSTAR) {
                // if no rest, match and subwalk pattern
                // if rest, process rest and subwalk pattern
                // if it's a symlink, but we didn't get here by way of a
                // globstar match (meaning it's the first time THIS globstar
                // has traversed a symlink), then we follow it. Otherwise, stop.
                if (!t.isSymbolicLink() ||
                    this.follow ||
                    pattern.checkFollowGlobstar()) {
                    this.subwalks.add(t, pattern);
                }
                const rp = rest?.pattern();
                const rrest = rest?.rest();
                if (!rest || ((rp === '' || rp === '.') && !rrest)) {
                    // only HAS to be a dir if it ends in **/ or **/.
                    // but ending in ** will match files as well.
                    this.matches.add(t, absolute, rp === '' || rp === '.');
                }
                else {
                    if (rp === '..') {
                        // this would mean you're matching **/.. at the fs root,
                        // and no thanks, I'm not gonna test that specific case.
                        /* c8 ignore start */
                        const tp = t.parent || t;
                        /* c8 ignore stop */
                        if (!rrest)
                            this.matches.add(tp, absolute, true);
                        else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {
                            this.subwalks.add(tp, rrest);
                        }
                    }
                }
            }
            else if (p instanceof RegExp) {
                this.subwalks.add(t, pattern);
            }
        }
        return this;
    }
    subwalkTargets() {
        return this.subwalks.keys();
    }
    child() {
        return new Processor(this.opts, this.hasWalkedCache);
    }
    // return a new Processor containing the subwalks for each
    // child entry, and a set of matches, and
    // a hasWalkedCache that's a copy of this one
    // then we're going to call
    filterEntries(parent, entries) {
        const patterns = this.subwalks.get(parent);
        // put matches and entry walks into the results processor
        const results = this.child();
        for (const e of entries) {
            for (const pattern of patterns) {
                const absolute = pattern.isAbsolute();
                const p = pattern.pattern();
                const rest = pattern.rest();
                if (p === minimatch_1.GLOBSTAR) {
                    results.testGlobstar(e, pattern, rest, absolute);
                }
                else if (p instanceof RegExp) {
                    results.testRegExp(e, p, rest, absolute);
                }
                else {
                    results.testString(e, p, rest, absolute);
                }
            }
        }
        return results;
    }
    testGlobstar(e, pattern, rest, absolute) {
        if (this.dot || !e.name.startsWith('.')) {
            if (!pattern.hasMore()) {
                this.matches.add(e, absolute, false);
            }
            if (e.canReaddir()) {
                // if we're in follow mode or it's not a symlink, just keep
                // testing the same pattern. If there's more after the globstar,
                // then this symlink consumes the globstar. If not, then we can
                // follow at most ONE symlink along the way, so we mark it, which
                // also checks to ensure that it wasn't already marked.
                if (this.follow || !e.isSymbolicLink()) {
                    this.subwalks.add(e, pattern);
                }
                else if (e.isSymbolicLink()) {
                    if (rest && pattern.checkFollowGlobstar()) {
                        this.subwalks.add(e, rest);
                    }
                    else if (pattern.markFollowGlobstar()) {
                        this.subwalks.add(e, pattern);
                    }
                }
            }
        }
        // if the NEXT thing matches this entry, then also add
        // the rest.
        if (rest) {
            const rp = rest.pattern();
            if (typeof rp === 'string' &&
                // dots and empty were handled already
                rp !== '..' &&
                rp !== '' &&
                rp !== '.') {
                this.testString(e, rp, rest.rest(), absolute);
            }
            else if (rp === '..') {
                /* c8 ignore start */
                const ep = e.parent || e;
                /* c8 ignore stop */
                this.subwalks.add(ep, rest);
            }
            else if (rp instanceof RegExp) {
                this.testRegExp(e, rp, rest.rest(), absolute);
            }
        }
    }
    testRegExp(e, p, rest, absolute) {
        if (!p.test(e.name))
            return;
        if (!rest) {
            this.matches.add(e, absolute, false);
        }
        else {
            this.subwalks.add(e, rest);
        }
    }
    testString(e, p, rest, absolute) {
        // should never happen?
        if (!e.isNamed(p))
            return;
        if (!rest) {
            this.matches.add(e, absolute, false);
        }
        else {
            this.subwalks.add(e, rest);
        }
    }
}
exports.Processor = Processor;
//# sourceMappingURL=processor.js.mapPK~\Kb!b!glob/dist/commonjs/glob.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Glob = void 0;
const minimatch_1 = require("minimatch");
const node_url_1 = require("node:url");
const path_scurry_1 = require("path-scurry");
const pattern_js_1 = require("./pattern.js");
const walker_js_1 = require("./walker.js");
// if no process global, just call it linux.
// so we default to case-sensitive, / separators
const defaultPlatform = (typeof process === 'object' &&
    process &&
    typeof process.platform === 'string') ?
    process.platform
    : 'linux';
/**
 * An object that can perform glob pattern traversals.
 */
class Glob {
    absolute;
    cwd;
    root;
    dot;
    dotRelative;
    follow;
    ignore;
    magicalBraces;
    mark;
    matchBase;
    maxDepth;
    nobrace;
    nocase;
    nodir;
    noext;
    noglobstar;
    pattern;
    platform;
    realpath;
    scurry;
    stat;
    signal;
    windowsPathsNoEscape;
    withFileTypes;
    includeChildMatches;
    /**
     * The options provided to the constructor.
     */
    opts;
    /**
     * An array of parsed immutable {@link Pattern} objects.
     */
    patterns;
    /**
     * All options are stored as properties on the `Glob` object.
     *
     * See {@link GlobOptions} for full options descriptions.
     *
     * Note that a previous `Glob` object can be passed as the
     * `GlobOptions` to another `Glob` instantiation to re-use settings
     * and caches with a new pattern.
     *
     * Traversal functions can be called multiple times to run the walk
     * again.
     */
    constructor(pattern, opts) {
        /* c8 ignore start */
        if (!opts)
            throw new TypeError('glob options required');
        /* c8 ignore stop */
        this.withFileTypes = !!opts.withFileTypes;
        this.signal = opts.signal;
        this.follow = !!opts.follow;
        this.dot = !!opts.dot;
        this.dotRelative = !!opts.dotRelative;
        this.nodir = !!opts.nodir;
        this.mark = !!opts.mark;
        if (!opts.cwd) {
            this.cwd = '';
        }
        else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) {
            opts.cwd = (0, node_url_1.fileURLToPath)(opts.cwd);
        }
        this.cwd = opts.cwd || '';
        this.root = opts.root;
        this.magicalBraces = !!opts.magicalBraces;
        this.nobrace = !!opts.nobrace;
        this.noext = !!opts.noext;
        this.realpath = !!opts.realpath;
        this.absolute = opts.absolute;
        this.includeChildMatches = opts.includeChildMatches !== false;
        this.noglobstar = !!opts.noglobstar;
        this.matchBase = !!opts.matchBase;
        this.maxDepth =
            typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity;
        this.stat = !!opts.stat;
        this.ignore = opts.ignore;
        if (this.withFileTypes && this.absolute !== undefined) {
            throw new Error('cannot set absolute and withFileTypes:true');
        }
        if (typeof pattern === 'string') {
            pattern = [pattern];
        }
        this.windowsPathsNoEscape =
            !!opts.windowsPathsNoEscape ||
                opts.allowWindowsEscape ===
                    false;
        if (this.windowsPathsNoEscape) {
            pattern = pattern.map(p => p.replace(/\\/g, '/'));
        }
        if (this.matchBase) {
            if (opts.noglobstar) {
                throw new TypeError('base matching requires globstar');
            }
            pattern = pattern.map(p => (p.includes('/') ? p : `./**/${p}`));
        }
        this.pattern = pattern;
        this.platform = opts.platform || defaultPlatform;
        this.opts = { ...opts, platform: this.platform };
        if (opts.scurry) {
            this.scurry = opts.scurry;
            if (opts.nocase !== undefined &&
                opts.nocase !== opts.scurry.nocase) {
                throw new Error('nocase option contradicts provided scurry option');
            }
        }
        else {
            const Scurry = opts.platform === 'win32' ? path_scurry_1.PathScurryWin32
                : opts.platform === 'darwin' ? path_scurry_1.PathScurryDarwin
                    : opts.platform ? path_scurry_1.PathScurryPosix
                        : path_scurry_1.PathScurry;
            this.scurry = new Scurry(this.cwd, {
                nocase: opts.nocase,
                fs: opts.fs,
            });
        }
        this.nocase = this.scurry.nocase;
        // If you do nocase:true on a case-sensitive file system, then
        // we need to use regexps instead of strings for non-magic
        // path portions, because statting `aBc` won't return results
        // for the file `AbC` for example.
        const nocaseMagicOnly = this.platform === 'darwin' || this.platform === 'win32';
        const mmo = {
            // default nocase based on platform
            ...opts,
            dot: this.dot,
            matchBase: this.matchBase,
            nobrace: this.nobrace,
            nocase: this.nocase,
            nocaseMagicOnly,
            nocomment: true,
            noext: this.noext,
            nonegate: true,
            optimizationLevel: 2,
            platform: this.platform,
            windowsPathsNoEscape: this.windowsPathsNoEscape,
            debug: !!this.opts.debug,
        };
        const mms = this.pattern.map(p => new minimatch_1.Minimatch(p, mmo));
        const [matchSet, globParts] = mms.reduce((set, m) => {
            set[0].push(...m.set);
            set[1].push(...m.globParts);
            return set;
        }, [[], []]);
        this.patterns = matchSet.map((set, i) => {
            const g = globParts[i];
            /* c8 ignore start */
            if (!g)
                throw new Error('invalid pattern object');
            /* c8 ignore stop */
            return new pattern_js_1.Pattern(set, g, 0, this.platform);
        });
    }
    async walk() {
        // Walkers always return array of Path objects, so we just have to
        // coerce them into the right shape.  It will have already called
        // realpath() if the option was set to do so, so we know that's cached.
        // start out knowing the cwd, at least
        return [
            ...(await new walker_js_1.GlobWalker(this.patterns, this.scurry.cwd, {
                ...this.opts,
                maxDepth: this.maxDepth !== Infinity ?
                    this.maxDepth + this.scurry.cwd.depth()
                    : Infinity,
                platform: this.platform,
                nocase: this.nocase,
                includeChildMatches: this.includeChildMatches,
            }).walk()),
        ];
    }
    walkSync() {
        return [
            ...new walker_js_1.GlobWalker(this.patterns, this.scurry.cwd, {
                ...this.opts,
                maxDepth: this.maxDepth !== Infinity ?
                    this.maxDepth + this.scurry.cwd.depth()
                    : Infinity,
                platform: this.platform,
                nocase: this.nocase,
                includeChildMatches: this.includeChildMatches,
            }).walkSync(),
        ];
    }
    stream() {
        return new walker_js_1.GlobStream(this.patterns, this.scurry.cwd, {
            ...this.opts,
            maxDepth: this.maxDepth !== Infinity ?
                this.maxDepth + this.scurry.cwd.depth()
                : Infinity,
            platform: this.platform,
            nocase: this.nocase,
            includeChildMatches: this.includeChildMatches,
        }).stream();
    }
    streamSync() {
        return new walker_js_1.GlobStream(this.patterns, this.scurry.cwd, {
            ...this.opts,
            maxDepth: this.maxDepth !== Infinity ?
                this.maxDepth + this.scurry.cwd.depth()
                : Infinity,
            platform: this.platform,
            nocase: this.nocase,
            includeChildMatches: this.includeChildMatches,
        }).streamSync();
    }
    /**
     * Default sync iteration function. Returns a Generator that
     * iterates over the results.
     */
    iterateSync() {
        return this.streamSync()[Symbol.iterator]();
    }
    [Symbol.iterator]() {
        return this.iterateSync();
    }
    /**
     * Default async iteration function. Returns an AsyncGenerator that
     * iterates over the results.
     */
    iterate() {
        return this.stream()[Symbol.asyncIterator]();
    }
    [Symbol.asyncIterator]() {
        return this.iterate();
    }
}
exports.Glob = Glob;
//# sourceMappingURL=glob.js.mapPK~\ebglob/dist/commonjs/index.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.glob = exports.sync = exports.iterate = exports.iterateSync = exports.stream = exports.streamSync = exports.globIterate = exports.globIterateSync = exports.globSync = exports.globStream = exports.globStreamSync = exports.Ignore = exports.hasMagic = exports.Glob = exports.unescape = exports.escape = void 0;
const minimatch_1 = require("minimatch");
const glob_js_1 = require("./glob.js");
const has_magic_js_1 = require("./has-magic.js");
var minimatch_2 = require("minimatch");
Object.defineProperty(exports, "escape", { enumerable: true, get: function () { return minimatch_2.escape; } });
Object.defineProperty(exports, "unescape", { enumerable: true, get: function () { return minimatch_2.unescape; } });
var glob_js_2 = require("./glob.js");
Object.defineProperty(exports, "Glob", { enumerable: true, get: function () { return glob_js_2.Glob; } });
var has_magic_js_2 = require("./has-magic.js");
Object.defineProperty(exports, "hasMagic", { enumerable: true, get: function () { return has_magic_js_2.hasMagic; } });
var ignore_js_1 = require("./ignore.js");
Object.defineProperty(exports, "Ignore", { enumerable: true, get: function () { return ignore_js_1.Ignore; } });
function globStreamSync(pattern, options = {}) {
    return new glob_js_1.Glob(pattern, options).streamSync();
}
exports.globStreamSync = globStreamSync;
function globStream(pattern, options = {}) {
    return new glob_js_1.Glob(pattern, options).stream();
}
exports.globStream = globStream;
function globSync(pattern, options = {}) {
    return new glob_js_1.Glob(pattern, options).walkSync();
}
exports.globSync = globSync;
async function glob_(pattern, options = {}) {
    return new glob_js_1.Glob(pattern, options).walk();
}
function globIterateSync(pattern, options = {}) {
    return new glob_js_1.Glob(pattern, options).iterateSync();
}
exports.globIterateSync = globIterateSync;
function globIterate(pattern, options = {}) {
    return new glob_js_1.Glob(pattern, options).iterate();
}
exports.globIterate = globIterate;
// aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc
exports.streamSync = globStreamSync;
exports.stream = Object.assign(globStream, { sync: globStreamSync });
exports.iterateSync = globIterateSync;
exports.iterate = Object.assign(globIterate, {
    sync: globIterateSync,
});
exports.sync = Object.assign(globSync, {
    stream: globStreamSync,
    iterate: globIterateSync,
});
exports.glob = Object.assign(glob_, {
    glob: glob_,
    globSync,
    sync: exports.sync,
    globStream,
    stream: exports.stream,
    globStreamSync,
    streamSync: exports.streamSync,
    globIterate,
    iterate: exports.iterate,
    globIterateSync,
    iterateSync: exports.iterateSync,
    Glob: glob_js_1.Glob,
    hasMagic: has_magic_js_1.hasMagic,
    escape: minimatch_1.escape,
    unescape: minimatch_1.unescape,
});
exports.glob.glob = exports.glob;
//# sourceMappingURL=index.js.mapPK~\JXE2E2glob/dist/commonjs/walker.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GlobStream = exports.GlobWalker = exports.GlobUtil = void 0;
/**
 * Single-use utility classes to provide functionality to the {@link Glob}
 * methods.
 *
 * @module
 */
const minipass_1 = require("minipass");
const ignore_js_1 = require("./ignore.js");
const processor_js_1 = require("./processor.js");
const makeIgnore = (ignore, opts) => typeof ignore === 'string' ? new ignore_js_1.Ignore([ignore], opts)
    : Array.isArray(ignore) ? new ignore_js_1.Ignore(ignore, opts)
        : ignore;
/**
 * basic walking utilities that all the glob walker types use
 */
class GlobUtil {
    path;
    patterns;
    opts;
    seen = new Set();
    paused = false;
    aborted = false;
    #onResume = [];
    #ignore;
    #sep;
    signal;
    maxDepth;
    includeChildMatches;
    constructor(patterns, path, opts) {
        this.patterns = patterns;
        this.path = path;
        this.opts = opts;
        this.#sep = !opts.posix && opts.platform === 'win32' ? '\\' : '/';
        this.includeChildMatches = opts.includeChildMatches !== false;
        if (opts.ignore || !this.includeChildMatches) {
            this.#ignore = makeIgnore(opts.ignore ?? [], opts);
            if (!this.includeChildMatches &&
                typeof this.#ignore.add !== 'function') {
                const m = 'cannot ignore child matches, ignore lacks add() method.';
                throw new Error(m);
            }
        }
        // ignore, always set with maxDepth, but it's optional on the
        // GlobOptions type
        /* c8 ignore start */
        this.maxDepth = opts.maxDepth || Infinity;
        /* c8 ignore stop */
        if (opts.signal) {
            this.signal = opts.signal;
            this.signal.addEventListener('abort', () => {
                this.#onResume.length = 0;
            });
        }
    }
    #ignored(path) {
        return this.seen.has(path) || !!this.#ignore?.ignored?.(path);
    }
    #childrenIgnored(path) {
        return !!this.#ignore?.childrenIgnored?.(path);
    }
    // backpressure mechanism
    pause() {
        this.paused = true;
    }
    resume() {
        /* c8 ignore start */
        if (this.signal?.aborted)
            return;
        /* c8 ignore stop */
        this.paused = false;
        let fn = undefined;
        while (!this.paused && (fn = this.#onResume.shift())) {
            fn();
        }
    }
    onResume(fn) {
        if (this.signal?.aborted)
            return;
        /* c8 ignore start */
        if (!this.paused) {
            fn();
        }
        else {
            /* c8 ignore stop */
            this.#onResume.push(fn);
        }
    }
    // do the requisite realpath/stat checking, and return the path
    // to add or undefined to filter it out.
    async matchCheck(e, ifDir) {
        if (ifDir && this.opts.nodir)
            return undefined;
        let rpc;
        if (this.opts.realpath) {
            rpc = e.realpathCached() || (await e.realpath());
            if (!rpc)
                return undefined;
            e = rpc;
        }
        const needStat = e.isUnknown() || this.opts.stat;
        const s = needStat ? await e.lstat() : e;
        if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {
            const target = await s.realpath();
            /* c8 ignore start */
            if (target && (target.isUnknown() || this.opts.stat)) {
                await target.lstat();
            }
            /* c8 ignore stop */
        }
        return this.matchCheckTest(s, ifDir);
    }
    matchCheckTest(e, ifDir) {
        return (e &&
            (this.maxDepth === Infinity || e.depth() <= this.maxDepth) &&
            (!ifDir || e.canReaddir()) &&
            (!this.opts.nodir || !e.isDirectory()) &&
            (!this.opts.nodir ||
                !this.opts.follow ||
                !e.isSymbolicLink() ||
                !e.realpathCached()?.isDirectory()) &&
            !this.#ignored(e)) ?
            e
            : undefined;
    }
    matchCheckSync(e, ifDir) {
        if (ifDir && this.opts.nodir)
            return undefined;
        let rpc;
        if (this.opts.realpath) {
            rpc = e.realpathCached() || e.realpathSync();
            if (!rpc)
                return undefined;
            e = rpc;
        }
        const needStat = e.isUnknown() || this.opts.stat;
        const s = needStat ? e.lstatSync() : e;
        if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {
            const target = s.realpathSync();
            if (target && (target?.isUnknown() || this.opts.stat)) {
                target.lstatSync();
            }
        }
        return this.matchCheckTest(s, ifDir);
    }
    matchFinish(e, absolute) {
        if (this.#ignored(e))
            return;
        // we know we have an ignore if this is false, but TS doesn't
        if (!this.includeChildMatches && this.#ignore?.add) {
            const ign = `${e.relativePosix()}/**`;
            this.#ignore.add(ign);
        }
        const abs = this.opts.absolute === undefined ? absolute : this.opts.absolute;
        this.seen.add(e);
        const mark = this.opts.mark && e.isDirectory() ? this.#sep : '';
        // ok, we have what we need!
        if (this.opts.withFileTypes) {
            this.matchEmit(e);
        }
        else if (abs) {
            const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath();
            this.matchEmit(abs + mark);
        }
        else {
            const rel = this.opts.posix ? e.relativePosix() : e.relative();
            const pre = this.opts.dotRelative && !rel.startsWith('..' + this.#sep) ?
                '.' + this.#sep
                : '';
            this.matchEmit(!rel ? '.' + mark : pre + rel + mark);
        }
    }
    async match(e, absolute, ifDir) {
        const p = await this.matchCheck(e, ifDir);
        if (p)
            this.matchFinish(p, absolute);
    }
    matchSync(e, absolute, ifDir) {
        const p = this.matchCheckSync(e, ifDir);
        if (p)
            this.matchFinish(p, absolute);
    }
    walkCB(target, patterns, cb) {
        /* c8 ignore start */
        if (this.signal?.aborted)
            cb();
        /* c8 ignore stop */
        this.walkCB2(target, patterns, new processor_js_1.Processor(this.opts), cb);
    }
    walkCB2(target, patterns, processor, cb) {
        if (this.#childrenIgnored(target))
            return cb();
        if (this.signal?.aborted)
            cb();
        if (this.paused) {
            this.onResume(() => this.walkCB2(target, patterns, processor, cb));
            return;
        }
        processor.processPatterns(target, patterns);
        // done processing.  all of the above is sync, can be abstracted out.
        // subwalks is a map of paths to the entry filters they need
        // matches is a map of paths to [absolute, ifDir] tuples.
        let tasks = 1;
        const next = () => {
            if (--tasks === 0)
                cb();
        };
        for (const [m, absolute, ifDir] of processor.matches.entries()) {
            if (this.#ignored(m))
                continue;
            tasks++;
            this.match(m, absolute, ifDir).then(() => next());
        }
        for (const t of processor.subwalkTargets()) {
            if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {
                continue;
            }
            tasks++;
            const childrenCached = t.readdirCached();
            if (t.calledReaddir())
                this.walkCB3(t, childrenCached, processor, next);
            else {
                t.readdirCB((_, entries) => this.walkCB3(t, entries, processor, next), true);
            }
        }
        next();
    }
    walkCB3(target, entries, processor, cb) {
        processor = processor.filterEntries(target, entries);
        let tasks = 1;
        const next = () => {
            if (--tasks === 0)
                cb();
        };
        for (const [m, absolute, ifDir] of processor.matches.entries()) {
            if (this.#ignored(m))
                continue;
            tasks++;
            this.match(m, absolute, ifDir).then(() => next());
        }
        for (const [target, patterns] of processor.subwalks.entries()) {
            tasks++;
            this.walkCB2(target, patterns, processor.child(), next);
        }
        next();
    }
    walkCBSync(target, patterns, cb) {
        /* c8 ignore start */
        if (this.signal?.aborted)
            cb();
        /* c8 ignore stop */
        this.walkCB2Sync(target, patterns, new processor_js_1.Processor(this.opts), cb);
    }
    walkCB2Sync(target, patterns, processor, cb) {
        if (this.#childrenIgnored(target))
            return cb();
        if (this.signal?.aborted)
            cb();
        if (this.paused) {
            this.onResume(() => this.walkCB2Sync(target, patterns, processor, cb));
            return;
        }
        processor.processPatterns(target, patterns);
        // done processing.  all of the above is sync, can be abstracted out.
        // subwalks is a map of paths to the entry filters they need
        // matches is a map of paths to [absolute, ifDir] tuples.
        let tasks = 1;
        const next = () => {
            if (--tasks === 0)
                cb();
        };
        for (const [m, absolute, ifDir] of processor.matches.entries()) {
            if (this.#ignored(m))
                continue;
            this.matchSync(m, absolute, ifDir);
        }
        for (const t of processor.subwalkTargets()) {
            if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {
                continue;
            }
            tasks++;
            const children = t.readdirSync();
            this.walkCB3Sync(t, children, processor, next);
        }
        next();
    }
    walkCB3Sync(target, entries, processor, cb) {
        processor = processor.filterEntries(target, entries);
        let tasks = 1;
        const next = () => {
            if (--tasks === 0)
                cb();
        };
        for (const [m, absolute, ifDir] of processor.matches.entries()) {
            if (this.#ignored(m))
                continue;
            this.matchSync(m, absolute, ifDir);
        }
        for (const [target, patterns] of processor.subwalks.entries()) {
            tasks++;
            this.walkCB2Sync(target, patterns, processor.child(), next);
        }
        next();
    }
}
exports.GlobUtil = GlobUtil;
class GlobWalker extends GlobUtil {
    matches = new Set();
    constructor(patterns, path, opts) {
        super(patterns, path, opts);
    }
    matchEmit(e) {
        this.matches.add(e);
    }
    async walk() {
        if (this.signal?.aborted)
            throw this.signal.reason;
        if (this.path.isUnknown()) {
            await this.path.lstat();
        }
        await new Promise((res, rej) => {
            this.walkCB(this.path, this.patterns, () => {
                if (this.signal?.aborted) {
                    rej(this.signal.reason);
                }
                else {
                    res(this.matches);
                }
            });
        });
        return this.matches;
    }
    walkSync() {
        if (this.signal?.aborted)
            throw this.signal.reason;
        if (this.path.isUnknown()) {
            this.path.lstatSync();
        }
        // nothing for the callback to do, because this never pauses
        this.walkCBSync(this.path, this.patterns, () => {
            if (this.signal?.aborted)
                throw this.signal.reason;
        });
        return this.matches;
    }
}
exports.GlobWalker = GlobWalker;
class GlobStream extends GlobUtil {
    results;
    constructor(patterns, path, opts) {
        super(patterns, path, opts);
        this.results = new minipass_1.Minipass({
            signal: this.signal,
            objectMode: true,
        });
        this.results.on('drain', () => this.resume());
        this.results.on('resume', () => this.resume());
    }
    matchEmit(e) {
        this.results.write(e);
        if (!this.results.flowing)
            this.pause();
    }
    stream() {
        const target = this.path;
        if (target.isUnknown()) {
            target.lstat().then(() => {
                this.walkCB(target, this.patterns, () => this.results.end());
            });
        }
        else {
            this.walkCB(target, this.patterns, () => this.results.end());
        }
        return this.results;
    }
    streamSync() {
        if (this.path.isUnknown()) {
            this.path.lstatSync();
        }
        this.walkCBSync(this.path, this.patterns, () => this.results.end());
        return this.results;
    }
}
exports.GlobStream = GlobStream;
//# sourceMappingURL=walker.js.mapPK~\a-LLglob/dist/commonjs/ignore.d.tsnu[/// 
import { Minimatch, MinimatchOptions } from 'minimatch';
import { Path } from 'path-scurry';
import { GlobWalkerOpts } from './walker.js';
export interface IgnoreLike {
    ignored?: (p: Path) => boolean;
    childrenIgnored?: (p: Path) => boolean;
    add?: (ignore: string) => void;
}
/**
 * Class used to process ignored patterns
 */
export declare class Ignore implements IgnoreLike {
    relative: Minimatch[];
    relativeChildren: Minimatch[];
    absolute: Minimatch[];
    absoluteChildren: Minimatch[];
    platform: NodeJS.Platform;
    mmopts: MinimatchOptions;
    constructor(ignored: string[], { nobrace, nocase, noext, noglobstar, platform, }: GlobWalkerOpts);
    add(ign: string): void;
    ignored(p: Path): boolean;
    childrenIgnored(p: Path): boolean;
}
//# sourceMappingURL=ignore.d.ts.mapPK~\ׄglob/dist/commonjs/pattern.jsnu["use strict";
// this is just a very light wrapper around 2 arrays with an offset index
Object.defineProperty(exports, "__esModule", { value: true });
exports.Pattern = void 0;
const minimatch_1 = require("minimatch");
const isPatternList = (pl) => pl.length >= 1;
const isGlobList = (gl) => gl.length >= 1;
/**
 * An immutable-ish view on an array of glob parts and their parsed
 * results
 */
class Pattern {
    #patternList;
    #globList;
    #index;
    length;
    #platform;
    #rest;
    #globString;
    #isDrive;
    #isUNC;
    #isAbsolute;
    #followGlobstar = true;
    constructor(patternList, globList, index, platform) {
        if (!isPatternList(patternList)) {
            throw new TypeError('empty pattern list');
        }
        if (!isGlobList(globList)) {
            throw new TypeError('empty glob list');
        }
        if (globList.length !== patternList.length) {
            throw new TypeError('mismatched pattern list and glob list lengths');
        }
        this.length = patternList.length;
        if (index < 0 || index >= this.length) {
            throw new TypeError('index out of range');
        }
        this.#patternList = patternList;
        this.#globList = globList;
        this.#index = index;
        this.#platform = platform;
        // normalize root entries of absolute patterns on initial creation.
        if (this.#index === 0) {
            // c: => ['c:/']
            // C:/ => ['C:/']
            // C:/x => ['C:/', 'x']
            // //host/share => ['//host/share/']
            // //host/share/ => ['//host/share/']
            // //host/share/x => ['//host/share/', 'x']
            // /etc => ['/', 'etc']
            // / => ['/']
            if (this.isUNC()) {
                // '' / '' / 'host' / 'share'
                const [p0, p1, p2, p3, ...prest] = this.#patternList;
                const [g0, g1, g2, g3, ...grest] = this.#globList;
                if (prest[0] === '') {
                    // ends in /
                    prest.shift();
                    grest.shift();
                }
                const p = [p0, p1, p2, p3, ''].join('/');
                const g = [g0, g1, g2, g3, ''].join('/');
                this.#patternList = [p, ...prest];
                this.#globList = [g, ...grest];
                this.length = this.#patternList.length;
            }
            else if (this.isDrive() || this.isAbsolute()) {
                const [p1, ...prest] = this.#patternList;
                const [g1, ...grest] = this.#globList;
                if (prest[0] === '') {
                    // ends in /
                    prest.shift();
                    grest.shift();
                }
                const p = p1 + '/';
                const g = g1 + '/';
                this.#patternList = [p, ...prest];
                this.#globList = [g, ...grest];
                this.length = this.#patternList.length;
            }
        }
    }
    /**
     * The first entry in the parsed list of patterns
     */
    pattern() {
        return this.#patternList[this.#index];
    }
    /**
     * true of if pattern() returns a string
     */
    isString() {
        return typeof this.#patternList[this.#index] === 'string';
    }
    /**
     * true of if pattern() returns GLOBSTAR
     */
    isGlobstar() {
        return this.#patternList[this.#index] === minimatch_1.GLOBSTAR;
    }
    /**
     * true if pattern() returns a regexp
     */
    isRegExp() {
        return this.#patternList[this.#index] instanceof RegExp;
    }
    /**
     * The /-joined set of glob parts that make up this pattern
     */
    globString() {
        return (this.#globString =
            this.#globString ||
                (this.#index === 0 ?
                    this.isAbsolute() ?
                        this.#globList[0] + this.#globList.slice(1).join('/')
                        : this.#globList.join('/')
                    : this.#globList.slice(this.#index).join('/')));
    }
    /**
     * true if there are more pattern parts after this one
     */
    hasMore() {
        return this.length > this.#index + 1;
    }
    /**
     * The rest of the pattern after this part, or null if this is the end
     */
    rest() {
        if (this.#rest !== undefined)
            return this.#rest;
        if (!this.hasMore())
            return (this.#rest = null);
        this.#rest = new Pattern(this.#patternList, this.#globList, this.#index + 1, this.#platform);
        this.#rest.#isAbsolute = this.#isAbsolute;
        this.#rest.#isUNC = this.#isUNC;
        this.#rest.#isDrive = this.#isDrive;
        return this.#rest;
    }
    /**
     * true if the pattern represents a //unc/path/ on windows
     */
    isUNC() {
        const pl = this.#patternList;
        return this.#isUNC !== undefined ?
            this.#isUNC
            : (this.#isUNC =
                this.#platform === 'win32' &&
                    this.#index === 0 &&
                    pl[0] === '' &&
                    pl[1] === '' &&
                    typeof pl[2] === 'string' &&
                    !!pl[2] &&
                    typeof pl[3] === 'string' &&
                    !!pl[3]);
    }
    // pattern like C:/...
    // split = ['C:', ...]
    // XXX: would be nice to handle patterns like `c:*` to test the cwd
    // in c: for *, but I don't know of a way to even figure out what that
    // cwd is without actually chdir'ing into it?
    /**
     * True if the pattern starts with a drive letter on Windows
     */
    isDrive() {
        const pl = this.#patternList;
        return this.#isDrive !== undefined ?
            this.#isDrive
            : (this.#isDrive =
                this.#platform === 'win32' &&
                    this.#index === 0 &&
                    this.length > 1 &&
                    typeof pl[0] === 'string' &&
                    /^[a-z]:$/i.test(pl[0]));
    }
    // pattern = '/' or '/...' or '/x/...'
    // split = ['', ''] or ['', ...] or ['', 'x', ...]
    // Drive and UNC both considered absolute on windows
    /**
     * True if the pattern is rooted on an absolute path
     */
    isAbsolute() {
        const pl = this.#patternList;
        return this.#isAbsolute !== undefined ?
            this.#isAbsolute
            : (this.#isAbsolute =
                (pl[0] === '' && pl.length > 1) ||
                    this.isDrive() ||
                    this.isUNC());
    }
    /**
     * consume the root of the pattern, and return it
     */
    root() {
        const p = this.#patternList[0];
        return (typeof p === 'string' && this.isAbsolute() && this.#index === 0) ?
            p
            : '';
    }
    /**
     * Check to see if the current globstar pattern is allowed to follow
     * a symbolic link.
     */
    checkFollowGlobstar() {
        return !(this.#index === 0 ||
            !this.isGlobstar() ||
            !this.#followGlobstar);
    }
    /**
     * Mark that the current globstar pattern is following a symbolic link
     */
    markFollowGlobstar() {
        if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar)
            return false;
        this.#followGlobstar = false;
        return true;
    }
}
exports.Pattern = Pattern;
//# sourceMappingURL=pattern.js.mapPK~\} glob/dist/commonjs/glob.d.ts.mapnu[{"version":3,"file":"glob.d.ts","sourceRoot":"","sources":["../../src/glob.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,SAAS,EAAoB,MAAM,WAAW,CAAA;AACvD,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AAEnC,OAAO,EAC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9B,mBAAmB,EAAE,OAAO,CAAA;IAE5B;;OAEG;IACH,IAAI,EAAE,IAAI,CAAA;IAEV;;OAEG;IACH,QAAQ,EAAE,OAAO,EAAE,CAAA;IAEnB;;;;;;;;;;;OAWG;gBACS,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAAE,IAAI,EAAE,IAAI;IA2HlD;;OAEG;IACG,IAAI,IAAI,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IAoBpC;;OAEG;IACH,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IAgBzB;;OAEG;IACH,MAAM,IAAI,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;IAc9C;;OAEG;IACH,UAAU,IAAI,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;IAclD;;;OAGG;IACH,WAAW,IAAI,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC;IAGlD,CAAC,MAAM,CAAC,QAAQ,CAAC;IAIjB;;;OAGG;IACH,OAAO,IAAI,cAAc,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC;IAGnD,CAAC,MAAM,CAAC,aAAa,CAAC;CAGvB"}PK~\nUglob/dist/commonjs/index.d.tsnu[import { Minipass } from 'minipass';
import { Path } from 'path-scurry';
import type { GlobOptions, GlobOptionsWithFileTypesFalse, GlobOptionsWithFileTypesTrue, GlobOptionsWithFileTypesUnset } from './glob.js';
import { Glob } from './glob.js';
export { escape, unescape } from 'minimatch';
export type { FSOption, Path, WalkOptions, WalkOptionsWithFileTypesTrue, WalkOptionsWithFileTypesUnset, } from 'path-scurry';
export { Glob } from './glob.js';
export type { GlobOptions, GlobOptionsWithFileTypesFalse, GlobOptionsWithFileTypesTrue, GlobOptionsWithFileTypesUnset, } from './glob.js';
export { hasMagic } from './has-magic.js';
export { Ignore } from './ignore.js';
export type { IgnoreLike } from './ignore.js';
export type { MatchStream } from './walker.js';
/**
 * Syncronous form of {@link globStream}. Will read all the matches as fast as
 * you consume them, even all in a single tick if you consume them immediately,
 * but will still respond to backpressure if they're not consumed immediately.
 */
export declare function globStreamSync(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): Minipass;
export declare function globStreamSync(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): Minipass;
export declare function globStreamSync(pattern: string | string[], options: GlobOptionsWithFileTypesUnset): Minipass;
export declare function globStreamSync(pattern: string | string[], options: GlobOptions): Minipass | Minipass;
/**
 * Return a stream that emits all the strings or `Path` objects and
 * then emits `end` when completed.
 */
export declare function globStream(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): Minipass;
export declare function globStream(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): Minipass;
export declare function globStream(pattern: string | string[], options?: GlobOptionsWithFileTypesUnset | undefined): Minipass;
export declare function globStream(pattern: string | string[], options: GlobOptions): Minipass | Minipass;
/**
 * Synchronous form of {@link glob}
 */
export declare function globSync(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): string[];
export declare function globSync(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): Path[];
export declare function globSync(pattern: string | string[], options?: GlobOptionsWithFileTypesUnset | undefined): string[];
export declare function globSync(pattern: string | string[], options: GlobOptions): Path[] | string[];
/**
 * Perform an asynchronous glob search for the pattern(s) specified. Returns
 * [Path](https://isaacs.github.io/path-scurry/classes/PathBase) objects if the
 * {@link withFileTypes} option is set to `true`. See {@link GlobOptions} for
 * full option descriptions.
 */
declare function glob_(pattern: string | string[], options?: GlobOptionsWithFileTypesUnset | undefined): Promise;
declare function glob_(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): Promise;
declare function glob_(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): Promise;
declare function glob_(pattern: string | string[], options: GlobOptions): Promise;
/**
 * Return a sync iterator for walking glob pattern matches.
 */
export declare function globIterateSync(pattern: string | string[], options?: GlobOptionsWithFileTypesUnset | undefined): Generator;
export declare function globIterateSync(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): Generator;
export declare function globIterateSync(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): Generator;
export declare function globIterateSync(pattern: string | string[], options: GlobOptions): Generator | Generator;
/**
 * Return an async iterator for walking glob pattern matches.
 */
export declare function globIterate(pattern: string | string[], options?: GlobOptionsWithFileTypesUnset | undefined): AsyncGenerator;
export declare function globIterate(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): AsyncGenerator;
export declare function globIterate(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): AsyncGenerator;
export declare function globIterate(pattern: string | string[], options: GlobOptions): AsyncGenerator | AsyncGenerator;
export declare const streamSync: typeof globStreamSync;
export declare const stream: typeof globStream & {
    sync: typeof globStreamSync;
};
export declare const iterateSync: typeof globIterateSync;
export declare const iterate: typeof globIterate & {
    sync: typeof globIterateSync;
};
export declare const sync: typeof globSync & {
    stream: typeof globStreamSync;
    iterate: typeof globIterateSync;
};
export declare const glob: typeof glob_ & {
    glob: typeof glob_;
    globSync: typeof globSync;
    sync: typeof globSync & {
        stream: typeof globStreamSync;
        iterate: typeof globIterateSync;
    };
    globStream: typeof globStream;
    stream: typeof globStream & {
        sync: typeof globStreamSync;
    };
    globStreamSync: typeof globStreamSync;
    streamSync: typeof globStreamSync;
    globIterate: typeof globIterate;
    iterate: typeof globIterate & {
        sync: typeof globIterateSync;
    };
    globIterateSync: typeof globIterateSync;
    iterateSync: typeof globIterateSync;
    Glob: typeof Glob;
    hasMagic: (pattern: string | string[], options?: GlobOptions) => boolean;
    escape: (s: string, { windowsPathsNoEscape, }?: Pick | undefined) => string;
    unescape: (s: string, { windowsPathsNoEscape, }?: Pick | undefined) => string;
};
//# sourceMappingURL=index.d.ts.mapPK~\e:glob/dist/commonjs/ignore.jsnu["use strict";
// give it a pattern, and it'll be able to tell you if
// a given path should be ignored.
// Ignoring a path ignores its children if the pattern ends in /**
// Ignores are always parsed in dot:true mode
Object.defineProperty(exports, "__esModule", { value: true });
exports.Ignore = void 0;
const minimatch_1 = require("minimatch");
const pattern_js_1 = require("./pattern.js");
const defaultPlatform = (typeof process === 'object' &&
    process &&
    typeof process.platform === 'string') ?
    process.platform
    : 'linux';
/**
 * Class used to process ignored patterns
 */
class Ignore {
    relative;
    relativeChildren;
    absolute;
    absoluteChildren;
    platform;
    mmopts;
    constructor(ignored, { nobrace, nocase, noext, noglobstar, platform = defaultPlatform, }) {
        this.relative = [];
        this.absolute = [];
        this.relativeChildren = [];
        this.absoluteChildren = [];
        this.platform = platform;
        this.mmopts = {
            dot: true,
            nobrace,
            nocase,
            noext,
            noglobstar,
            optimizationLevel: 2,
            platform,
            nocomment: true,
            nonegate: true,
        };
        for (const ign of ignored)
            this.add(ign);
    }
    add(ign) {
        // this is a little weird, but it gives us a clean set of optimized
        // minimatch matchers, without getting tripped up if one of them
        // ends in /** inside a brace section, and it's only inefficient at
        // the start of the walk, not along it.
        // It'd be nice if the Pattern class just had a .test() method, but
        // handling globstars is a bit of a pita, and that code already lives
        // in minimatch anyway.
        // Another way would be if maybe Minimatch could take its set/globParts
        // as an option, and then we could at least just use Pattern to test
        // for absolute-ness.
        // Yet another way, Minimatch could take an array of glob strings, and
        // a cwd option, and do the right thing.
        const mm = new minimatch_1.Minimatch(ign, this.mmopts);
        for (let i = 0; i < mm.set.length; i++) {
            const parsed = mm.set[i];
            const globParts = mm.globParts[i];
            /* c8 ignore start */
            if (!parsed || !globParts) {
                throw new Error('invalid pattern object');
            }
            // strip off leading ./ portions
            // https://github.com/isaacs/node-glob/issues/570
            while (parsed[0] === '.' && globParts[0] === '.') {
                parsed.shift();
                globParts.shift();
            }
            /* c8 ignore stop */
            const p = new pattern_js_1.Pattern(parsed, globParts, 0, this.platform);
            const m = new minimatch_1.Minimatch(p.globString(), this.mmopts);
            const children = globParts[globParts.length - 1] === '**';
            const absolute = p.isAbsolute();
            if (absolute)
                this.absolute.push(m);
            else
                this.relative.push(m);
            if (children) {
                if (absolute)
                    this.absoluteChildren.push(m);
                else
                    this.relativeChildren.push(m);
            }
        }
    }
    ignored(p) {
        const fullpath = p.fullpath();
        const fullpaths = `${fullpath}/`;
        const relative = p.relative() || '.';
        const relatives = `${relative}/`;
        for (const m of this.relative) {
            if (m.match(relative) || m.match(relatives))
                return true;
        }
        for (const m of this.absolute) {
            if (m.match(fullpath) || m.match(fullpaths))
                return true;
        }
        return false;
    }
    childrenIgnored(p) {
        const fullpath = p.fullpath() + '/';
        const relative = (p.relative() || '.') + '/';
        for (const m of this.relativeChildren) {
            if (m.match(relative))
                return true;
        }
        for (const m of this.absoluteChildren) {
            if (m.match(fullpath))
                return true;
        }
        return false;
    }
}
exports.Ignore = Ignore;
//# sourceMappingURL=ignore.js.mapPK~\WZ  glob/dist/commonjs/index.js.mapnu[{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAA,yCAA4C;AAS5C,uCAAgC;AAChC,iDAAyC;AAEzC,uCAA4C;AAAnC,mGAAA,MAAM,OAAA;AAAE,qGAAA,QAAQ,OAAA;AAQzB,qCAAgC;AAAvB,+FAAA,IAAI,OAAA;AAOb,+CAAyC;AAAhC,wGAAA,QAAQ,OAAA;AACjB,yCAAoC;AAA3B,mGAAA,MAAM,OAAA;AAyBf,SAAgB,cAAc,CAC5B,OAA0B,EAC1B,UAAuB,EAAE;IAEzB,OAAO,IAAI,cAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,UAAU,EAAE,CAAA;AAChD,CAAC;AALD,wCAKC;AAsBD,SAAgB,UAAU,CACxB,OAA0B,EAC1B,UAAuB,EAAE;IAEzB,OAAO,IAAI,cAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,MAAM,EAAE,CAAA;AAC5C,CAAC;AALD,gCAKC;AAqBD,SAAgB,QAAQ,CACtB,OAA0B,EAC1B,UAAuB,EAAE;IAEzB,OAAO,IAAI,cAAI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ACX,IAAI,EAAJ,cAAI;IACJ,QAAQ,EAAR,uBAAQ;IACR,MAAM,EAAN,kBAAM;IACN,QAAQ,EAAR,oBAAQ;CACT,CAAC,CAAA;AACF,YAAI,CAAC,IAAI,GAAG,YAAI,CAAA","sourcesContent":["import { escape, unescape } from 'minimatch'\nimport { Minipass } from 'minipass'\nimport { Path } from 'path-scurry'\nimport type {\n  GlobOptions,\n  GlobOptionsWithFileTypesFalse,\n  GlobOptionsWithFileTypesTrue,\n  GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nimport { Glob } from './glob.js'\nimport { hasMagic } from './has-magic.js'\n\nexport { escape, unescape } from 'minimatch'\nexport type {\n  FSOption,\n  Path,\n  WalkOptions,\n  WalkOptionsWithFileTypesTrue,\n  WalkOptionsWithFileTypesUnset,\n} from 'path-scurry'\nexport { Glob } from './glob.js'\nexport type {\n  GlobOptions,\n  GlobOptionsWithFileTypesFalse,\n  GlobOptionsWithFileTypesTrue,\n  GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nexport { hasMagic } from './has-magic.js'\nexport { Ignore } from './ignore.js'\nexport type { IgnoreLike } from './ignore.js'\nexport type { MatchStream } from './walker.js'\n\n/**\n * Syncronous form of {@link globStream}. Will read all the matches as fast as\n * you consume them, even all in a single tick if you consume them immediately,\n * but will still respond to backpressure if they're not consumed immediately.\n */\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesUnset,\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptions,\n): Minipass | Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).streamSync()\n}\n\n/**\n * Return a stream that emits all the strings or `Path` objects and\n * then emits `end` when completed.\n */\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptions,\n): Minipass | Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).stream()\n}\n\n/**\n * Synchronous form of {@link glob}\n */\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Path[]\nexport function globSync(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptions,\n): Path[] | string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).walkSync()\n}\n\n/**\n * Perform an asynchronous glob search for the pattern(s) specified. Returns\n * [Path](https://isaacs.github.io/path-scurry/classes/PathBase) objects if the\n * {@link withFileTypes} option is set to `true`. See {@link GlobOptions} for\n * full option descriptions.\n */\nasync function glob_(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptions,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).walk()\n}\n\n/**\n * Return a sync iterator for walking glob pattern matches.\n */\nexport function globIterateSync(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptions,\n): Generator | Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).iterateSync()\n}\n\n/**\n * Return an async iterator for walking glob pattern matches.\n */\nexport function globIterate(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptions,\n): AsyncGenerator | AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).iterate()\n}\n\n// aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc\nexport const streamSync = globStreamSync\nexport const stream = Object.assign(globStream, { sync: globStreamSync })\nexport const iterateSync = globIterateSync\nexport const iterate = Object.assign(globIterate, {\n  sync: globIterateSync,\n})\nexport const sync = Object.assign(globSync, {\n  stream: globStreamSync,\n  iterate: globIterateSync,\n})\n\nexport const glob = Object.assign(glob_, {\n  glob: glob_,\n  globSync,\n  sync,\n  globStream,\n  stream,\n  globStreamSync,\n  streamSync,\n  globIterate,\n  iterate,\n  globIterateSync,\n  iterateSync,\n  Glob,\n  hasMagic,\n  escape,\n  unescape,\n})\nglob.glob = glob\n"]}PK~\:n:nglob/dist/commonjs/glob.js.mapnu[{"version":3,"file":"glob.js","sourceRoot":"","sources":["../../src/glob.ts"],"names":[],"mappings":";;;AAAA,yCAAuD;AAEvD,uCAAwC;AACxC,6CAOoB;AAEpB,6CAAsC;AACtC,2CAAoD;AAKpD,4CAA4C;AAC5C,gDAAgD;AAChD,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,EAAE,IAAI,CAAC,MAAM;YACnB,mBAAmB,EAAE,IAAI,CAAC,mBAAmB;SAC9C,CAAC,CAAC,MAAM,EAAE,CAAA;IACb,CAAC;IAMD,UAAU;QACR,OAAO,IAAI,sBAAU,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE;YACpD,GAAG,IAAI,CAAC,IAAI;YACZ,QAAQ,EACN,IAAI,CAAC,QAAQ,KAAK,QAAQ,CAAC,CAAC;gBAC1B,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE;gBACzC,CAAC,CAAC,QAAQ;YACZ,QAAQ,EAAE,IAAI,CAAC,QAAQ;YACvB,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,mBAAmB,EAAE,IAAI,CAAC,mBAAmB;SAC9C,CAAC,CAAC,UAAU,EAAE,CAAA;IACjB,CAAC;IAED;;;OAGG;IACH,WAAW;QACT,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAA;IAC7C,CAAC;IACD,CAAC,MAAM,CAAC,QAAQ,CAAC;QACf,OAAO,IAAI,CAAC,WAAW,EAAE,CAAA;IAC3B,CAAC;IAED;;;OAGG;IACH,OAAO;QACL,OAAO,IAAI,CAAC,MAAM,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,EAAE,CAAA;IAC9C,CAAC;IACD,CAAC,MAAM,CAAC,aAAa,CAAC;QACpB,OAAO,IAAI,CAAC,OAAO,EAAE,CAAA;IACvB,CAAC;CACF;AA7QD,oBA6QC","sourcesContent":["import { Minimatch, MinimatchOptions } from 'minimatch'\nimport { Minipass } from 'minipass'\nimport { fileURLToPath } from 'node:url'\nimport {\n  FSOption,\n  Path,\n  PathScurry,\n  PathScurryDarwin,\n  PathScurryPosix,\n  PathScurryWin32,\n} from 'path-scurry'\nimport { IgnoreLike } from './ignore.js'\nimport { Pattern } from './pattern.js'\nimport { GlobStream, GlobWalker } from './walker.js'\n\nexport type MatchSet = Minimatch['set']\nexport type GlobParts = Exclude\n\n// if no process global, just call it linux.\n// so we default to case-sensitive, / separators\nconst defaultPlatform: NodeJS.Platform =\n  (\n    typeof process === 'object' &&\n    process &&\n    typeof process.platform === 'string'\n  ) ?\n    process.platform\n  : 'linux'\n\n/**\n * A `GlobOptions` object may be provided to any of the exported methods, and\n * must be provided to the `Glob` constructor.\n *\n * All options are optional, boolean, and false by default, unless otherwise\n * noted.\n *\n * All resolved options are added to the Glob object as properties.\n *\n * If you are running many `glob` operations, you can pass a Glob object as the\n * `options` argument to a subsequent operation to share the previously loaded\n * cache.\n */\nexport interface GlobOptions {\n  /**\n   * Set to `true` to always receive absolute paths for\n   * matched files. Set to `false` to always return relative paths.\n   *\n   * When this option is not set, absolute paths are returned for patterns\n   * that are absolute, and otherwise paths are returned that are relative\n   * to the `cwd` setting.\n   *\n   * This does _not_ make an extra system call to get\n   * the realpath, it only does string path resolution.\n   *\n   * Conflicts with {@link withFileTypes}\n   */\n  absolute?: boolean\n\n  /**\n   * Set to false to enable {@link windowsPathsNoEscape}\n   *\n   * @deprecated\n   */\n  allowWindowsEscape?: boolean\n\n  /**\n   * The current working directory in which to search. Defaults to\n   * `process.cwd()`.\n   *\n   * May be eiher a string path or a `file://` URL object or string.\n   */\n  cwd?: string | URL\n\n  /**\n   * Include `.dot` files in normal matches and `globstar`\n   * matches. Note that an explicit dot in a portion of the pattern\n   * will always match dot files.\n   */\n  dot?: boolean\n\n  /**\n   * Prepend all relative path strings with `./` (or `.\\` on Windows).\n   *\n   * Without this option, returned relative paths are \"bare\", so instead of\n   * returning `'./foo/bar'`, they are returned as `'foo/bar'`.\n   *\n   * Relative patterns starting with `'../'` are not prepended with `./`, even\n   * if this option is set.\n   */\n  dotRelative?: boolean\n\n  /**\n   * Follow symlinked directories when expanding `**`\n   * patterns. This can result in a lot of duplicate references in\n   * the presence of cyclic links, and make performance quite bad.\n   *\n   * By default, a `**` in a pattern will follow 1 symbolic link if\n   * it is not the first item in the pattern, or none if it is the\n   * first item in the pattern, following the same behavior as Bash.\n   */\n  follow?: boolean\n\n  /**\n   * string or string[], or an object with `ignore` and `ignoreChildren`\n   * methods.\n   *\n   * If a string or string[] is provided, then this is treated as a glob\n   * pattern or array of glob patterns to exclude from matches. To ignore all\n   * children within a directory, as well as the entry itself, append `'/**'`\n   * to the ignore pattern.\n   *\n   * **Note** `ignore` patterns are _always_ in `dot:true` mode, regardless of\n   * any other settings.\n   *\n   * If an object is provided that has `ignored(path)` and/or\n   * `childrenIgnored(path)` methods, then these methods will be called to\n   * determine whether any Path is a match or if its children should be\n   * traversed, respectively.\n   */\n  ignore?: string | string[] | IgnoreLike\n\n  /**\n   * Treat brace expansion like `{a,b}` as a \"magic\" pattern. Has no\n   * effect if {@link nobrace} is set.\n   *\n   * Only has effect on the {@link hasMagic} function.\n   */\n  magicalBraces?: boolean\n\n  /**\n   * Add a `/` character to directory matches. Note that this requires\n   * additional stat calls in some cases.\n   */\n  mark?: boolean\n\n  /**\n   * Perform a basename-only match if the pattern does not contain any slash\n   * characters. That is, `*.js` would be treated as equivalent to\n   * `**\\/*.js`, matching all js files in all directories.\n   */\n  matchBase?: boolean\n\n  /**\n   * Limit the directory traversal to a given depth below the cwd.\n   * Note that this does NOT prevent traversal to sibling folders,\n   * root patterns, and so on. It only limits the maximum folder depth\n   * that the walk will descend, relative to the cwd.\n   */\n  maxDepth?: number\n\n  /**\n   * Do not expand `{a,b}` and `{1..3}` brace sets.\n   */\n  nobrace?: boolean\n\n  /**\n   * Perform a case-insensitive match. This defaults to `true` on macOS and\n   * Windows systems, and `false` on all others.\n   *\n   * **Note** `nocase` should only be explicitly set when it is\n   * known that the filesystem's case sensitivity differs from the\n   * platform default. If set `true` on case-sensitive file\n   * systems, or `false` on case-insensitive file systems, then the\n   * walk may return more or less results than expected.\n   */\n  nocase?: boolean\n\n  /**\n   * Do not match directories, only files. (Note: to match\n   * _only_ directories, put a `/` at the end of the pattern.)\n   */\n  nodir?: boolean\n\n  /**\n   * Do not match \"extglob\" patterns such as `+(a|b)`.\n   */\n  noext?: boolean\n\n  /**\n   * Do not match `**` against multiple filenames. (Ie, treat it as a normal\n   * `*` instead.)\n   *\n   * Conflicts with {@link matchBase}\n   */\n  noglobstar?: boolean\n\n  /**\n   * Defaults to value of `process.platform` if available, or `'linux'` if\n   * not. Setting `platform:'win32'` on non-Windows systems may cause strange\n   * behavior.\n   */\n  platform?: NodeJS.Platform\n\n  /**\n   * Set to true to call `fs.realpath` on all of the\n   * results. In the case of an entry that cannot be resolved, the\n   * entry is omitted. This incurs a slight performance penalty, of\n   * course, because of the added system calls.\n   */\n  realpath?: boolean\n\n  /**\n   *\n   * A string path resolved against the `cwd` option, which\n   * is used as the starting point for absolute patterns that start\n   * with `/`, (but not drive letters or UNC paths on Windows).\n   *\n   * Note that this _doesn't_ necessarily limit the walk to the\n   * `root` directory, and doesn't affect the cwd starting point for\n   * non-absolute patterns. A pattern containing `..` will still be\n   * able to traverse out of the root directory, if it is not an\n   * actual root directory on the filesystem, and any non-absolute\n   * patterns will be matched in the `cwd`. For example, the\n   * pattern `/../*` with `{root:'/some/path'}` will return all\n   * files in `/some`, not all files in `/some/path`. The pattern\n   * `*` with `{root:'/some/path'}` will return all the entries in\n   * the cwd, not the entries in `/some/path`.\n   *\n   * To start absolute and non-absolute patterns in the same\n   * path, you can use `{root:''}`. However, be aware that on\n   * Windows systems, a pattern like `x:/*` or `//host/share/*` will\n   * _always_ start in the `x:/` or `//host/share` directory,\n   * regardless of the `root` setting.\n   */\n  root?: string\n\n  /**\n   * A [PathScurry](http://npm.im/path-scurry) object used\n   * to traverse the file system. If the `nocase` option is set\n   * explicitly, then any provided `scurry` object must match this\n   * setting.\n   */\n  scurry?: PathScurry\n\n  /**\n   * Call `lstat()` on all entries, whether required or not to determine\n   * if it's a valid match. When used with {@link withFileTypes}, this means\n   * that matches will include data such as modified time, permissions, and\n   * so on.  Note that this will incur a performance cost due to the added\n   * system calls.\n   */\n  stat?: boolean\n\n  /**\n   * An AbortSignal which will cancel the Glob walk when\n   * triggered.\n   */\n  signal?: AbortSignal\n\n  /**\n   * Use `\\\\` as a path separator _only_, and\n   *  _never_ as an escape character. If set, all `\\\\` characters are\n   *  replaced with `/` in the pattern.\n   *\n   *  Note that this makes it **impossible** to match against paths\n   *  containing literal glob pattern characters, but allows matching\n   *  with patterns constructed using `path.join()` and\n   *  `path.resolve()` on Windows platforms, mimicking the (buggy!)\n   *  behavior of Glob v7 and before on Windows. Please use with\n   *  caution, and be mindful of [the caveat below about Windows\n   *  paths](#windows). (For legacy reasons, this is also set if\n   *  `allowWindowsEscape` is set to the exact value `false`.)\n   */\n  windowsPathsNoEscape?: boolean\n\n  /**\n   * Return [PathScurry](http://npm.im/path-scurry)\n   * `Path` objects instead of strings. These are similar to a\n   * NodeJS `Dirent` object, but with additional methods and\n   * properties.\n   *\n   * Conflicts with {@link absolute}\n   */\n  withFileTypes?: boolean\n\n  /**\n   * An fs implementation to override some or all of the defaults.  See\n   * http://npm.im/path-scurry for details about what can be overridden.\n   */\n  fs?: FSOption\n\n  /**\n   * Just passed along to Minimatch.  Note that this makes all pattern\n   * matching operations slower and *extremely* noisy.\n   */\n  debug?: boolean\n\n  /**\n   * Return `/` delimited paths, even on Windows.\n   *\n   * On posix systems, this has no effect.  But, on Windows, it means that\n   * paths will be `/` delimited, and absolute paths will be their full\n   * resolved UNC forms, eg instead of `'C:\\\\foo\\\\bar'`, it would return\n   * `'//?/C:/foo/bar'`\n   */\n  posix?: boolean\n\n  /**\n   * Do not match any children of any matches. For example, the pattern\n   * `**\\/foo` would match `a/foo`, but not `a/foo/b/foo` in this mode.\n   *\n   * This is especially useful for cases like \"find all `node_modules`\n   * folders, but not the ones in `node_modules`\".\n   *\n   * In order to support this, the `Ignore` implementation must support an\n   * `add(pattern: string)` method. If using the default `Ignore` class, then\n   * this is fine, but if this is set to `false`, and a custom `Ignore` is\n   * provided that does not have an `add()` method, then it will throw an\n   * error.\n   *\n   * **Caveat** It *only* ignores matches that would be a descendant of a\n   * previous match, and only if that descendant is matched *after* the\n   * ancestor is encountered. Since the file system walk happens in\n   * indeterminate order, it's possible that a match will already be added\n   * before its ancestor, if multiple or braced patterns are used.\n   *\n   * For example:\n   *\n   * ```ts\n   * const results = await glob([\n   *   // likely to match first, since it's just a stat\n   *   'a/b/c/d/e/f',\n   *\n   *   // this pattern is more complicated! It must to various readdir()\n   *   // calls and test the results against a regular expression, and that\n   *   // is certainly going to take a little bit longer.\n   *   //\n   *   // So, later on, it encounters a match at 'a/b/c/d/e', but it's too\n   *   // late to ignore a/b/c/d/e/f, because it's already been emitted.\n   *   'a/[bdf]/?/[a-z]/*',\n   * ], { includeChildMatches: false })\n   * ```\n   *\n   * It's best to only set this to `false` if you can be reasonably sure that\n   * no components of the pattern will potentially match one another's file\n   * system descendants, or if the occasional included child entry will not\n   * cause problems.\n   *\n   * @default true\n   */\n  includeChildMatches?: boolean\n}\n\nexport type GlobOptionsWithFileTypesTrue = GlobOptions & {\n  withFileTypes: true\n  // string options not relevant if returning Path objects.\n  absolute?: undefined\n  mark?: undefined\n  posix?: undefined\n}\n\nexport type GlobOptionsWithFileTypesFalse = GlobOptions & {\n  withFileTypes?: false\n}\n\nexport type GlobOptionsWithFileTypesUnset = GlobOptions & {\n  withFileTypes?: undefined\n}\n\nexport type Result =\n  Opts extends GlobOptionsWithFileTypesTrue ? Path\n  : Opts extends GlobOptionsWithFileTypesFalse ? string\n  : Opts extends GlobOptionsWithFileTypesUnset ? string\n  : string | Path\nexport type Results = Result[]\n\nexport type FileTypes =\n  Opts extends GlobOptionsWithFileTypesTrue ? true\n  : Opts extends GlobOptionsWithFileTypesFalse ? false\n  : Opts extends GlobOptionsWithFileTypesUnset ? false\n  : boolean\n\n/**\n * An object that can perform glob pattern traversals.\n */\nexport class Glob implements GlobOptions {\n  absolute?: boolean\n  cwd: string\n  root?: string\n  dot: boolean\n  dotRelative: boolean\n  follow: boolean\n  ignore?: string | string[] | IgnoreLike\n  magicalBraces: boolean\n  mark?: boolean\n  matchBase: boolean\n  maxDepth: number\n  nobrace: boolean\n  nocase: boolean\n  nodir: boolean\n  noext: boolean\n  noglobstar: boolean\n  pattern: string[]\n  platform: NodeJS.Platform\n  realpath: boolean\n  scurry: PathScurry\n  stat: boolean\n  signal?: AbortSignal\n  windowsPathsNoEscape: boolean\n  withFileTypes: FileTypes\n  includeChildMatches: boolean\n\n  /**\n   * The options provided to the constructor.\n   */\n  opts: Opts\n\n  /**\n   * An array of parsed immutable {@link Pattern} objects.\n   */\n  patterns: Pattern[]\n\n  /**\n   * All options are stored as properties on the `Glob` object.\n   *\n   * See {@link GlobOptions} for full options descriptions.\n   *\n   * Note that a previous `Glob` object can be passed as the\n   * `GlobOptions` to another `Glob` instantiation to re-use settings\n   * and caches with a new pattern.\n   *\n   * Traversal functions can be called multiple times to run the walk\n   * again.\n   */\n  constructor(pattern: string | string[], opts: Opts) {\n    /* c8 ignore start */\n    if (!opts) throw new TypeError('glob options required')\n    /* c8 ignore stop */\n    this.withFileTypes = !!opts.withFileTypes as FileTypes\n    this.signal = opts.signal\n    this.follow = !!opts.follow\n    this.dot = !!opts.dot\n    this.dotRelative = !!opts.dotRelative\n    this.nodir = !!opts.nodir\n    this.mark = !!opts.mark\n    if (!opts.cwd) {\n      this.cwd = ''\n    } else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) {\n      opts.cwd = fileURLToPath(opts.cwd)\n    }\n    this.cwd = opts.cwd || ''\n    this.root = opts.root\n    this.magicalBraces = !!opts.magicalBraces\n    this.nobrace = !!opts.nobrace\n    this.noext = !!opts.noext\n    this.realpath = !!opts.realpath\n    this.absolute = opts.absolute\n    this.includeChildMatches = opts.includeChildMatches !== false\n\n    this.noglobstar = !!opts.noglobstar\n    this.matchBase = !!opts.matchBase\n    this.maxDepth =\n      typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity\n    this.stat = !!opts.stat\n    this.ignore = opts.ignore\n\n    if (this.withFileTypes && this.absolute !== undefined) {\n      throw new Error('cannot set absolute and withFileTypes:true')\n    }\n\n    if (typeof pattern === 'string') {\n      pattern = [pattern]\n    }\n\n    this.windowsPathsNoEscape =\n      !!opts.windowsPathsNoEscape ||\n      (opts as { allowWindowsEscape?: boolean }).allowWindowsEscape ===\n        false\n\n    if (this.windowsPathsNoEscape) {\n      pattern = pattern.map(p => p.replace(/\\\\/g, '/'))\n    }\n\n    if (this.matchBase) {\n      if (opts.noglobstar) {\n        throw new TypeError('base matching requires globstar')\n      }\n      pattern = pattern.map(p => (p.includes('/') ? p : `./**/${p}`))\n    }\n\n    this.pattern = pattern\n\n    this.platform = opts.platform || defaultPlatform\n    this.opts = { ...opts, platform: this.platform }\n    if (opts.scurry) {\n      this.scurry = opts.scurry\n      if (\n        opts.nocase !== undefined &&\n        opts.nocase !== opts.scurry.nocase\n      ) {\n        throw new Error('nocase option contradicts provided scurry option')\n      }\n    } else {\n      const Scurry =\n        opts.platform === 'win32' ? PathScurryWin32\n        : opts.platform === 'darwin' ? PathScurryDarwin\n        : opts.platform ? PathScurryPosix\n        : PathScurry\n      this.scurry = new Scurry(this.cwd, {\n        nocase: opts.nocase,\n        fs: opts.fs,\n      })\n    }\n    this.nocase = this.scurry.nocase\n\n    // If you do nocase:true on a case-sensitive file system, then\n    // we need to use regexps instead of strings for non-magic\n    // path portions, because statting `aBc` won't return results\n    // for the file `AbC` for example.\n    const nocaseMagicOnly =\n      this.platform === 'darwin' || this.platform === 'win32'\n\n    const mmo: MinimatchOptions = {\n      // default nocase based on platform\n      ...opts,\n      dot: this.dot,\n      matchBase: this.matchBase,\n      nobrace: this.nobrace,\n      nocase: this.nocase,\n      nocaseMagicOnly,\n      nocomment: true,\n      noext: this.noext,\n      nonegate: true,\n      optimizationLevel: 2,\n      platform: this.platform,\n      windowsPathsNoEscape: this.windowsPathsNoEscape,\n      debug: !!this.opts.debug,\n    }\n\n    const mms = this.pattern.map(p => new Minimatch(p, mmo))\n    const [matchSet, globParts] = mms.reduce(\n      (set: [MatchSet, GlobParts], m) => {\n        set[0].push(...m.set)\n        set[1].push(...m.globParts)\n        return set\n      },\n      [[], []],\n    )\n    this.patterns = matchSet.map((set, i) => {\n      const g = globParts[i]\n      /* c8 ignore start */\n      if (!g) throw new Error('invalid pattern object')\n      /* c8 ignore stop */\n      return new Pattern(set, g, 0, this.platform)\n    })\n  }\n\n  /**\n   * Returns a Promise that resolves to the results array.\n   */\n  async walk(): Promise>\n  async walk(): Promise<(string | Path)[]> {\n    // Walkers always return array of Path objects, so we just have to\n    // coerce them into the right shape.  It will have already called\n    // realpath() if the option was set to do so, so we know that's cached.\n    // start out knowing the cwd, at least\n    return [\n      ...(await new GlobWalker(this.patterns, this.scurry.cwd, {\n        ...this.opts,\n        maxDepth:\n          this.maxDepth !== Infinity ?\n            this.maxDepth + this.scurry.cwd.depth()\n          : Infinity,\n        platform: this.platform,\n        nocase: this.nocase,\n        includeChildMatches: this.includeChildMatches,\n      }).walk()),\n    ]\n  }\n\n  /**\n   * synchronous {@link Glob.walk}\n   */\n  walkSync(): Results\n  walkSync(): (string | Path)[] {\n    return [\n      ...new GlobWalker(this.patterns, this.scurry.cwd, {\n        ...this.opts,\n        maxDepth:\n          this.maxDepth !== Infinity ?\n            this.maxDepth + this.scurry.cwd.depth()\n          : Infinity,\n        platform: this.platform,\n        nocase: this.nocase,\n        includeChildMatches: this.includeChildMatches,\n      }).walkSync(),\n    ]\n  }\n\n  /**\n   * Stream results asynchronously.\n   */\n  stream(): Minipass, Result>\n  stream(): Minipass {\n    return new GlobStream(this.patterns, this.scurry.cwd, {\n      ...this.opts,\n      maxDepth:\n        this.maxDepth !== Infinity ?\n          this.maxDepth + this.scurry.cwd.depth()\n        : Infinity,\n      platform: this.platform,\n      nocase: this.nocase,\n      includeChildMatches: this.includeChildMatches,\n    }).stream()\n  }\n\n  /**\n   * Stream results synchronously.\n   */\n  streamSync(): Minipass, Result>\n  streamSync(): Minipass {\n    return new GlobStream(this.patterns, this.scurry.cwd, {\n      ...this.opts,\n      maxDepth:\n        this.maxDepth !== Infinity ?\n          this.maxDepth + this.scurry.cwd.depth()\n        : Infinity,\n      platform: this.platform,\n      nocase: this.nocase,\n      includeChildMatches: this.includeChildMatches,\n    }).streamSync()\n  }\n\n  /**\n   * Default sync iteration function. Returns a Generator that\n   * iterates over the results.\n   */\n  iterateSync(): Generator, void, void> {\n    return this.streamSync()[Symbol.iterator]()\n  }\n  [Symbol.iterator]() {\n    return this.iterateSync()\n  }\n\n  /**\n   * Default async iteration function. Returns an AsyncGenerator that\n   * iterates over the results.\n   */\n  iterate(): AsyncGenerator, void, void> {\n    return this.stream()[Symbol.asyncIterator]()\n  }\n  [Symbol.asyncIterator]() {\n    return this.iterate()\n  }\n}\n"]}PK~\8\hXX!glob/dist/commonjs/processor.d.tsnu[import { MMRegExp } from 'minimatch';
import { Path } from 'path-scurry';
import { Pattern } from './pattern.js';
import { GlobWalkerOpts } from './walker.js';
/**
 * A cache of which patterns have been processed for a given Path
 */
export declare class HasWalkedCache {
    store: Map>;
    constructor(store?: Map>);
    copy(): HasWalkedCache;
    hasWalked(target: Path, pattern: Pattern): boolean | undefined;
    storeWalked(target: Path, pattern: Pattern): void;
}
/**
 * A record of which paths have been matched in a given walk step,
 * and whether they only are considered a match if they are a directory,
 * and whether their absolute or relative path should be returned.
 */
export declare class MatchRecord {
    store: Map;
    add(target: Path, absolute: boolean, ifDir: boolean): void;
    entries(): [Path, boolean, boolean][];
}
/**
 * A collection of patterns that must be processed in a subsequent step
 * for a given path.
 */
export declare class SubWalks {
    store: Map;
    add(target: Path, pattern: Pattern): void;
    get(target: Path): Pattern[];
    entries(): [Path, Pattern[]][];
    keys(): Path[];
}
/**
 * The class that processes patterns for a given path.
 *
 * Handles child entry filtering, and determining whether a path's
 * directory contents must be read.
 */
export declare class Processor {
    hasWalkedCache: HasWalkedCache;
    matches: MatchRecord;
    subwalks: SubWalks;
    patterns?: Pattern[];
    follow: boolean;
    dot: boolean;
    opts: GlobWalkerOpts;
    constructor(opts: GlobWalkerOpts, hasWalkedCache?: HasWalkedCache);
    processPatterns(target: Path, patterns: Pattern[]): this;
    subwalkTargets(): Path[];
    child(): Processor;
    filterEntries(parent: Path, entries: Path[]): Processor;
    testGlobstar(e: Path, pattern: Pattern, rest: Pattern | null, absolute: boolean): void;
    testRegExp(e: Path, p: MMRegExp, rest: Pattern | null, absolute: boolean): void;
    testString(e: Path, p: string, rest: Pattern | null, absolute: boolean): void;
}
//# sourceMappingURL=processor.d.ts.mapPK~\,// glob/dist/commonjs/ignore.js.mapnu[{"version":3,"file":"ignore.js","sourceRoot":"","sources":["../../src/ignore.ts"],"names":[],"mappings":";AAAA,sDAAsD;AACtD,kCAAkC;AAClC,kEAAkE;AAClE,6CAA6C;;;AAE7C,yCAAuD;AAEvD,6CAAsC;AAStC,MAAM,eAAe,GACnB,CACE,OAAO,OAAO,KAAK,QAAQ;IAC3B,OAAO;IACP,OAAO,OAAO,CAAC,QAAQ,KAAK,QAAQ,CACrC,CAAC,CAAC;IACD,OAAO,CAAC,QAAQ;IAClB,CAAC,CAAC,OAAO,CAAA;AAEX;;GAEG;AACH,MAAa,MAAM;IACjB,QAAQ,CAAa;IACrB,gBAAgB,CAAa;IAC7B,QAAQ,CAAa;IACrB,gBAAgB,CAAa;IAC7B,QAAQ,CAAiB;IACzB,MAAM,CAAkB;IAExB,YACE,OAAiB,EACjB,EACE,OAAO,EACP,MAAM,EACN,KAAK,EACL,UAAU,EACV,QAAQ,GAAG,eAAe,GACX;QAEjB,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAA;QAClB,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAA;QAClB,IAAI,CAAC,gBAAgB,GAAG,EAAE,CAAA;QAC1B,IAAI,CAAC,gBAAgB,GAAG,EAAE,CAAA;QAC1B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;QACxB,IAAI,CAAC,MAAM,GAAG;YACZ,GAAG,EA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O,IAAI,CAAA;QAC1D,CAAC;QACD,OAAO,KAAK,CAAA;IACd,CAAC;IAED,eAAe,CAAC,CAAO;QACrB,MAAM,QAAQ,GAAG,CAAC,CAAC,QAAQ,EAAE,GAAG,GAAG,CAAA;QACnC,MAAM,QAAQ,GAAG,CAAC,CAAC,CAAC,QAAQ,EAAE,IAAI,GAAG,CAAC,GAAG,GAAG,CAAA;QAC5C,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACtC,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC;gBAAE,OAAO,IAAI,CAAA;QACpC,CAAC;QACD,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACtC,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC;gBAAE,OAAO,IAAI,CAAA;QACpC,CAAC;QACD,OAAO,KAAK,CAAA;IACd,CAAC;CACF;AAvGD,wBAuGC","sourcesContent":["// give it a pattern, and it'll be able to tell you if\n// a given path should be ignored.\n// Ignoring a path ignores its children if the pattern ends in /**\n// Ignores are always parsed in dot:true mode\n\nimport { Minimatch, MinimatchOptions } from 'minimatch'\nimport { Path } from 'path-scurry'\nimport { Pattern } from './pattern.js'\nimport { GlobWalkerOpts } from './walker.js'\n\nexport interface IgnoreLike {\n  ignored?: (p: Path) => boolean\n  childrenIgnored?: (p: Path) => boolean\n  add?: (ignore: string) => void\n}\n\nconst defaultPlatform: NodeJS.Platform =\n  (\n    typeof process === 'object' &&\n    process &&\n    typeof process.platform === 'string'\n  ) ?\n    process.platform\n  : 'linux'\n\n/**\n * Class used to process ignored patterns\n */\nexport class Ignore implements IgnoreLike {\n  relative: Minimatch[]\n  relativeChildren: Minimatch[]\n  absolute: Minimatch[]\n  absoluteChildren: Minimatch[]\n  platform: NodeJS.Platform\n  mmopts: MinimatchOptions\n\n  constructor(\n    ignored: string[],\n    {\n      nobrace,\n      nocase,\n      noext,\n      noglobstar,\n      platform = defaultPlatform,\n    }: GlobWalkerOpts,\n  ) {\n    this.relative = []\n    this.absolute = []\n    this.relativeChildren = []\n    this.absoluteChildren = []\n    this.platform = platform\n    this.mmopts = {\n      dot: true,\n      nobrace,\n      nocase,\n      noext,\n      noglobstar,\n      optimizationLevel: 2,\n      platform,\n      nocomment: true,\n      nonegate: true,\n    }\n    for (const ign of ignored) this.add(ign)\n  }\n\n  add(ign: string) {\n    // this is a little weird, but it gives us a clean set of optimized\n    // minimatch matchers, without getting tripped up if one of them\n    // ends in /** inside a brace section, and it's only inefficient at\n    // the start of the walk, not along it.\n    // It'd be nice if the Pattern class just had a .test() method, but\n    // handling globstars is a bit of a pita, and that code already lives\n    // in minimatch anyway.\n    // Another way would be if maybe Minimatch could take its set/globParts\n    // as an option, and then we could at least just use Pattern to test\n    // for absolute-ness.\n    // Yet another way, Minimatch could take an array of glob strings, and\n    // a cwd option, and do the right thing.\n    const mm = new Minimatch(ign, this.mmopts)\n    for (let i = 0; i < mm.set.length; i++) {\n      const parsed = mm.set[i]\n      const globParts = mm.globParts[i]\n      /* c8 ignore start */\n      if (!parsed || !globParts) {\n        throw new Error('invalid pattern object')\n      }\n      // strip off leading ./ portions\n      // https://github.com/isaacs/node-glob/issues/570\n      while (parsed[0] === '.' && globParts[0] === '.') {\n        parsed.shift()\n        globParts.shift()\n      }\n      /* c8 ignore stop */\n      const p = new Pattern(parsed, globParts, 0, this.platform)\n      const m = new Minimatch(p.globString(), this.mmopts)\n      const children = globParts[globParts.length - 1] === '**'\n      const absolute = p.isAbsolute()\n      if (absolute) this.absolute.push(m)\n      else this.relative.push(m)\n      if (children) {\n        if (absolute) this.absoluteChildren.push(m)\n        else this.relativeChildren.push(m)\n      }\n    }\n  }\n\n  ignored(p: Path): boolean {\n    const fullpath = p.fullpath()\n    const fullpaths = `${fullpath}/`\n    const relative = p.relative() || '.'\n    const relatives = `${relative}/`\n    for (const m of this.relative) {\n      if (m.match(relative) || m.match(relatives)) return true\n    }\n    for (const m of this.absolute) {\n      if (m.match(fullpath) || m.match(fullpaths)) return true\n    }\n    return false\n  }\n\n  childrenIgnored(p: Path): boolean {\n    const fullpath = p.fullpath() + '/'\n    const relative = (p.relative() || '.') + '/'\n    for (const m of this.relativeChildren) {\n      if (m.match(relative)) return true\n    }\n    for (const m of this.absoluteChildren) {\n      if (m.match(fullpath)) return true\n    }\n    return false\n  }\n}\n"]}PK~\V%%glob/dist/esm/bin.mjsnu[#!/usr/bin/env node
import { foregroundChild } from 'foreground-child';
import { existsSync } from 'fs';
import { readFile } from 'fs/promises';
import { jack } from 'jackspeak';
import { join } from 'path';
import { fileURLToPath } from 'url';
import { globStream } from './index.js';
/* c8 ignore start */
const { version } = JSON.parse(await readFile(fileURLToPath(new URL('../../package.json', import.meta.url)), 'utf8').catch(() => readFile(fileURLToPath(new URL('../../package.json', import.meta.url)), 'utf8')));
/* c8 ignore stop */
const j = jack({
    usage: 'glob [options] [ [ ...]]',
})
    .description(`
    Glob v${version}

    Expand the positional glob expression arguments into any matching file
    system paths found.
  `)
    .opt({
    cmd: {
        short: 'c',
        hint: 'command',
        description: `Run the command provided, passing the glob expression
                    matches as arguments.`,
    },
})
    .opt({
    default: {
        short: 'p',
        hint: 'pattern',
        description: `If no positional arguments are provided, glob will use
                    this pattern`,
    },
})
    .flag({
    all: {
        short: 'A',
        description: `By default, the glob cli command will not expand any
                    arguments that are an exact match to a file on disk.

                    This prevents double-expanding, in case the shell expands
                    an argument whose filename is a glob expression.

                    For example, if 'app/*.ts' would match 'app/[id].ts', then
                    on Windows powershell or cmd.exe, 'glob app/*.ts' will
                    expand to 'app/[id].ts', as expected. However, in posix
                    shells such as bash or zsh, the shell will first expand
                    'app/*.ts' to a list of filenames. Then glob will look
                    for a file matching 'app/[id].ts' (ie, 'app/i.ts' or
                    'app/d.ts'), which is unexpected.

                    Setting '--all' prevents this behavior, causing glob
                    to treat ALL patterns as glob expressions to be expanded,
                    even if they are an exact match to a file on disk.

                    When setting this option, be sure to enquote arguments
                    so that the shell will not expand them prior to passing
                    them to the glob command process.
      `,
    },
    absolute: {
        short: 'a',
        description: 'Expand to absolute paths',
    },
    'dot-relative': {
        short: 'd',
        description: `Prepend './' on relative matches`,
    },
    mark: {
        short: 'm',
        description: `Append a / on any directories matched`,
    },
    posix: {
        short: 'x',
        description: `Always resolve to posix style paths, using '/' as the
                    directory separator, even on Windows. Drive letter
                    absolute matches on Windows will be expanded to their
                    full resolved UNC maths, eg instead of 'C:\\foo\\bar',
                    it will expand to '//?/C:/foo/bar'.
      `,
    },
    follow: {
        short: 'f',
        description: `Follow symlinked directories when expanding '**'`,
    },
    realpath: {
        short: 'R',
        description: `Call 'fs.realpath' on all of the results. In the case
                    of an entry that cannot be resolved, the entry is
                    omitted. This incurs a slight performance penalty, of
                    course, because of the added system calls.`,
    },
    stat: {
        short: 's',
        description: `Call 'fs.lstat' on all entries, whether required or not
                    to determine if it's a valid match.`,
    },
    'match-base': {
        short: 'b',
        description: `Perform a basename-only match if the pattern does not
                    contain any slash characters. That is, '*.js' would be
                    treated as equivalent to '**/*.js', matching js files
                    in all directories.
      `,
    },
    dot: {
        description: `Allow patterns to match files/directories that start
                    with '.', even if the pattern does not start with '.'
      `,
    },
    nobrace: {
        description: 'Do not expand {...} patterns',
    },
    nocase: {
        description: `Perform a case-insensitive match. This defaults to
                    'true' on macOS and Windows platforms, and false on
                    all others.

                    Note: 'nocase' should only be explicitly set when it is
                    known that the filesystem's case sensitivity differs
                    from the platform default. If set 'true' on
                    case-insensitive file systems, then the walk may return
                    more or less results than expected.
      `,
    },
    nodir: {
        description: `Do not match directories, only files.

                    Note: to *only* match directories, append a '/' at the
                    end of the pattern.
      `,
    },
    noext: {
        description: `Do not expand extglob patterns, such as '+(a|b)'`,
    },
    noglobstar: {
        description: `Do not expand '**' against multiple path portions.
                    Ie, treat it as a normal '*' instead.`,
    },
    'windows-path-no-escape': {
        description: `Use '\\' as a path separator *only*, and *never* as an
                    escape character. If set, all '\\' characters are
                    replaced with '/' in the pattern.`,
    },
})
    .num({
    'max-depth': {
        short: 'D',
        description: `Maximum depth to traverse from the current
                    working directory`,
    },
})
    .opt({
    cwd: {
        short: 'C',
        description: 'Current working directory to execute/match in',
        default: process.cwd(),
    },
    root: {
        short: 'r',
        description: `A string path resolved against the 'cwd', which is
                    used as the starting point for absolute patterns that
                    start with '/' (but not drive letters or UNC paths
                    on Windows).

                    Note that this *doesn't* necessarily limit the walk to
                    the 'root' directory, and doesn't affect the cwd
                    starting point for non-absolute patterns. A pattern
                    containing '..' will still be able to traverse out of
                    the root directory, if it is not an actual root directory
                    on the filesystem, and any non-absolute patterns will
                    still be matched in the 'cwd'.

                    To start absolute and non-absolute patterns in the same
                    path, you can use '--root=' to set it to the empty
                    string. However, be aware that on Windows systems, a
                    pattern like 'x:/*' or '//host/share/*' will *always*
                    start in the 'x:/' or '//host/share/' directory,
                    regardless of the --root setting.
      `,
    },
    platform: {
        description: `Defaults to the value of 'process.platform' if
                    available, or 'linux' if not. Setting --platform=win32
                    on non-Windows systems may cause strange behavior!`,
        validOptions: [
            'aix',
            'android',
            'darwin',
            'freebsd',
            'haiku',
            'linux',
            'openbsd',
            'sunos',
            'win32',
            'cygwin',
            'netbsd',
        ],
    },
})
    .optList({
    ignore: {
        short: 'i',
        description: `Glob patterns to ignore`,
    },
})
    .flag({
    debug: {
        short: 'v',
        description: `Output a huge amount of noisy debug information about
                    patterns as they are parsed and used to match files.`,
    },
})
    .flag({
    help: {
        short: 'h',
        description: 'Show this usage information',
    },
});
try {
    const { positionals, values } = j.parse();
    if (values.help) {
        console.log(j.usage());
        process.exit(0);
    }
    if (positionals.length === 0 && !values.default)
        throw 'No patterns provided';
    if (positionals.length === 0 && values.default)
        positionals.push(values.default);
    const patterns = values.all ? positionals : positionals.filter(p => !existsSync(p));
    const matches = values.all ?
        []
        : positionals.filter(p => existsSync(p)).map(p => join(p));
    const stream = globStream(patterns, {
        absolute: values.absolute,
        cwd: values.cwd,
        dot: values.dot,
        dotRelative: values['dot-relative'],
        follow: values.follow,
        ignore: values.ignore,
        mark: values.mark,
        matchBase: values['match-base'],
        maxDepth: values['max-depth'],
        nobrace: values.nobrace,
        nocase: values.nocase,
        nodir: values.nodir,
        noext: values.noext,
        noglobstar: values.noglobstar,
        platform: values.platform,
        realpath: values.realpath,
        root: values.root,
        stat: values.stat,
        debug: values.debug,
        posix: values.posix,
    });
    const cmd = values.cmd;
    if (!cmd) {
        matches.forEach(m => console.log(m));
        stream.on('data', f => console.log(f));
    }
    else {
        stream.on('data', f => matches.push(f));
        stream.on('end', () => foregroundChild(cmd, matches, { shell: true }));
    }
}
catch (e) {
    console.error(j.usage());
    console.error(e instanceof Error ? e.message : String(e));
    process.exit(1);
}
//# sourceMappingURL=bin.mjs.mapPK~\ddglob/dist/esm/walker.d.ts.mapnu[{"version":3,"file":"walker.d.ts","sourceRoot":"","sources":["../../src/walker.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AACnC,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,EAAU,UAAU,EAAE,MAAM,aAAa,CAAA;AAOhD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AACtC,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAE1C,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,kBAAkB,CAAC,EAAE,OAAO,CAAA;IAC5B,GAAG,CAAC,EAAE,MAAM,GAAG,GAAG,CAAA;IAClB,GAAG,CAAC,EAAE,OAAO,CAAA;IACb,WAAW,CAAC,EAAE,OAAO,CAAA;IACrB,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,UAAU,CAAA;IACvC,IAAI,CAAC,EAAE,OAAO,CAAA;IACd,SAAS,CAAC,EAAE,OAAO,CAAA;IAGnB,QAAQ,CAAC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BrC,QAAQ,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;CAW3B;AAED,qBAAa,UAAU,CACrB,CAAC,SAAS,cAAc,GAAG,cAAc,CACzC,SAAQ,QAAQ,CAAC,CAAC,CAAC;IACnB,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,CAAA;gBAE3B,QAAQ,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IAUpD,SAAS,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,GAAG,IAAI;IAK7B,MAAM,IAAI,WAAW,CAAC,CAAC,CAAC;IAYxB,UAAU,IAAI,WAAW,CAAC,CAAC,CAAC;CAO7B"}PK~\~iiglob/dist/esm/bin.d.mts.mapnu[{"version":3,"file":"bin.d.mts","sourceRoot":"","sources":["../../src/bin.mts"],"names":[],"mappings":""}PK~\:AAglob/dist/esm/bin.d.mtsnu[#!/usr/bin/env node
export {};
//# sourceMappingURL=bin.d.mts.mapPK~\xglob/dist/esm/package.jsonnu[{
  "type": "module"
}
PK~\[glob/dist/esm/has-magic.js.mapnu[{"version":3,"file":"has-magic.js","sourceRoot":"","sources":["../../src/has-magic.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAA;AAGrC;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,CACtB,OAA0B,EAC1B,UAAuB,EAAE,EAChB,EAAE;IACX,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QAC5B,OAAO,GAAG,CAAC,OAAO,CAAC,CAAA;IACrB,CAAC;IACD,KAAK,MAAM,CAAC,IAAI,OAAO,EAAE,CAAC;QACxB,IAAI,IAAI,SAAS,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,QAAQ,EAAE;YAAE,OAAO,IAAI,CAAA;IACvD,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC,CAAA","sourcesContent":["import { Minimatch } from 'minimatch'\nimport { GlobOptions } from './glob.js'\n\n/**\n * Return true if the patterns provided contain any magic glob characters,\n * given the options provided.\n *\n * Brace expansion is not considered \"magic\" unless the `magicalBraces` option\n * is set, as brace expansion just turns one string into an array of strings.\n * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and\n * `'xby'` both do not contain any magic glob characters, and it's treated the\n * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true`\n * is in the options, brace expansion _is_ treated as a pattern having magic.\n */\nexport const hasMagic = (\n  pattern: string | string[],\n  options: GlobOptions = {},\n): boolean => {\n  if (!Array.isArray(pattern)) {\n    pattern = [pattern]\n  }\n  for (const p of pattern) {\n    if (new Minimatch(p, options).hasMagic()) return true\n  }\n  return false\n}\n"]}PK~\oglob/dist/esm/index.d.ts.mapnu[{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AACnC,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,KAAK,EACV,WAAW,EACX,6BAA6B,EAC7B,4BAA4B,EAC5B,6BAA6B,EAC9B,MAAM,WAAW,CAAA;AAClB,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAGhC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AAC5C,YAAY,EACV,QAAQ,EACR,IAAI,EACJ,WAAW,EACX,4BAA4B,EAC5B,6BAA6B,GAC9B,MAAM,aAAa,CAAA;AACpB,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,YAAY,EACV,WAAW,EACX,6BAA6B,EAC7B,4BAA4B,EAC5B,6BAA6B,GAC9B,MAAM,WAAW,CAAA;AAClB,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAA;A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AI,EAAE,CAAC;YACV,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAA;QACtC,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,CAAA;QAC5B,CAAC;IACH,CAAC;CACF","sourcesContent":["// synchronous utility for filtering entries and calculating subwalks\n\nimport { GLOBSTAR, MMRegExp } from 'minimatch'\nimport { Path } from 'path-scurry'\nimport { MMPattern, Pattern } from './pattern.js'\nimport { GlobWalkerOpts } from './walker.js'\n\n/**\n * A cache of which patterns have been processed for a given Path\n */\nexport class HasWalkedCache {\n  store: Map>\n  constructor(store: Map> = new Map()) {\n    this.store = store\n  }\n  copy() {\n    return new HasWalkedCache(new Map(this.store))\n  }\n  hasWalked(target: Path, pattern: Pattern) {\n    return this.store.get(target.fullpath())?.has(pattern.globString())\n  }\n  storeWalked(target: Path, pattern: Pattern) {\n    const fullpath = target.fullpath()\n    const cached = this.store.get(fullpath)\n    if (cached) cached.add(pattern.globString())\n    else this.store.set(fullpath, new Set([pattern.globString()]))\n  }\n}\n\n/**\n * A record of which paths have been matched in a given walk step,\n * and whether they only are considered a match if they are a directory,\n * and whether their absolute or relative path should be returned.\n */\nexport class MatchRecord {\n  store: Map = new Map()\n  add(target: Path, absolute: boolean, ifDir: boolean) {\n    const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0)\n    const current = this.store.get(target)\n    this.store.set(target, current === undefined ? n : n & current)\n  }\n  // match, absolute, ifdir\n  entries(): [Path, boolean, boolean][] {\n    return [...this.store.entries()].map(([path, n]) => [\n      path,\n      !!(n & 2),\n      !!(n & 1),\n    ])\n  }\n}\n\n/**\n * A collection of patterns that must be processed in a subsequent step\n * for a given path.\n */\nexport class SubWalks {\n  store: Map = new Map()\n  add(target: Path, pattern: Pattern) {\n    if (!target.canReaddir()) {\n      return\n    }\n    const subs = this.store.get(target)\n    if (subs) {\n      if (!subs.find(p => p.globString() === pattern.globString())) {\n        subs.push(pattern)\n      }\n    } else this.store.set(target, [pattern])\n  }\n  get(target: Path): Pattern[] {\n    const subs = this.store.get(target)\n    /* c8 ignore start */\n    if (!subs) {\n      throw new Error('attempting to walk unknown path')\n    }\n    /* c8 ignore stop */\n    return subs\n  }\n  entries(): [Path, Pattern[]][] {\n    return this.keys().map(k => [k, this.store.get(k) as Pattern[]])\n  }\n  keys(): Path[] {\n    return [...this.store.keys()].filter(t => t.canReaddir())\n  }\n}\n\n/**\n * The class that processes patterns for a given path.\n *\n * Handles child entry filtering, and determining whether a path's\n * directory contents must be read.\n */\nexport class Processor {\n  hasWalkedCache: HasWalkedCache\n  matches = new MatchRecord()\n  subwalks = new SubWalks()\n  patterns?: Pattern[]\n  follow: boolean\n  dot: boolean\n  opts: GlobWalkerOpts\n\n  constructor(opts: GlobWalkerOpts, hasWalkedCache?: HasWalkedCache) {\n    this.opts = opts\n    this.follow = !!opts.follow\n    this.dot = !!opts.dot\n    this.hasWalkedCache =\n      hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache()\n  }\n\n  processPatterns(target: Path, patterns: Pattern[]) {\n    this.patterns = patterns\n    const processingSet: [Path, Pattern][] = patterns.map(p => [target, p])\n\n    // map of paths to the magic-starting subwalks they need to walk\n    // first item in patterns is the filter\n\n    for (let [t, pattern] of processingSet) {\n      this.hasWalkedCache.storeWalked(t, pattern)\n\n      const root = pattern.root()\n      const absolute = pattern.isAbsolute() && this.opts.absolute !== false\n\n      // start absolute patterns at root\n      if (root) {\n        t = t.resolve(\n          root === '/' && this.opts.root !== undefined ?\n            this.opts.root\n          : root,\n        )\n        const rest = pattern.rest()\n        if (!rest) {\n          this.matches.add(t, true, false)\n          continue\n        } else {\n          pattern = rest\n        }\n      }\n\n      if (t.isENOENT()) continue\n\n      let p: MMPattern\n      let rest: Pattern | null\n      let changed = false\n      while (\n        typeof (p = pattern.pattern()) === 'string' &&\n        (rest = pattern.rest())\n      ) {\n        const c = t.resolve(p)\n        t = c\n        pattern = rest\n        changed = true\n      }\n      p = pattern.pattern()\n      rest = pattern.rest()\n      if (changed) {\n        if (this.hasWalkedCache.hasWalked(t, pattern)) continue\n        this.hasWalkedCache.storeWalked(t, pattern)\n      }\n\n      // now we have either a final string for a known entry,\n      // more strings for an unknown entry,\n      // or a pattern starting with magic, mounted on t.\n      if (typeof p === 'string') {\n        // must not be final entry, otherwise we would have\n        // concatenated it earlier.\n        const ifDir = p === '..' || p === '' || p === '.'\n        this.matches.add(t.resolve(p), absolute, ifDir)\n        continue\n      } else if (p === GLOBSTAR) {\n        // if no rest, match and subwalk pattern\n        // if rest, process rest and subwalk pattern\n        // if it's a symlink, but we didn't get here by way of a\n        // globstar match (meaning it's the first time THIS globstar\n        // has traversed a symlink), then we follow it. Otherwise, stop.\n        if (\n          !t.isSymbolicLink() ||\n          this.follow ||\n          pattern.checkFollowGlobstar()\n        ) {\n          this.subwalks.add(t, pattern)\n        }\n        const rp = rest?.pattern()\n        const rrest = rest?.rest()\n        if (!rest || ((rp === '' || rp === '.') && !rrest)) {\n          // only HAS to be a dir if it ends in **/ or **/.\n          // but ending in ** will match files as well.\n          this.matches.add(t, absolute, rp === '' || rp === '.')\n        } else {\n          if (rp === '..') {\n            // this would mean you're matching **/.. at the fs root,\n            // and no thanks, I'm not gonna test that specific case.\n            /* c8 ignore start */\n            const tp = t.parent || t\n            /* c8 ignore stop */\n            if (!rrest) this.matches.add(tp, absolute, true)\n            else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {\n              this.subwalks.add(tp, rrest)\n            }\n          }\n        }\n      } else if (p instanceof RegExp) {\n        this.subwalks.add(t, pattern)\n      }\n    }\n\n    return this\n  }\n\n  subwalkTargets(): Path[] {\n    return this.subwalks.keys()\n  }\n\n  child() {\n    return new Processor(this.opts, this.hasWalkedCache)\n  }\n\n  // return a new Processor containing the subwalks for each\n  // child entry, and a set of matches, and\n  // a hasWalkedCache that's a copy of this one\n  // then we're going to call\n  filterEntries(parent: Path, entries: Path[]): Processor {\n    const patterns = this.subwalks.get(parent)\n    // put matches and entry walks into the results processor\n    const results = this.child()\n    for (const e of entries) {\n      for (const pattern of patterns) {\n        const absolute = pattern.isAbsolute()\n        const p = pattern.pattern()\n        const rest = pattern.rest()\n        if (p === GLOBSTAR) {\n          results.testGlobstar(e, pattern, rest, absolute)\n        } else if (p instanceof RegExp) {\n          results.testRegExp(e, p, rest, absolute)\n        } else {\n          results.testString(e, p, rest, absolute)\n        }\n      }\n    }\n    return results\n  }\n\n  testGlobstar(\n    e: Path,\n    pattern: Pattern,\n    rest: Pattern | null,\n    absolute: boolean,\n  ) {\n    if (this.dot || !e.name.startsWith('.')) {\n      if (!pattern.hasMore()) {\n        this.matches.add(e, absolute, false)\n      }\n      if (e.canReaddir()) {\n        // if we're in follow mode or it's not a symlink, just keep\n        // testing the same pattern. If there's more after the globstar,\n        // then this symlink consumes the globstar. If not, then we can\n        // follow at most ONE symlink along the way, so we mark it, which\n        // also checks to ensure that it wasn't already marked.\n        if (this.follow || !e.isSymbolicLink()) {\n          this.subwalks.add(e, pattern)\n        } else if (e.isSymbolicLink()) {\n          if (rest && pattern.checkFollowGlobstar()) {\n            this.subwalks.add(e, rest)\n          } else if (pattern.markFollowGlobstar()) {\n            this.subwalks.add(e, pattern)\n          }\n        }\n      }\n    }\n    // if the NEXT thing matches this entry, then also add\n    // the rest.\n    if (rest) {\n      const rp = rest.pattern()\n      if (\n        typeof rp === 'string' &&\n        // dots and empty were handled already\n        rp !== '..' &&\n        rp !== '' &&\n        rp !== '.'\n      ) {\n        this.testString(e, rp, rest.rest(), absolute)\n      } else if (rp === '..') {\n        /* c8 ignore start */\n        const ep = e.parent || e\n        /* c8 ignore stop */\n        this.subwalks.add(ep, rest)\n      } else if (rp instanceof RegExp) {\n        this.testRegExp(e, rp, rest.rest(), absolute)\n      }\n    }\n  }\n\n  testRegExp(\n    e: Path,\n    p: MMRegExp,\n    rest: Pattern | null,\n    absolute: boolean,\n  ) {\n    if (!p.test(e.name)) return\n    if (!rest) {\n      this.matches.add(e, absolute, false)\n    } else {\n      this.subwalks.add(e, rest)\n    }\n  }\n\n  testString(e: Path, p: string, rest: Pattern | null, absolute: boolean) {\n    // should never happen?\n    if (!e.isNamed(p)) return\n    if (!rest) {\n      this.matches.add(e, absolute, false)\n    } else {\n      this.subwalks.add(e, rest)\n    }\n  }\n}\n"]}PK~\Zrglob/dist/esm/walker.d.tsnu[/// 
/**
 * Single-use utility classes to provide functionality to the {@link Glob}
 * methods.
 *
 * @module
 */
import { Minipass } from 'minipass';
import { Path } from 'path-scurry';
import { IgnoreLike } from './ignore.js';
import { Pattern } from './pattern.js';
import { Processor } from './processor.js';
export interface GlobWalkerOpts {
    absolute?: boolean;
    allowWindowsEscape?: boolean;
    cwd?: string | URL;
    dot?: boolean;
    dotRelative?: boolean;
    follow?: boolean;
    ignore?: string | string[] | IgnoreLike;
    mark?: boolean;
    matchBase?: boolean;
    maxDepth?: number;
    nobrace?: boolean;
    nocase?: boolean;
    nodir?: boolean;
    noext?: boolean;
    noglobstar?: boolean;
    platform?: NodeJS.Platform;
    posix?: boolean;
    realpath?: boolean;
    root?: string;
    stat?: boolean;
    signal?: AbortSignal;
    windowsPathsNoEscape?: boolean;
    withFileTypes?: boolean;
    includeChildMatches?: boolean;
}
export type GWOFileTypesTrue = GlobWalkerOpts & {
    withFileTypes: true;
};
export type GWOFileTypesFalse = GlobWalkerOpts & {
    withFileTypes: false;
};
export type GWOFileTypesUnset = GlobWalkerOpts & {
    withFileTypes?: undefined;
};
export type Result = O extends GWOFileTypesTrue ? Path : O extends GWOFileTypesFalse ? string : O extends GWOFileTypesUnset ? string : Path | string;
export type Matches = O extends GWOFileTypesTrue ? Set : O extends GWOFileTypesFalse ? Set : O extends GWOFileTypesUnset ? Set : Set;
export type MatchStream = Minipass, Result>;
/**
 * basic walking utilities that all the glob walker types use
 */
export declare abstract class GlobUtil {
    #private;
    path: Path;
    patterns: Pattern[];
    opts: O;
    seen: Set;
    paused: boolean;
    aborted: boolean;
    signal?: AbortSignal;
    maxDepth: number;
    includeChildMatches: boolean;
    constructor(patterns: Pattern[], path: Path, opts: O);
    pause(): void;
    resume(): void;
    onResume(fn: () => any): void;
    matchCheck(e: Path, ifDir: boolean): Promise;
    matchCheckTest(e: Path | undefined, ifDir: boolean): Path | undefined;
    matchCheckSync(e: Path, ifDir: boolean): Path | undefined;
    abstract matchEmit(p: Result): void;
    abstract matchEmit(p: string | Path): void;
    matchFinish(e: Path, absolute: boolean): void;
    match(e: Path, absolute: boolean, ifDir: boolean): Promise;
    matchSync(e: Path, absolute: boolean, ifDir: boolean): void;
    walkCB(target: Path, patterns: Pattern[], cb: () => any): void;
    walkCB2(target: Path, patterns: Pattern[], processor: Processor, cb: () => any): any;
    walkCB3(target: Path, entries: Path[], processor: Processor, cb: () => any): void;
    walkCBSync(target: Path, patterns: Pattern[], cb: () => any): void;
    walkCB2Sync(target: Path, patterns: Pattern[], processor: Processor, cb: () => any): any;
    walkCB3Sync(target: Path, entries: Path[], processor: Processor, cb: () => any): void;
}
export declare class GlobWalker extends GlobUtil {
    matches: Set>;
    constructor(patterns: Pattern[], path: Path, opts: O);
    matchEmit(e: Result): void;
    walk(): Promise>>;
    walkSync(): Set>;
}
export declare class GlobStream extends GlobUtil {
    results: Minipass, Result>;
    constructor(patterns: Pattern[], path: Path, opts: O);
    matchEmit(e: Result): void;
    stream(): MatchStream;
    streamSync(): MatchStream;
}
//# sourceMappingURL=walker.d.ts.mapPK~\2glob/dist/esm/has-magic.jsnu[import { Minimatch } from 'minimatch';
/**
 * Return true if the patterns provided contain any magic glob characters,
 * given the options provided.
 *
 * Brace expansion is not considered "magic" unless the `magicalBraces` option
 * is set, as brace expansion just turns one string into an array of strings.
 * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and
 * `'xby'` both do not contain any magic glob characters, and it's treated the
 * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true`
 * is in the options, brace expansion _is_ treated as a pattern having magic.
 */
export const hasMagic = (pattern, options = {}) => {
    if (!Array.isArray(pattern)) {
        pattern = [pattern];
    }
    for (const p of pattern) {
        if (new Minimatch(p, options).hasMagic())
            return true;
    }
    return false;
};
//# sourceMappingURL=has-magic.js.mapPK~\25wwglob/dist/esm/ignore.d.ts.mapnu[{"version":3,"file":"ignore.d.ts","sourceRoot":"","sources":["../../src/ignore.ts"],"names":[],"mappings":";AAKA,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAA;AACvD,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAElC,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAE5C,MAAM,WAAW,UAAU;IACzB,OAAO,CAAC,EAAE,CAAC,CAAC,EAAE,IAAI,KAAK,OAAO,CAAA;IAC9B,eAAe,CAAC,EAAE,CAAC,CAAC,EAAE,IAAI,KAAK,OAAO,CAAA;IACtC,GAAG,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,CAAA;CAC/B;AAWD;;GAEG;AACH,qBAAa,MAAO,YAAW,UAAU;IACvC,QAAQ,EAAE,SAAS,EAAE,CAAA;IACrB,gBAAgB,EAAE,SAAS,EAAE,CAAA;IAC7B,QAAQ,EAAE,SAAS,EAAE,CAAA;IACrB,gBAAgB,EAAE,SAAS,EAAE,CAAA;IAC7B,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAA;IACzB,MAAM,EAAE,gBAAgB,CAAA;gBAGtB,OAAO,EAAE,MAAM,EAAE,EACjB,EACE,OAAO,EACP,MAAM,EACN,KAAK,EACL,UAAU,EACV,QAA0B,GAC3B,EAAE,cAAc;IAqBnB,GAAG,CAAC,GAAG,EAAE,MAAM;IAyCf,OAAO,CAAC,CAAC,EAAE,IAAI,GAAG,OAAO;IAczB,eAAe,CAAC,CAAC,EAAE,IAAI,GAAG,OAAO;CAWlC"}PK~\/^}}glob/dist/esm/pattern.d.tsnu[/// 
import { GLOBSTAR } from 'minimatch';
export type MMPattern = string | RegExp | typeof GLOBSTAR;
export type PatternList = [p: MMPattern, ...rest: MMPattern[]];
export type UNCPatternList = [
    p0: '',
    p1: '',
    p2: string,
    p3: string,
    ...rest: MMPattern[]
];
export type DrivePatternList = [p0: string, ...rest: MMPattern[]];
export type AbsolutePatternList = [p0: '', ...rest: MMPattern[]];
export type GlobList = [p: string, ...rest: string[]];
/**
 * An immutable-ish view on an array of glob parts and their parsed
 * results
 */
export declare class Pattern {
    #private;
    readonly length: number;
    constructor(patternList: MMPattern[], globList: string[], index: number, platform: NodeJS.Platform);
    /**
     * The first entry in the parsed list of patterns
     */
    pattern(): MMPattern;
    /**
     * true of if pattern() returns a string
     */
    isString(): boolean;
    /**
     * true of if pattern() returns GLOBSTAR
     */
    isGlobstar(): boolean;
    /**
     * true if pattern() returns a regexp
     */
    isRegExp(): boolean;
    /**
     * The /-joined set of glob parts that make up this pattern
     */
    globString(): string;
    /**
     * true if there are more pattern parts after this one
     */
    hasMore(): boolean;
    /**
     * The rest of the pattern after this part, or null if this is the end
     */
    rest(): Pattern | null;
    /**
     * true if the pattern represents a //unc/path/ on windows
     */
    isUNC(): boolean;
    /**
     * True if the pattern starts with a drive letter on Windows
     */
    isDrive(): boolean;
    /**
     * True if the pattern is rooted on an absolute path
     */
    isAbsolute(): boolean;
    /**
     * consume the root of the pattern, and return it
     */
    root(): string;
    /**
     * Check to see if the current globstar pattern is allowed to follow
     * a symbolic link.
     */
    checkFollowGlobstar(): boolean;
    /**
     * Mark that the current globstar pattern is following a symbolic link
     */
    markFollowGlobstar(): boolean;
}
//# sourceMappingURL=pattern.d.ts.mapPK~\vNglob/dist/esm/has-magic.d.tsnu[import { GlobOptions } from './glob.js';
/**
 * Return true if the patterns provided contain any magic glob characters,
 * given the options provided.
 *
 * Brace expansion is not considered "magic" unless the `magicalBraces` option
 * is set, as brace expansion just turns one string into an array of strings.
 * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and
 * `'xby'` both do not contain any magic glob characters, and it's treated the
 * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true`
 * is in the options, brace expansion _is_ treated as a pattern having magic.
 */
export declare const hasMagic: (pattern: string | string[], options?: GlobOptions) => boolean;
//# sourceMappingURL=has-magic.d.ts.mapPK~\`8_ glob/dist/esm/processor.d.ts.mapnu[{"version":3,"file":"processor.d.ts","sourceRoot":"","sources":["../../src/processor.ts"],"names":[],"mappings":"AAEA,OAAO,EAAY,QAAQ,EAAE,MAAM,WAAW,CAAA;AAC9C,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,EAAa,OAAO,EAAE,MAAM,cAAc,CAAA;AACjD,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAE5C;;GAEG;AACH,qBAAa,cAAc;IACzB,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAA;gBACnB,KAAK,GAAE,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAa;IAGvD,IAAI;IAGJ,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO;IAGxC,WAAW,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO;CAM3C;AAED;;;;GAIG;AACH,qBAAa,WAAW;IACtB,KAAK,EAAE,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,CAAY;IACpC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO;IAMnD,OAAO,IAAI,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE;CAOtC;AAED;;;GAGG;AACH,qBAAa,QAAQ;IACnB,KAAK,EAAE,GAAG,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,CAAY;IACvC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO;IAWlC,GAAG,CAAC,MAAM,EAAE,IAAI,GAAG,OAAO,EAAE;IAS5B,OAAO,IAAI,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE;IAG9B,IAAI,IAAI,IAAI,EAAE;CAGf;AAED;;;;;GAKG;AACH,qBAAa,SAAS;IACpB,cAAc,EAAE,cAAc,CAAA;IAC9B,OAAO,cAAoB;IAC3B,QAAQ,WAAiB;IACzB,QAAQ,CAAC,EAAE,OAAO,EAAE,CAAA;IACpB,MAAM,EAAE,OAAO,CAAA;IACf,GAAG,EAAE,OAAO,CAAA;IACZ,IAAI,EAAE,cAAc,CAAA;gBAER,IAAI,EAAE,cAAc,EAAE,cAAc,CAAC,EAAE,cAAc;IAQjE,eAAe,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE;IAmGjD,cAAc,IAAI,IAAI,EAAE;IAIxB,KAAK;IAQL,aAAa,CAAC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,SAAS;IAqBvD,YAAY,CACV,CAAC,EAAE,IAAI,EACP,OAAO,EAAE,OAAO,EAChB,IAAI,EAAE,OAAO,GAAG,IAAI,EACpB,QAAQ,EAAE,OAAO;IA8CnB,UAAU,CACR,CAAC,EAAE,IAAI,EACP,CAAC,EAAE,QAAQ,EACX,IAAI,EAAE,OAAO,GAAG,IAAI,EACpB,QAAQ,EAAE,OAAO;IAUnB,UAAU,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,IAAI,EAAE,QAAQ,EAAE,OAAO;CASvE"}PK~\δ::glob/dist/esm/glob.d.tsnu[/// 
import { Minimatch } from 'minimatch';
import { Minipass } from 'minipass';
import { FSOption, Path, PathScurry } from 'path-scurry';
import { IgnoreLike } from './ignore.js';
import { Pattern } from './pattern.js';
export type MatchSet = Minimatch['set'];
export type GlobParts = Exclude;
/**
 * A `GlobOptions` object may be provided to any of the exported methods, and
 * must be provided to the `Glob` constructor.
 *
 * All options are optional, boolean, and false by default, unless otherwise
 * noted.
 *
 * All resolved options are added to the Glob object as properties.
 *
 * If you are running many `glob` operations, you can pass a Glob object as the
 * `options` argument to a subsequent operation to share the previously loaded
 * cache.
 */
export interface GlobOptions {
    /**
     * Set to `true` to always receive absolute paths for
     * matched files. Set to `false` to always return relative paths.
     *
     * When this option is not set, absolute paths are returned for patterns
     * that are absolute, and otherwise paths are returned that are relative
     * to the `cwd` setting.
     *
     * This does _not_ make an extra system call to get
     * the realpath, it only does string path resolution.
     *
     * Conflicts with {@link withFileTypes}
     */
    absolute?: boolean;
    /**
     * Set to false to enable {@link windowsPathsNoEscape}
     *
     * @deprecated
     */
    allowWindowsEscape?: boolean;
    /**
     * The current working directory in which to search. Defaults to
     * `process.cwd()`.
     *
     * May be eiher a string path or a `file://` URL object or string.
     */
    cwd?: string | URL;
    /**
     * Include `.dot` files in normal matches and `globstar`
     * matches. Note that an explicit dot in a portion of the pattern
     * will always match dot files.
     */
    dot?: boolean;
    /**
     * Prepend all relative path strings with `./` (or `.\` on Windows).
     *
     * Without this option, returned relative paths are "bare", so instead of
     * returning `'./foo/bar'`, they are returned as `'foo/bar'`.
     *
     * Relative patterns starting with `'../'` are not prepended with `./`, even
     * if this option is set.
     */
    dotRelative?: boolean;
    /**
     * Follow symlinked directories when expanding `**`
     * patterns. This can result in a lot of duplicate references in
     * the presence of cyclic links, and make performance quite bad.
     *
     * By default, a `**` in a pattern will follow 1 symbolic link if
     * it is not the first item in the pattern, or none if it is the
     * first item in the pattern, following the same behavior as Bash.
     */
    follow?: boolean;
    /**
     * string or string[], or an object with `ignore` and `ignoreChildren`
     * methods.
     *
     * If a string or string[] is provided, then this is treated as a glob
     * pattern or array of glob patterns to exclude from matches. To ignore all
     * children within a directory, as well as the entry itself, append `'/**'`
     * to the ignore pattern.
     *
     * **Note** `ignore` patterns are _always_ in `dot:true` mode, regardless of
     * any other settings.
     *
     * If an object is provided that has `ignored(path)` and/or
     * `childrenIgnored(path)` methods, then these methods will be called to
     * determine whether any Path is a match or if its children should be
     * traversed, respectively.
     */
    ignore?: string | string[] | IgnoreLike;
    /**
     * Treat brace expansion like `{a,b}` as a "magic" pattern. Has no
     * effect if {@link nobrace} is set.
     *
     * Only has effect on the {@link hasMagic} function.
     */
    magicalBraces?: boolean;
    /**
     * Add a `/` character to directory matches. Note that this requires
     * additional stat calls in some cases.
     */
    mark?: boolean;
    /**
     * Perform a basename-only match if the pattern does not contain any slash
     * characters. That is, `*.js` would be treated as equivalent to
     * `**\/*.js`, matching all js files in all directories.
     */
    matchBase?: boolean;
    /**
     * Limit the directory traversal to a given depth below the cwd.
     * Note that this does NOT prevent traversal to sibling folders,
     * root patterns, and so on. It only limits the maximum folder depth
     * that the walk will descend, relative to the cwd.
     */
    maxDepth?: number;
    /**
     * Do not expand `{a,b}` and `{1..3}` brace sets.
     */
    nobrace?: boolean;
    /**
     * Perform a case-insensitive match. This defaults to `true` on macOS and
     * Windows systems, and `false` on all others.
     *
     * **Note** `nocase` should only be explicitly set when it is
     * known that the filesystem's case sensitivity differs from the
     * platform default. If set `true` on case-sensitive file
     * systems, or `false` on case-insensitive file systems, then the
     * walk may return more or less results than expected.
     */
    nocase?: boolean;
    /**
     * Do not match directories, only files. (Note: to match
     * _only_ directories, put a `/` at the end of the pattern.)
     */
    nodir?: boolean;
    /**
     * Do not match "extglob" patterns such as `+(a|b)`.
     */
    noext?: boolean;
    /**
     * Do not match `**` against multiple filenames. (Ie, treat it as a normal
     * `*` instead.)
     *
     * Conflicts with {@link matchBase}
     */
    noglobstar?: boolean;
    /**
     * Defaults to value of `process.platform` if available, or `'linux'` if
     * not. Setting `platform:'win32'` on non-Windows systems may cause strange
     * behavior.
     */
    platform?: NodeJS.Platform;
    /**
     * Set to true to call `fs.realpath` on all of the
     * results. In the case of an entry that cannot be resolved, the
     * entry is omitted. This incurs a slight performance penalty, of
     * course, because of the added system calls.
     */
    realpath?: boolean;
    /**
     *
     * A string path resolved against the `cwd` option, which
     * is used as the starting point for absolute patterns that start
     * with `/`, (but not drive letters or UNC paths on Windows).
     *
     * Note that this _doesn't_ necessarily limit the walk to the
     * `root` directory, and doesn't affect the cwd starting point for
     * non-absolute patterns. A pattern containing `..` will still be
     * able to traverse out of the root directory, if it is not an
     * actual root directory on the filesystem, and any non-absolute
     * patterns will be matched in the `cwd`. For example, the
     * pattern `/../*` with `{root:'/some/path'}` will return all
     * files in `/some`, not all files in `/some/path`. The pattern
     * `*` with `{root:'/some/path'}` will return all the entries in
     * the cwd, not the entries in `/some/path`.
     *
     * To start absolute and non-absolute patterns in the same
     * path, you can use `{root:''}`. However, be aware that on
     * Windows systems, a pattern like `x:/*` or `//host/share/*` will
     * _always_ start in the `x:/` or `//host/share` directory,
     * regardless of the `root` setting.
     */
    root?: string;
    /**
     * A [PathScurry](http://npm.im/path-scurry) object used
     * to traverse the file system. If the `nocase` option is set
     * explicitly, then any provided `scurry` object must match this
     * setting.
     */
    scurry?: PathScurry;
    /**
     * Call `lstat()` on all entries, whether required or not to determine
     * if it's a valid match. When used with {@link withFileTypes}, this means
     * that matches will include data such as modified time, permissions, and
     * so on.  Note that this will incur a performance cost due to the added
     * system calls.
     */
    stat?: boolean;
    /**
     * An AbortSignal which will cancel the Glob walk when
     * triggered.
     */
    signal?: AbortSignal;
    /**
     * Use `\\` as a path separator _only_, and
     *  _never_ as an escape character. If set, all `\\` characters are
     *  replaced with `/` in the pattern.
     *
     *  Note that this makes it **impossible** to match against paths
     *  containing literal glob pattern characters, but allows matching
     *  with patterns constructed using `path.join()` and
     *  `path.resolve()` on Windows platforms, mimicking the (buggy!)
     *  behavior of Glob v7 and before on Windows. Please use with
     *  caution, and be mindful of [the caveat below about Windows
     *  paths](#windows). (For legacy reasons, this is also set if
     *  `allowWindowsEscape` is set to the exact value `false`.)
     */
    windowsPathsNoEscape?: boolean;
    /**
     * Return [PathScurry](http://npm.im/path-scurry)
     * `Path` objects instead of strings. These are similar to a
     * NodeJS `Dirent` object, but with additional methods and
     * properties.
     *
     * Conflicts with {@link absolute}
     */
    withFileTypes?: boolean;
    /**
     * An fs implementation to override some or all of the defaults.  See
     * http://npm.im/path-scurry for details about what can be overridden.
     */
    fs?: FSOption;
    /**
     * Just passed along to Minimatch.  Note that this makes all pattern
     * matching operations slower and *extremely* noisy.
     */
    debug?: boolean;
    /**
     * Return `/` delimited paths, even on Windows.
     *
     * On posix systems, this has no effect.  But, on Windows, it means that
     * paths will be `/` delimited, and absolute paths will be their full
     * resolved UNC forms, eg instead of `'C:\\foo\\bar'`, it would return
     * `'//?/C:/foo/bar'`
     */
    posix?: boolean;
    /**
     * Do not match any children of any matches. For example, the pattern
     * `**\/foo` would match `a/foo`, but not `a/foo/b/foo` in this mode.
     *
     * This is especially useful for cases like "find all `node_modules`
     * folders, but not the ones in `node_modules`".
     *
     * In order to support this, the `Ignore` implementation must support an
     * `add(pattern: string)` method. If using the default `Ignore` class, then
     * this is fine, but if this is set to `false`, and a custom `Ignore` is
     * provided that does not have an `add()` method, then it will throw an
     * error.
     *
     * **Caveat** It *only* ignores matches that would be a descendant of a
     * previous match, and only if that descendant is matched *after* the
     * ancestor is encountered. Since the file system walk happens in
     * indeterminate order, it's possible that a match will already be added
     * before its ancestor, if multiple or braced patterns are used.
     *
     * For example:
     *
     * ```ts
     * const results = await glob([
     *   // likely to match first, since it's just a stat
     *   'a/b/c/d/e/f',
     *
     *   // this pattern is more complicated! It must to various readdir()
     *   // calls and test the results against a regular expression, and that
     *   // is certainly going to take a little bit longer.
     *   //
     *   // So, later on, it encounters a match at 'a/b/c/d/e', but it's too
     *   // late to ignore a/b/c/d/e/f, because it's already been emitted.
     *   'a/[bdf]/?/[a-z]/*',
     * ], { includeChildMatches: false })
     * ```
     *
     * It's best to only set this to `false` if you can be reasonably sure that
     * no components of the pattern will potentially match one another's file
     * system descendants, or if the occasional included child entry will not
     * cause problems.
     *
     * @default true
     */
    includeChildMatches?: boolean;
}
export type GlobOptionsWithFileTypesTrue = GlobOptions & {
    withFileTypes: true;
    absolute?: undefined;
    mark?: undefined;
    posix?: undefined;
};
export type GlobOptionsWithFileTypesFalse = GlobOptions & {
    withFileTypes?: false;
};
export type GlobOptionsWithFileTypesUnset = GlobOptions & {
    withFileTypes?: undefined;
};
export type Result = Opts extends GlobOptionsWithFileTypesTrue ? Path : Opts extends GlobOptionsWithFileTypesFalse ? string : Opts extends GlobOptionsWithFileTypesUnset ? string : string | Path;
export type Results = Result[];
export type FileTypes = Opts extends GlobOptionsWithFileTypesTrue ? true : Opts extends GlobOptionsWithFileTypesFalse ? false : Opts extends GlobOptionsWithFileTypesUnset ? false : boolean;
/**
 * An object that can perform glob pattern traversals.
 */
export declare class Glob implements GlobOptions {
    absolute?: boolean;
    cwd: string;
    root?: string;
    dot: boolean;
    dotRelative: boolean;
    follow: boolean;
    ignore?: string | string[] | IgnoreLike;
    magicalBraces: boolean;
    mark?: boolean;
    matchBase: boolean;
    maxDepth: number;
    nobrace: boolean;
    nocase: boolean;
    nodir: boolean;
    noext: boolean;
    noglobstar: boolean;
    pattern: string[];
    platform: NodeJS.Platform;
    realpath: boolean;
    scurry: PathScurry;
    stat: boolean;
    signal?: AbortSignal;
    windowsPathsNoEscape: boolean;
    withFileTypes: FileTypes;
    includeChildMatches: boolean;
    /**
     * The options provided to the constructor.
     */
    opts: Opts;
    /**
     * An array of parsed immutable {@link Pattern} objects.
     */
    patterns: Pattern[];
    /**
     * All options are stored as properties on the `Glob` object.
     *
     * See {@link GlobOptions} for full options descriptions.
     *
     * Note that a previous `Glob` object can be passed as the
     * `GlobOptions` to another `Glob` instantiation to re-use settings
     * and caches with a new pattern.
     *
     * Traversal functions can be called multiple times to run the walk
     * again.
     */
    constructor(pattern: string | string[], opts: Opts);
    /**
     * Returns a Promise that resolves to the results array.
     */
    walk(): Promise>;
    /**
     * synchronous {@link Glob.walk}
     */
    walkSync(): Results;
    /**
     * Stream results asynchronously.
     */
    stream(): Minipass, Result>;
    /**
     * Stream results synchronously.
     */
    streamSync(): Minipass, Result>;
    /**
     * Default sync iteration function. Returns a Generator that
     * iterates over the results.
     */
    iterateSync(): Generator, void, void>;
    [Symbol.iterator](): Generator, void, void>;
    /**
     * Default async iteration function. Returns an AsyncGenerator that
     * iterates over the results.
     */
    iterate(): AsyncGenerator, void, void>;
    [Symbol.asyncIterator](): AsyncGenerator, void, void>;
}
//# sourceMappingURL=glob.d.ts.mapPK~\1m1mglob/dist/esm/walker.js.mapnu[{"version":3,"file":"walker.js","sourceRoot":"","sources":["../../src/walker.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AAEnC,OAAO,EAAE,MAAM,EAAc,MAAM,aAAa,CAAA;AAQhD,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AA0D1C,MAAM,UAAU,GAAG,CACjB,MAAsC,EACtC,IAAoB,EACR,EAAE,CACd,OAAO,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,MAAM,CAAC,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC;IACvD,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC;QAClD,CAAC,CAAC,MAAM,CAAA;AAEV;;GAEG;AACH,MAAM,OAAgB,QAAQ;IAC5B,IAAI,CAAM;IACV,QAAQ,CAAW;IACnB,IAAI,CAAG;IACP,IAAI,GAAc,IAAI,GAAG,EAAQ,CAAA;IACjC,MAAM,GAAY,KAAK,CAAA;IACvB,OAAO,GAAY,KAAK,CAAA;IACxB,SAAS,GAAkB,EAAE,CAAA;IAC7B,OAAO,CAAa;IACpB,IAAI,CAAY;IAChB,MAAM,CAAc;IACpB,QAAQ,CAAQ;IAChB,mBAAmB,CAAS;IAG5B,YAAY,QAAmB,EAAE,IAAU,EAAE,IAAO;QAClD,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;QACxB,IAAI,CAAC,IAAI,GAA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OAAO,CAAA;IACrB,CAAC;IAED,UAAU;QACR,IAAI,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,EAAE,CAAC;YAC1B,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAA;QACvB,CAAC;QACD,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAA;QACnE,OAAO,IAAI,CAAC,OAAO,CAAA;IACrB,CAAC;CACF","sourcesContent":["/**\n * Single-use utility classes to provide functionality to the {@link Glob}\n * methods.\n *\n * @module\n */\nimport { Minipass } from 'minipass'\nimport { Path } from 'path-scurry'\nimport { Ignore, IgnoreLike } from './ignore.js'\n\n// XXX can we somehow make it so that it NEVER processes a given path more than\n// once, enough that the match set tracking is no longer needed?  that'd speed\n// things up a lot.  Or maybe bring back nounique, and skip it in that case?\n\n// a single minimatch set entry with 1 or more parts\nimport { Pattern } from './pattern.js'\nimport { Processor } from './processor.js'\n\nexport interface GlobWalkerOpts {\n  absolute?: boolean\n  allowWindowsEscape?: boolean\n  cwd?: string | URL\n  dot?: boolean\n  dotRelative?: boolean\n  follow?: boolean\n  ignore?: string | string[] | IgnoreLike\n  mark?: boolean\n  matchBase?: boolean\n  // Note: maxDepth here means \"maximum actual Path.depth()\",\n  // not \"maximum depth beyond cwd\"\n  maxDepth?: number\n  nobrace?: boolean\n  nocase?: boolean\n  nodir?: boolean\n  noext?: boolean\n  noglobstar?: boolean\n  platform?: NodeJS.Platform\n  posix?: boolean\n  realpath?: boolean\n  root?: string\n  stat?: boolean\n  signal?: AbortSignal\n  windowsPathsNoEscape?: boolean\n  withFileTypes?: boolean\n  includeChildMatches?: boolean\n}\n\nexport type GWOFileTypesTrue = GlobWalkerOpts & {\n  withFileTypes: true\n}\nexport type GWOFileTypesFalse = GlobWalkerOpts & {\n  withFileTypes: false\n}\nexport type GWOFileTypesUnset = GlobWalkerOpts & {\n  withFileTypes?: undefined\n}\n\nexport type Result =\n  O extends GWOFileTypesTrue ? Path\n  : O extends GWOFileTypesFalse ? string\n  : O extends GWOFileTypesUnset ? string\n  : Path | string\n\nexport type Matches =\n  O extends GWOFileTypesTrue ? Set\n  : O extends GWOFileTypesFalse ? Set\n  : O extends GWOFileTypesUnset ? Set\n  : Set\n\nexport type MatchStream = Minipass<\n  Result,\n  Result\n>\n\nconst makeIgnore = (\n  ignore: string | string[] | IgnoreLike,\n  opts: GlobWalkerOpts,\n): IgnoreLike =>\n  typeof ignore === 'string' ? new Ignore([ignore], opts)\n  : Array.isArray(ignore) ? new Ignore(ignore, opts)\n  : ignore\n\n/**\n * basic walking utilities that all the glob walker types use\n */\nexport abstract class GlobUtil {\n  path: Path\n  patterns: Pattern[]\n  opts: O\n  seen: Set = new Set()\n  paused: boolean = false\n  aborted: boolean = false\n  #onResume: (() => any)[] = []\n  #ignore?: IgnoreLike\n  #sep: '\\\\' | '/'\n  signal?: AbortSignal\n  maxDepth: number\n  includeChildMatches: boolean\n\n  constructor(patterns: Pattern[], path: Path, opts: O)\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    this.patterns = patterns\n    this.path = path\n    this.opts = opts\n    this.#sep = !opts.posix && opts.platform === 'win32' ? '\\\\' : '/'\n    this.includeChildMatches = opts.includeChildMatches !== false\n    if (opts.ignore || !this.includeChildMatches) {\n      this.#ignore = makeIgnore(opts.ignore ?? [], opts)\n      if (\n        !this.includeChildMatches &&\n        typeof this.#ignore.add !== 'function'\n      ) {\n        const m = 'cannot ignore child matches, ignore lacks add() method.'\n        throw new Error(m)\n      }\n    }\n    // ignore, always set with maxDepth, but it's optional on the\n    // GlobOptions type\n    /* c8 ignore start */\n    this.maxDepth = opts.maxDepth || Infinity\n    /* c8 ignore stop */\n    if (opts.signal) {\n      this.signal = opts.signal\n      this.signal.addEventListener('abort', () => {\n        this.#onResume.length = 0\n      })\n    }\n  }\n\n  #ignored(path: Path): boolean {\n    return this.seen.has(path) || !!this.#ignore?.ignored?.(path)\n  }\n  #childrenIgnored(path: Path): boolean {\n    return !!this.#ignore?.childrenIgnored?.(path)\n  }\n\n  // backpressure mechanism\n  pause() {\n    this.paused = true\n  }\n  resume() {\n    /* c8 ignore start */\n    if (this.signal?.aborted) return\n    /* c8 ignore stop */\n    this.paused = false\n    let fn: (() => any) | undefined = undefined\n    while (!this.paused && (fn = this.#onResume.shift())) {\n      fn()\n    }\n  }\n  onResume(fn: () => any) {\n    if (this.signal?.aborted) return\n    /* c8 ignore start */\n    if (!this.paused) {\n      fn()\n    } else {\n      /* c8 ignore stop */\n      this.#onResume.push(fn)\n    }\n  }\n\n  // do the requisite realpath/stat checking, and return the path\n  // to add or undefined to filter it out.\n  async matchCheck(e: Path, ifDir: boolean): Promise {\n    if (ifDir && this.opts.nodir) return undefined\n    let rpc: Path | undefined\n    if (this.opts.realpath) {\n      rpc = e.realpathCached() || (await e.realpath())\n      if (!rpc) return undefined\n      e = rpc\n    }\n    const needStat = e.isUnknown() || this.opts.stat\n    const s = needStat ? await e.lstat() : e\n    if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n      const target = await s.realpath()\n      /* c8 ignore start */\n      if (target && (target.isUnknown() || this.opts.stat)) {\n        await target.lstat()\n      }\n      /* c8 ignore stop */\n    }\n    return this.matchCheckTest(s, ifDir)\n  }\n\n  matchCheckTest(e: Path | undefined, ifDir: boolean): Path | undefined {\n    return (\n        e &&\n          (this.maxDepth === Infinity || e.depth() <= this.maxDepth) &&\n          (!ifDir || e.canReaddir()) &&\n          (!this.opts.nodir || !e.isDirectory()) &&\n          (!this.opts.nodir ||\n            !this.opts.follow ||\n            !e.isSymbolicLink() ||\n            !e.realpathCached()?.isDirectory()) &&\n          !this.#ignored(e)\n      ) ?\n        e\n      : undefined\n  }\n\n  matchCheckSync(e: Path, ifDir: boolean): Path | undefined {\n    if (ifDir && this.opts.nodir) return undefined\n    let rpc: Path | undefined\n    if (this.opts.realpath) {\n      rpc = e.realpathCached() || e.realpathSync()\n      if (!rpc) return undefined\n      e = rpc\n    }\n    const needStat = e.isUnknown() || this.opts.stat\n    const s = needStat ? e.lstatSync() : e\n    if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n      const target = s.realpathSync()\n      if (target && (target?.isUnknown() || this.opts.stat)) {\n        target.lstatSync()\n      }\n    }\n    return this.matchCheckTest(s, ifDir)\n  }\n\n  abstract matchEmit(p: Result): void\n  abstract matchEmit(p: string | Path): void\n\n  matchFinish(e: Path, absolute: boolean) {\n    if (this.#ignored(e)) return\n    // we know we have an ignore if this is false, but TS doesn't\n    if (!this.includeChildMatches && this.#ignore?.add) {\n      const ign = `${e.relativePosix()}/**`\n      this.#ignore.add(ign)\n    }\n    const abs =\n      this.opts.absolute === undefined ? absolute : this.opts.absolute\n    this.seen.add(e)\n    const mark = this.opts.mark && e.isDirectory() ? this.#sep : ''\n    // ok, we have what we need!\n    if (this.opts.withFileTypes) {\n      this.matchEmit(e)\n    } else if (abs) {\n      const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath()\n      this.matchEmit(abs + mark)\n    } else {\n      const rel = this.opts.posix ? e.relativePosix() : e.relative()\n      const pre =\n        this.opts.dotRelative && !rel.startsWith('..' + this.#sep) ?\n          '.' + this.#sep\n        : ''\n      this.matchEmit(!rel ? '.' + mark : pre + rel + mark)\n    }\n  }\n\n  async match(e: Path, absolute: boolean, ifDir: boolean): Promise {\n    const p = await this.matchCheck(e, ifDir)\n    if (p) this.matchFinish(p, absolute)\n  }\n\n  matchSync(e: Path, absolute: boolean, ifDir: boolean): void {\n    const p = this.matchCheckSync(e, ifDir)\n    if (p) this.matchFinish(p, absolute)\n  }\n\n  walkCB(target: Path, patterns: Pattern[], cb: () => any) {\n    /* c8 ignore start */\n    if (this.signal?.aborted) cb()\n    /* c8 ignore stop */\n    this.walkCB2(target, patterns, new Processor(this.opts), cb)\n  }\n\n  walkCB2(\n    target: Path,\n    patterns: Pattern[],\n    processor: Processor,\n    cb: () => any,\n  ) {\n    if (this.#childrenIgnored(target)) return cb()\n    if (this.signal?.aborted) cb()\n    if (this.paused) {\n      this.onResume(() => this.walkCB2(target, patterns, processor, cb))\n      return\n    }\n    processor.processPatterns(target, patterns)\n\n    // done processing.  all of the above is sync, can be abstracted out.\n    // subwalks is a map of paths to the entry filters they need\n    // matches is a map of paths to [absolute, ifDir] tuples.\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      tasks++\n      this.match(m, absolute, ifDir).then(() => next())\n    }\n\n    for (const t of processor.subwalkTargets()) {\n      if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n        continue\n      }\n      tasks++\n      const childrenCached = t.readdirCached()\n      if (t.calledReaddir())\n        this.walkCB3(t, childrenCached, processor, next)\n      else {\n        t.readdirCB(\n          (_, entries) => this.walkCB3(t, entries, processor, next),\n          true,\n        )\n      }\n    }\n\n    next()\n  }\n\n  walkCB3(\n    target: Path,\n    entries: Path[],\n    processor: Processor,\n    cb: () => any,\n  ) {\n    processor = processor.filterEntries(target, entries)\n\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      tasks++\n      this.match(m, absolute, ifDir).then(() => next())\n    }\n    for (const [target, patterns] of processor.subwalks.entries()) {\n      tasks++\n      this.walkCB2(target, patterns, processor.child(), next)\n    }\n\n    next()\n  }\n\n  walkCBSync(target: Path, patterns: Pattern[], cb: () => any) {\n    /* c8 ignore start */\n    if (this.signal?.aborted) cb()\n    /* c8 ignore stop */\n    this.walkCB2Sync(target, patterns, new Processor(this.opts), cb)\n  }\n\n  walkCB2Sync(\n    target: Path,\n    patterns: Pattern[],\n    processor: Processor,\n    cb: () => any,\n  ) {\n    if (this.#childrenIgnored(target)) return cb()\n    if (this.signal?.aborted) cb()\n    if (this.paused) {\n      this.onResume(() =>\n        this.walkCB2Sync(target, patterns, processor, cb),\n      )\n      return\n    }\n    processor.processPatterns(target, patterns)\n\n    // done processing.  all of the above is sync, can be abstracted out.\n    // subwalks is a map of paths to the entry filters they need\n    // matches is a map of paths to [absolute, ifDir] tuples.\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      this.matchSync(m, absolute, ifDir)\n    }\n\n    for (const t of processor.subwalkTargets()) {\n      if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n        continue\n      }\n      tasks++\n      const children = t.readdirSync()\n      this.walkCB3Sync(t, children, processor, next)\n    }\n\n    next()\n  }\n\n  walkCB3Sync(\n    target: Path,\n    entries: Path[],\n    processor: Processor,\n    cb: () => any,\n  ) {\n    processor = processor.filterEntries(target, entries)\n\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      this.matchSync(m, absolute, ifDir)\n    }\n    for (const [target, patterns] of processor.subwalks.entries()) {\n      tasks++\n      this.walkCB2Sync(target, patterns, processor.child(), next)\n    }\n\n    next()\n  }\n}\n\nexport class GlobWalker<\n  O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil {\n  matches = new Set>()\n\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    super(patterns, path, opts)\n  }\n\n  matchEmit(e: Result): void {\n    this.matches.add(e)\n  }\n\n  async walk(): Promise>> {\n    if (this.signal?.aborted) throw this.signal.reason\n    if (this.path.isUnknown()) {\n      await this.path.lstat()\n    }\n    await new Promise((res, rej) => {\n      this.walkCB(this.path, this.patterns, () => {\n        if (this.signal?.aborted) {\n          rej(this.signal.reason)\n        } else {\n          res(this.matches)\n        }\n      })\n    })\n    return this.matches\n  }\n\n  walkSync(): Set> {\n    if (this.signal?.aborted) throw this.signal.reason\n    if (this.path.isUnknown()) {\n      this.path.lstatSync()\n    }\n    // nothing for the callback to do, because this never pauses\n    this.walkCBSync(this.path, this.patterns, () => {\n      if (this.signal?.aborted) throw this.signal.reason\n    })\n    return this.matches\n  }\n}\n\nexport class GlobStream<\n  O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil {\n  results: Minipass, Result>\n\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    super(patterns, path, opts)\n    this.results = new Minipass, Result>({\n      signal: this.signal,\n      objectMode: true,\n    })\n    this.results.on('drain', () => this.resume())\n    this.results.on('resume', () => this.resume())\n  }\n\n  matchEmit(e: Result): void {\n    this.results.write(e)\n    if (!this.results.flowing) this.pause()\n  }\n\n  stream(): MatchStream {\n    const target = this.path\n    if (target.isUnknown()) {\n      target.lstat().then(() => {\n        this.walkCB(target, this.patterns, () => this.results.end())\n      })\n    } else {\n      this.walkCB(target, this.patterns, () => this.results.end())\n    }\n    return this.results\n  }\n\n  streamSync(): MatchStream {\n    if (this.path.isUnknown()) {\n      this.path.lstatSync()\n    }\n    this.walkCBSync(this.path, this.patterns, () => this.results.end())\n    return this.results\n  }\n}\n"]}PK~\<=##glob/dist/esm/pattern.d.ts.mapnu[{"version":3,"file":"pattern.d.ts","sourceRoot":"","sources":["../../src/pattern.ts"],"names":[],"mappings":";AAEA,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AACpC,MAAM,MAAM,SAAS,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,QAAQ,CAAA;AAGzD,MAAM,MAAM,WAAW,GAAG,CAAC,CAAC,EAAE,SAAS,EAAE,GAAG,IAAI,EAAE,SAAS,EAAE,CAAC,CAAA;AAC9D,MAAM,MAAM,cAAc,GAAG;IAC3B,EAAE,EAAE,EAAE;IACN,EAAE,EAAE,EAAE;IACN,EAAE,EAAE,MAAM;IACV,EAAE,EAAE,MAAM;IACV,GAAG,IAAI,EAAE,SAAS,EAAE;CACrB,CAAA;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AO,EAAE;oBACd,IAAI,CAAC,KAAK,EAAE,CAAC,CAAA;IACrB,CAAC;IAED;;OAEG;IACH,IAAI;QACF,MAAM,CAAC,GAAG,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,CAAA;QAC9B,OAAO,CACH,OAAO,CAAC,KAAK,QAAQ,IAAI,IAAI,CAAC,UAAU,EAAE,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,CAChE,CAAC,CAAC;YACD,CAAC;YACH,CAAC,CAAC,EAAE,CAAA;IACR,CAAC;IAED;;;OAGG;IACH,mBAAmB;QACjB,OAAO,CAAC,CACN,IAAI,CAAC,MAAM,KAAK,CAAC;YACjB,CAAC,IAAI,CAAC,UAAU,EAAE;YAClB,CAAC,IAAI,CAAC,eAAe,CACtB,CAAA;IACH,CAAC;IAED;;OAEG;IACH,kBAAkB;QAChB,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,IAAI,CAAC,eAAe;YAClE,OAAO,KAAK,CAAA;QACd,IAAI,CAAC,eAAe,GAAG,KAAK,CAAA;QAC5B,OAAO,IAAI,CAAA;IACb,CAAC;CACF","sourcesContent":["// this is just a very light wrapper around 2 arrays with an offset index\n\nimport { GLOBSTAR } from 'minimatch'\nexport type MMPattern = string | RegExp | typeof GLOBSTAR\n\n// an array of length >= 1\nexport type PatternList = [p: MMPattern, ...rest: MMPattern[]]\nexport type UNCPatternList = [\n  p0: '',\n  p1: '',\n  p2: string,\n  p3: string,\n  ...rest: MMPattern[],\n]\nexport type DrivePatternList = [p0: string, ...rest: MMPattern[]]\nexport type AbsolutePatternList = [p0: '', ...rest: MMPattern[]]\nexport type GlobList = [p: string, ...rest: string[]]\n\nconst isPatternList = (pl: MMPattern[]): pl is PatternList =>\n  pl.length >= 1\nconst isGlobList = (gl: string[]): gl is GlobList => gl.length >= 1\n\n/**\n * An immutable-ish view on an array of glob parts and their parsed\n * results\n */\nexport class Pattern {\n  readonly #patternList: PatternList\n  readonly #globList: GlobList\n  readonly #index: number\n  readonly length: number\n  readonly #platform: NodeJS.Platform\n  #rest?: Pattern | null\n  #globString?: string\n  #isDrive?: boolean\n  #isUNC?: boolean\n  #isAbsolute?: boolean\n  #followGlobstar: boolean = true\n\n  constructor(\n    patternList: MMPattern[],\n    globList: string[],\n    index: number,\n    platform: NodeJS.Platform,\n  ) {\n    if (!isPatternList(patternList)) {\n      throw new TypeError('empty pattern list')\n    }\n    if (!isGlobList(globList)) {\n      throw new TypeError('empty glob list')\n    }\n    if (globList.length !== patternList.length) {\n      throw new TypeError('mismatched pattern list and glob list lengths')\n    }\n    this.length = patternList.length\n    if (index < 0 || index >= this.length) {\n      throw new TypeError('index out of range')\n    }\n    this.#patternList = patternList\n    this.#globList = globList\n    this.#index = index\n    this.#platform = platform\n\n    // normalize root entries of absolute patterns on initial creation.\n    if (this.#index === 0) {\n      // c: => ['c:/']\n      // C:/ => ['C:/']\n      // C:/x => ['C:/', 'x']\n      // //host/share => ['//host/share/']\n      // //host/share/ => ['//host/share/']\n      // //host/share/x => ['//host/share/', 'x']\n      // /etc => ['/', 'etc']\n      // / => ['/']\n      if (this.isUNC()) {\n        // '' / '' / 'host' / 'share'\n        const [p0, p1, p2, p3, ...prest] = this.#patternList\n        const [g0, g1, g2, g3, ...grest] = this.#globList\n        if (prest[0] === '') {\n          // ends in /\n          prest.shift()\n          grest.shift()\n        }\n        const p = [p0, p1, p2, p3, ''].join('/')\n        const g = [g0, g1, g2, g3, ''].join('/')\n        this.#patternList = [p, ...prest]\n        this.#globList = [g, ...grest]\n        this.length = this.#patternList.length\n      } else if (this.isDrive() || this.isAbsolute()) {\n        const [p1, ...prest] = this.#patternList\n        const [g1, ...grest] = this.#globList\n        if (prest[0] === '') {\n          // ends in /\n          prest.shift()\n          grest.shift()\n        }\n        const p = (p1 as string) + '/'\n        const g = g1 + '/'\n        this.#patternList = [p, ...prest]\n        this.#globList = [g, ...grest]\n        this.length = this.#patternList.length\n      }\n    }\n  }\n\n  /**\n   * The first entry in the parsed list of patterns\n   */\n  pattern(): MMPattern {\n    return this.#patternList[this.#index] as MMPattern\n  }\n\n  /**\n   * true of if pattern() returns a string\n   */\n  isString(): boolean {\n    return typeof this.#patternList[this.#index] === 'string'\n  }\n  /**\n   * true of if pattern() returns GLOBSTAR\n   */\n  isGlobstar(): boolean {\n    return this.#patternList[this.#index] === GLOBSTAR\n  }\n  /**\n   * true if pattern() returns a regexp\n   */\n  isRegExp(): boolean {\n    return this.#patternList[this.#index] instanceof RegExp\n  }\n\n  /**\n   * The /-joined set of glob parts that make up this pattern\n   */\n  globString(): string {\n    return (this.#globString =\n      this.#globString ||\n      (this.#index === 0 ?\n        this.isAbsolute() ?\n          this.#globList[0] + this.#globList.slice(1).join('/')\n        : this.#globList.join('/')\n      : this.#globList.slice(this.#index).join('/')))\n  }\n\n  /**\n   * true if there are more pattern parts after this one\n   */\n  hasMore(): boolean {\n    return this.length > this.#index + 1\n  }\n\n  /**\n   * The rest of the pattern after this part, or null if this is the end\n   */\n  rest(): Pattern | null {\n    if (this.#rest !== undefined) return this.#rest\n    if (!this.hasMore()) return (this.#rest = null)\n    this.#rest = new Pattern(\n      this.#patternList,\n      this.#globList,\n      this.#index + 1,\n      this.#platform,\n    )\n    this.#rest.#isAbsolute = this.#isAbsolute\n    this.#rest.#isUNC = this.#isUNC\n    this.#rest.#isDrive = this.#isDrive\n    return this.#rest\n  }\n\n  /**\n   * true if the pattern represents a //unc/path/ on windows\n   */\n  isUNC(): boolean {\n    const pl = this.#patternList\n    return this.#isUNC !== undefined ?\n        this.#isUNC\n      : (this.#isUNC =\n          this.#platform === 'win32' &&\n          this.#index === 0 &&\n          pl[0] === '' &&\n          pl[1] === '' &&\n          typeof pl[2] === 'string' &&\n          !!pl[2] &&\n          typeof pl[3] === 'string' &&\n          !!pl[3])\n  }\n\n  // pattern like C:/...\n  // split = ['C:', ...]\n  // XXX: would be nice to handle patterns like `c:*` to test the cwd\n  // in c: for *, but I don't know of a way to even figure out what that\n  // cwd is without actually chdir'ing into it?\n  /**\n   * True if the pattern starts with a drive letter on Windows\n   */\n  isDrive(): boolean {\n    const pl = this.#patternList\n    return this.#isDrive !== undefined ?\n        this.#isDrive\n      : (this.#isDrive =\n          this.#platform === 'win32' &&\n          this.#index === 0 &&\n          this.length > 1 &&\n          typeof pl[0] === 'string' &&\n          /^[a-z]:$/i.test(pl[0]))\n  }\n\n  // pattern = '/' or '/...' or '/x/...'\n  // split = ['', ''] or ['', ...] or ['', 'x', ...]\n  // Drive and UNC both considered absolute on windows\n  /**\n   * True if the pattern is rooted on an absolute path\n   */\n  isAbsolute(): boolean {\n    const pl = this.#patternList\n    return this.#isAbsolute !== undefined ?\n        this.#isAbsolute\n      : (this.#isAbsolute =\n          (pl[0] === '' && pl.length > 1) ||\n          this.isDrive() ||\n          this.isUNC())\n  }\n\n  /**\n   * consume the root of the pattern, and return it\n   */\n  root(): string {\n    const p = this.#patternList[0]\n    return (\n        typeof p === 'string' && this.isAbsolute() && this.#index === 0\n      ) ?\n        p\n      : ''\n  }\n\n  /**\n   * Check to see if the current globstar pattern is allowed to follow\n   * a symbolic link.\n   */\n  checkFollowGlobstar(): boolean {\n    return !(\n      this.#index === 0 ||\n      !this.isGlobstar() ||\n      !this.#followGlobstar\n    )\n  }\n\n  /**\n   * Mark that the current globstar pattern is following a symbolic link\n   */\n  markFollowGlobstar(): boolean {\n    if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar)\n      return false\n    this.#followGlobstar = false\n    return true\n  }\n}\n"]}PK~\	= glob/dist/esm/has-magic.d.ts.mapnu[{"version":3,"file":"has-magic.d.ts","sourceRoot":"","sources":["../../src/has-magic.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AAEvC;;;;;;;;;;GAUG;AACH,eAAO,MAAM,QAAQ,YACV,MAAM,GAAG,MAAM,EAAE,YACjB,WAAW,KACnB,OAQF,CAAA"}PK~\4gt((glob/dist/esm/processor.jsnu[// synchronous utility for filtering entries and calculating subwalks
import { GLOBSTAR } from 'minimatch';
/**
 * A cache of which patterns have been processed for a given Path
 */
export class HasWalkedCache {
    store;
    constructor(store = new Map()) {
        this.store = store;
    }
    copy() {
        return new HasWalkedCache(new Map(this.store));
    }
    hasWalked(target, pattern) {
        return this.store.get(target.fullpath())?.has(pattern.globString());
    }
    storeWalked(target, pattern) {
        const fullpath = target.fullpath();
        const cached = this.store.get(fullpath);
        if (cached)
            cached.add(pattern.globString());
        else
            this.store.set(fullpath, new Set([pattern.globString()]));
    }
}
/**
 * A record of which paths have been matched in a given walk step,
 * and whether they only are considered a match if they are a directory,
 * and whether their absolute or relative path should be returned.
 */
export class MatchRecord {
    store = new Map();
    add(target, absolute, ifDir) {
        const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0);
        const current = this.store.get(target);
        this.store.set(target, current === undefined ? n : n & current);
    }
    // match, absolute, ifdir
    entries() {
        return [...this.store.entries()].map(([path, n]) => [
            path,
            !!(n & 2),
            !!(n & 1),
        ]);
    }
}
/**
 * A collection of patterns that must be processed in a subsequent step
 * for a given path.
 */
export class SubWalks {
    store = new Map();
    add(target, pattern) {
        if (!target.canReaddir()) {
            return;
        }
        const subs = this.store.get(target);
        if (subs) {
            if (!subs.find(p => p.globString() === pattern.globString())) {
                subs.push(pattern);
            }
        }
        else
            this.store.set(target, [pattern]);
    }
    get(target) {
        const subs = this.store.get(target);
        /* c8 ignore start */
        if (!subs) {
            throw new Error('attempting to walk unknown path');
        }
        /* c8 ignore stop */
        return subs;
    }
    entries() {
        return this.keys().map(k => [k, this.store.get(k)]);
    }
    keys() {
        return [...this.store.keys()].filter(t => t.canReaddir());
    }
}
/**
 * The class that processes patterns for a given path.
 *
 * Handles child entry filtering, and determining whether a path's
 * directory contents must be read.
 */
export class Processor {
    hasWalkedCache;
    matches = new MatchRecord();
    subwalks = new SubWalks();
    patterns;
    follow;
    dot;
    opts;
    constructor(opts, hasWalkedCache) {
        this.opts = opts;
        this.follow = !!opts.follow;
        this.dot = !!opts.dot;
        this.hasWalkedCache =
            hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache();
    }
    processPatterns(target, patterns) {
        this.patterns = patterns;
        const processingSet = patterns.map(p => [target, p]);
        // map of paths to the magic-starting subwalks they need to walk
        // first item in patterns is the filter
        for (let [t, pattern] of processingSet) {
            this.hasWalkedCache.storeWalked(t, pattern);
            const root = pattern.root();
            const absolute = pattern.isAbsolute() && this.opts.absolute !== false;
            // start absolute patterns at root
            if (root) {
                t = t.resolve(root === '/' && this.opts.root !== undefined ?
                    this.opts.root
                    : root);
                const rest = pattern.rest();
                if (!rest) {
                    this.matches.add(t, true, false);
                    continue;
                }
                else {
                    pattern = rest;
                }
            }
            if (t.isENOENT())
                continue;
            let p;
            let rest;
            let changed = false;
            while (typeof (p = pattern.pattern()) === 'string' &&
                (rest = pattern.rest())) {
                const c = t.resolve(p);
                t = c;
                pattern = rest;
                changed = true;
            }
            p = pattern.pattern();
            rest = pattern.rest();
            if (changed) {
                if (this.hasWalkedCache.hasWalked(t, pattern))
                    continue;
                this.hasWalkedCache.storeWalked(t, pattern);
            }
            // now we have either a final string for a known entry,
            // more strings for an unknown entry,
            // or a pattern starting with magic, mounted on t.
            if (typeof p === 'string') {
                // must not be final entry, otherwise we would have
                // concatenated it earlier.
                const ifDir = p === '..' || p === '' || p === '.';
                this.matches.add(t.resolve(p), absolute, ifDir);
                continue;
            }
            else if (p === GLOBSTAR) {
                // if no rest, match and subwalk pattern
                // if rest, process rest and subwalk pattern
                // if it's a symlink, but we didn't get here by way of a
                // globstar match (meaning it's the first time THIS globstar
                // has traversed a symlink), then we follow it. Otherwise, stop.
                if (!t.isSymbolicLink() ||
                    this.follow ||
                    pattern.checkFollowGlobstar()) {
                    this.subwalks.add(t, pattern);
                }
                const rp = rest?.pattern();
                const rrest = rest?.rest();
                if (!rest || ((rp === '' || rp === '.') && !rrest)) {
                    // only HAS to be a dir if it ends in **/ or **/.
                    // but ending in ** will match files as well.
                    this.matches.add(t, absolute, rp === '' || rp === '.');
                }
                else {
                    if (rp === '..') {
                        // this would mean you're matching **/.. at the fs root,
                        // and no thanks, I'm not gonna test that specific case.
                        /* c8 ignore start */
                        const tp = t.parent || t;
                        /* c8 ignore stop */
                        if (!rrest)
                            this.matches.add(tp, absolute, true);
                        else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {
                            this.subwalks.add(tp, rrest);
                        }
                    }
                }
            }
            else if (p instanceof RegExp) {
                this.subwalks.add(t, pattern);
            }
        }
        return this;
    }
    subwalkTargets() {
        return this.subwalks.keys();
    }
    child() {
        return new Processor(this.opts, this.hasWalkedCache);
    }
    // return a new Processor containing the subwalks for each
    // child entry, and a set of matches, and
    // a hasWalkedCache that's a copy of this one
    // then we're going to call
    filterEntries(parent, entries) {
        const patterns = this.subwalks.get(parent);
        // put matches and entry walks into the results processor
        const results = this.child();
        for (const e of entries) {
            for (const pattern of patterns) {
                const absolute = pattern.isAbsolute();
                const p = pattern.pattern();
                const rest = pattern.rest();
                if (p === GLOBSTAR) {
                    results.testGlobstar(e, pattern, rest, absolute);
                }
                else if (p instanceof RegExp) {
                    results.testRegExp(e, p, rest, absolute);
                }
                else {
                    results.testString(e, p, rest, absolute);
                }
            }
        }
        return results;
    }
    testGlobstar(e, pattern, rest, absolute) {
        if (this.dot || !e.name.startsWith('.')) {
            if (!pattern.hasMore()) {
                this.matches.add(e, absolute, false);
            }
            if (e.canReaddir()) {
                // if we're in follow mode or it's not a symlink, just keep
                // testing the same pattern. If there's more after the globstar,
                // then this symlink consumes the globstar. If not, then we can
                // follow at most ONE symlink along the way, so we mark it, which
                // also checks to ensure that it wasn't already marked.
                if (this.follow || !e.isSymbolicLink()) {
                    this.subwalks.add(e, pattern);
                }
                else if (e.isSymbolicLink()) {
                    if (rest && pattern.checkFollowGlobstar()) {
                        this.subwalks.add(e, rest);
                    }
                    else if (pattern.markFollowGlobstar()) {
                        this.subwalks.add(e, pattern);
                    }
                }
            }
        }
        // if the NEXT thing matches this entry, then also add
        // the rest.
        if (rest) {
            const rp = rest.pattern();
            if (typeof rp === 'string' &&
                // dots and empty were handled already
                rp !== '..' &&
                rp !== '' &&
                rp !== '.') {
                this.testString(e, rp, rest.rest(), absolute);
            }
            else if (rp === '..') {
                /* c8 ignore start */
                const ep = e.parent || e;
                /* c8 ignore stop */
                this.subwalks.add(ep, rest);
            }
            else if (rp instanceof RegExp) {
                this.testRegExp(e, rp, rest.rest(), absolute);
            }
        }
    }
    testRegExp(e, p, rest, absolute) {
        if (!p.test(e.name))
            return;
        if (!rest) {
            this.matches.add(e, absolute, false);
        }
        else {
            this.subwalks.add(e, rest);
        }
    }
    testString(e, p, rest, absolute) {
        // should never happen?
        if (!e.isNamed(p))
            return;
        if (!rest) {
            this.matches.add(e, absolute, false);
        }
        else {
            this.subwalks.add(e, rest);
        }
    }
}
//# sourceMappingURL=processor.js.mapPK~\b$ѓ  glob/dist/esm/glob.jsnu[import { Minimatch } from 'minimatch';
import { fileURLToPath } from 'node:url';
import { PathScurry, PathScurryDarwin, PathScurryPosix, PathScurryWin32, } from 'path-scurry';
import { Pattern } from './pattern.js';
import { GlobStream, GlobWalker } from './walker.js';
// if no process global, just call it linux.
// so we default to case-sensitive, / separators
const defaultPlatform = (typeof process === 'object' &&
    process &&
    typeof process.platform === 'string') ?
    process.platform
    : 'linux';
/**
 * An object that can perform glob pattern traversals.
 */
export class Glob {
    absolute;
    cwd;
    root;
    dot;
    dotRelative;
    follow;
    ignore;
    magicalBraces;
    mark;
    matchBase;
    maxDepth;
    nobrace;
    nocase;
    nodir;
    noext;
    noglobstar;
    pattern;
    platform;
    realpath;
    scurry;
    stat;
    signal;
    windowsPathsNoEscape;
    withFileTypes;
    includeChildMatches;
    /**
     * The options provided to the constructor.
     */
    opts;
    /**
     * An array of parsed immutable {@link Pattern} objects.
     */
    patterns;
    /**
     * All options are stored as properties on the `Glob` object.
     *
     * See {@link GlobOptions} for full options descriptions.
     *
     * Note that a previous `Glob` object can be passed as the
     * `GlobOptions` to another `Glob` instantiation to re-use settings
     * and caches with a new pattern.
     *
     * Traversal functions can be called multiple times to run the walk
     * again.
     */
    constructor(pattern, opts) {
        /* c8 ignore start */
        if (!opts)
            throw new TypeError('glob options required');
        /* c8 ignore stop */
        this.withFileTypes = !!opts.withFileTypes;
        this.signal = opts.signal;
        this.follow = !!opts.follow;
        this.dot = !!opts.dot;
        this.dotRelative = !!opts.dotRelative;
        this.nodir = !!opts.nodir;
        this.mark = !!opts.mark;
        if (!opts.cwd) {
            this.cwd = '';
        }
        else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) {
            opts.cwd = fileURLToPath(opts.cwd);
        }
        this.cwd = opts.cwd || '';
        this.root = opts.root;
        this.magicalBraces = !!opts.magicalBraces;
        this.nobrace = !!opts.nobrace;
        this.noext = !!opts.noext;
        this.realpath = !!opts.realpath;
        this.absolute = opts.absolute;
        this.includeChildMatches = opts.includeChildMatches !== false;
        this.noglobstar = !!opts.noglobstar;
        this.matchBase = !!opts.matchBase;
        this.maxDepth =
            typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity;
        this.stat = !!opts.stat;
        this.ignore = opts.ignore;
        if (this.withFileTypes && this.absolute !== undefined) {
            throw new Error('cannot set absolute and withFileTypes:true');
        }
        if (typeof pattern === 'string') {
            pattern = [pattern];
        }
        this.windowsPathsNoEscape =
            !!opts.windowsPathsNoEscape ||
                opts.allowWindowsEscape ===
                    false;
        if (this.windowsPathsNoEscape) {
            pattern = pattern.map(p => p.replace(/\\/g, '/'));
        }
        if (this.matchBase) {
            if (opts.noglobstar) {
                throw new TypeError('base matching requires globstar');
            }
            pattern = pattern.map(p => (p.includes('/') ? p : `./**/${p}`));
        }
        this.pattern = pattern;
        this.platform = opts.platform || defaultPlatform;
        this.opts = { ...opts, platform: this.platform };
        if (opts.scurry) {
            this.scurry = opts.scurry;
            if (opts.nocase !== undefined &&
                opts.nocase !== opts.scurry.nocase) {
                throw new Error('nocase option contradicts provided scurry option');
            }
        }
        else {
            const Scurry = opts.platform === 'win32' ? PathScurryWin32
                : opts.platform === 'darwin' ? PathScurryDarwin
                    : opts.platform ? PathScurryPosix
                        : PathScurry;
            this.scurry = new Scurry(this.cwd, {
                nocase: opts.nocase,
                fs: opts.fs,
            });
        }
        this.nocase = this.scurry.nocase;
        // If you do nocase:true on a case-sensitive file system, then
        // we need to use regexps instead of strings for non-magic
        // path portions, because statting `aBc` won't return results
        // for the file `AbC` for example.
        const nocaseMagicOnly = this.platform === 'darwin' || this.platform === 'win32';
        const mmo = {
            // default nocase based on platform
            ...opts,
            dot: this.dot,
            matchBase: this.matchBase,
            nobrace: this.nobrace,
            nocase: this.nocase,
            nocaseMagicOnly,
            nocomment: true,
            noext: this.noext,
            nonegate: true,
            optimizationLevel: 2,
            platform: this.platform,
            windowsPathsNoEscape: this.windowsPathsNoEscape,
            debug: !!this.opts.debug,
        };
        const mms = this.pattern.map(p => new Minimatch(p, mmo));
        const [matchSet, globParts] = mms.reduce((set, m) => {
            set[0].push(...m.set);
            set[1].push(...m.globParts);
            return set;
        }, [[], []]);
        this.patterns = matchSet.map((set, i) => {
            const g = globParts[i];
            /* c8 ignore start */
            if (!g)
                throw new Error('invalid pattern object');
            /* c8 ignore stop */
            return new Pattern(set, g, 0, this.platform);
        });
    }
    async walk() {
        // Walkers always return array of Path objects, so we just have to
        // coerce them into the right shape.  It will have already called
        // realpath() if the option was set to do so, so we know that's cached.
        // start out knowing the cwd, at least
        return [
            ...(await new GlobWalker(this.patterns, this.scurry.cwd, {
                ...this.opts,
                maxDepth: this.maxDepth !== Infinity ?
                    this.maxDepth + this.scurry.cwd.depth()
                    : Infinity,
                platform: this.platform,
                nocase: this.nocase,
                includeChildMatches: this.includeChildMatches,
            }).walk()),
        ];
    }
    walkSync() {
        return [
            ...new GlobWalker(this.patterns, this.scurry.cwd, {
                ...this.opts,
                maxDepth: this.maxDepth !== Infinity ?
                    this.maxDepth + this.scurry.cwd.depth()
                    : Infinity,
                platform: this.platform,
                nocase: this.nocase,
                includeChildMatches: this.includeChildMatches,
            }).walkSync(),
        ];
    }
    stream() {
        return new GlobStream(this.patterns, this.scurry.cwd, {
            ...this.opts,
            maxDepth: this.maxDepth !== Infinity ?
                this.maxDepth + this.scurry.cwd.depth()
                : Infinity,
            platform: this.platform,
            nocase: this.nocase,
            includeChildMatches: this.includeChildMatches,
        }).stream();
    }
    streamSync() {
        return new GlobStream(this.patterns, this.scurry.cwd, {
            ...this.opts,
            maxDepth: this.maxDepth !== Infinity ?
                this.maxDepth + this.scurry.cwd.depth()
                : Infinity,
            platform: this.platform,
            nocase: this.nocase,
            includeChildMatches: this.includeChildMatches,
        }).streamSync();
    }
    /**
     * Default sync iteration function. Returns a Generator that
     * iterates over the results.
     */
    iterateSync() {
        return this.streamSync()[Symbol.iterator]();
    }
    [Symbol.iterator]() {
        return this.iterateSync();
    }
    /**
     * Default async iteration function. Returns an AsyncGenerator that
     * iterates over the results.
     */
    iterate() {
        return this.stream()[Symbol.asyncIterator]();
    }
    [Symbol.asyncIterator]() {
        return this.iterate();
    }
}
//# sourceMappingURL=glob.js.mapPK~\Nooglob/dist/esm/index.jsnu[import { escape, unescape } from 'minimatch';
import { Glob } from './glob.js';
import { hasMagic } from './has-magic.js';
export { escape, unescape } from 'minimatch';
export { Glob } from './glob.js';
export { hasMagic } from './has-magic.js';
export { Ignore } from './ignore.js';
export function globStreamSync(pattern, options = {}) {
    return new Glob(pattern, options).streamSync();
}
export function globStream(pattern, options = {}) {
    return new Glob(pattern, options).stream();
}
export function globSync(pattern, options = {}) {
    return new Glob(pattern, options).walkSync();
}
async function glob_(pattern, options = {}) {
    return new Glob(pattern, options).walk();
}
export function globIterateSync(pattern, options = {}) {
    return new Glob(pattern, options).iterateSync();
}
export function globIterate(pattern, options = {}) {
    return new Glob(pattern, options).iterate();
}
// aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc
export const streamSync = globStreamSync;
export const stream = Object.assign(globStream, { sync: globStreamSync });
export const iterateSync = globIterateSync;
export const iterate = Object.assign(globIterate, {
    sync: globIterateSync,
});
export const sync = Object.assign(globSync, {
    stream: globStreamSync,
    iterate: globIterateSync,
});
export const glob = Object.assign(glob_, {
    glob: glob_,
    globSync,
    sync,
    globStream,
    stream,
    globStreamSync,
    streamSync,
    globIterate,
    iterate,
    globIterateSync,
    iterateSync,
    Glob,
    hasMagic,
    escape,
    unescape,
});
glob.glob = glob;
//# sourceMappingURL=index.js.mapPK~\u9u9glob/dist/esm/bin.mjs.mapnu[{"version":3,"file":"bin.mjs","sourceRoot":"","sources":["../../src/bin.mts"],"names":[],"mappings":";AACA,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAA;AAClD,OAAO,EAAE,UAAU,EAAE,MAAM,IAAI,CAAA;AAC/B,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AACtC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAA;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAA;AACnC,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAA;AAEvC,qBAAqB;AACrB,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC,KAAK,CAC5B,MAAM,QAAQ,CACZ,aAAa,CAAC,IAAI,GAAG,CAAC,oBAAoB,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAC7D,MAAM,CACP,CAAC,KAAK,CAAC,GAAG,EAAE,CACX,QAAQ,CACN,aAAa,CAAC,IAAI,GAAG,CAAC,oBAAoB,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAC7D,MAAM,CACP,CACF,CACqB,CAAA;AACxB,oBAAoB;AAEpB,MAAM,CAAC,GAAG,IAAI,CAAC;IACb,KAAK,EAAE,4CAA4C;CACpD,CAAC;KACC,WAAW,CACV;YACQ,OAAO;;;;GAIhB,C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IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,KAAK,EAAE,MAAM,CAAC,KAAK;QACnB,KAAK,EAAE,MAAM,CAAC,KAAK;KACpB,CAAC,CAAA;IAEF,MAAM,GAAG,GAAG,MAAM,CAAC,GAAG,CAAA;IACtB,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAA;QACpC,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAA;IACxC,CAAC;SAAM,CAAC;QACN,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAA;QACvC,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,eAAe,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,CAAA;IACxE,CAAC;AACH,CAAC;AAAC,OAAO,CAAC,EAAE,CAAC;IACX,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,CAAA;IACxB,OAAO,CAAC,KAAK,CAAC,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAA;IACzD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;AACjB,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { foregroundChild } from 'foreground-child'\nimport { existsSync } from 'fs'\nimport { readFile } from 'fs/promises'\nimport { jack } from 'jackspeak'\nimport { join } from 'path'\nimport { fileURLToPath } from 'url'\nimport { globStream } from './index.js'\n\n/* c8 ignore start */\nconst { version } = JSON.parse(\n  await readFile(\n    fileURLToPath(new URL('../../package.json', import.meta.url)),\n    'utf8',\n  ).catch(() =>\n    readFile(\n      fileURLToPath(new URL('../../package.json', import.meta.url)),\n      'utf8',\n    ),\n  ),\n) as { version: string }\n/* c8 ignore stop */\n\nconst j = jack({\n  usage: 'glob [options] [ [ ...]]',\n})\n  .description(\n    `\n    Glob v${version}\n\n    Expand the positional glob expression arguments into any matching file\n    system paths found.\n  `,\n  )\n  .opt({\n    cmd: {\n      short: 'c',\n      hint: 'command',\n      description: `Run the command provided, passing the glob expression\n                    matches as arguments.`,\n    },\n  })\n  .opt({\n    default: {\n      short: 'p',\n      hint: 'pattern',\n      description: `If no positional arguments are provided, glob will use\n                    this pattern`,\n    },\n  })\n  .flag({\n    all: {\n      short: 'A',\n      description: `By default, the glob cli command will not expand any\n                    arguments that are an exact match to a file on disk.\n\n                    This prevents double-expanding, in case the shell expands\n                    an argument whose filename is a glob expression.\n\n                    For example, if 'app/*.ts' would match 'app/[id].ts', then\n                    on Windows powershell or cmd.exe, 'glob app/*.ts' will\n                    expand to 'app/[id].ts', as expected. However, in posix\n                    shells such as bash or zsh, the shell will first expand\n                    'app/*.ts' to a list of filenames. Then glob will look\n                    for a file matching 'app/[id].ts' (ie, 'app/i.ts' or\n                    'app/d.ts'), which is unexpected.\n\n                    Setting '--all' prevents this behavior, causing glob\n                    to treat ALL patterns as glob expressions to be expanded,\n                    even if they are an exact match to a file on disk.\n\n                    When setting this option, be sure to enquote arguments\n                    so that the shell will not expand them prior to passing\n                    them to the glob command process.\n      `,\n    },\n    absolute: {\n      short: 'a',\n      description: 'Expand to absolute paths',\n    },\n    'dot-relative': {\n      short: 'd',\n      description: `Prepend './' on relative matches`,\n    },\n    mark: {\n      short: 'm',\n      description: `Append a / on any directories matched`,\n    },\n    posix: {\n      short: 'x',\n      description: `Always resolve to posix style paths, using '/' as the\n                    directory separator, even on Windows. Drive letter\n                    absolute matches on Windows will be expanded to their\n                    full resolved UNC maths, eg instead of 'C:\\\\foo\\\\bar',\n                    it will expand to '//?/C:/foo/bar'.\n      `,\n    },\n\n    follow: {\n      short: 'f',\n      description: `Follow symlinked directories when expanding '**'`,\n    },\n    realpath: {\n      short: 'R',\n      description: `Call 'fs.realpath' on all of the results. In the case\n                    of an entry that cannot be resolved, the entry is\n                    omitted. This incurs a slight performance penalty, of\n                    course, because of the added system calls.`,\n    },\n    stat: {\n      short: 's',\n      description: `Call 'fs.lstat' on all entries, whether required or not\n                    to determine if it's a valid match.`,\n    },\n    'match-base': {\n      short: 'b',\n      description: `Perform a basename-only match if the pattern does not\n                    contain any slash characters. That is, '*.js' would be\n                    treated as equivalent to '**/*.js', matching js files\n                    in all directories.\n      `,\n    },\n\n    dot: {\n      description: `Allow patterns to match files/directories that start\n                    with '.', even if the pattern does not start with '.'\n      `,\n    },\n    nobrace: {\n      description: 'Do not expand {...} patterns',\n    },\n    nocase: {\n      description: `Perform a case-insensitive match. This defaults to\n                    'true' on macOS and Windows platforms, and false on\n                    all others.\n\n                    Note: 'nocase' should only be explicitly set when it is\n                    known that the filesystem's case sensitivity differs\n                    from the platform default. If set 'true' on\n                    case-insensitive file systems, then the walk may return\n                    more or less results than expected.\n      `,\n    },\n    nodir: {\n      description: `Do not match directories, only files.\n\n                    Note: to *only* match directories, append a '/' at the\n                    end of the pattern.\n      `,\n    },\n    noext: {\n      description: `Do not expand extglob patterns, such as '+(a|b)'`,\n    },\n    noglobstar: {\n      description: `Do not expand '**' against multiple path portions.\n                    Ie, treat it as a normal '*' instead.`,\n    },\n    'windows-path-no-escape': {\n      description: `Use '\\\\' as a path separator *only*, and *never* as an\n                    escape character. If set, all '\\\\' characters are\n                    replaced with '/' in the pattern.`,\n    },\n  })\n  .num({\n    'max-depth': {\n      short: 'D',\n      description: `Maximum depth to traverse from the current\n                    working directory`,\n    },\n  })\n  .opt({\n    cwd: {\n      short: 'C',\n      description: 'Current working directory to execute/match in',\n      default: process.cwd(),\n    },\n    root: {\n      short: 'r',\n      description: `A string path resolved against the 'cwd', which is\n                    used as the starting point for absolute patterns that\n                    start with '/' (but not drive letters or UNC paths\n                    on Windows).\n\n                    Note that this *doesn't* necessarily limit the walk to\n                    the 'root' directory, and doesn't affect the cwd\n                    starting point for non-absolute patterns. A pattern\n                    containing '..' will still be able to traverse out of\n                    the root directory, if it is not an actual root directory\n                    on the filesystem, and any non-absolute patterns will\n                    still be matched in the 'cwd'.\n\n                    To start absolute and non-absolute patterns in the same\n                    path, you can use '--root=' to set it to the empty\n                    string. However, be aware that on Windows systems, a\n                    pattern like 'x:/*' or '//host/share/*' will *always*\n                    start in the 'x:/' or '//host/share/' directory,\n                    regardless of the --root setting.\n      `,\n    },\n    platform: {\n      description: `Defaults to the value of 'process.platform' if\n                    available, or 'linux' if not. Setting --platform=win32\n                    on non-Windows systems may cause strange behavior!`,\n      validOptions: [\n        'aix',\n        'android',\n        'darwin',\n        'freebsd',\n        'haiku',\n        'linux',\n        'openbsd',\n        'sunos',\n        'win32',\n        'cygwin',\n        'netbsd',\n      ],\n    },\n  })\n  .optList({\n    ignore: {\n      short: 'i',\n      description: `Glob patterns to ignore`,\n    },\n  })\n  .flag({\n    debug: {\n      short: 'v',\n      description: `Output a huge amount of noisy debug information about\n                    patterns as they are parsed and used to match files.`,\n    },\n  })\n  .flag({\n    help: {\n      short: 'h',\n      description: 'Show this usage information',\n    },\n  })\n\ntry {\n  const { positionals, values } = j.parse()\n  if (values.help) {\n    console.log(j.usage())\n    process.exit(0)\n  }\n  if (positionals.length === 0 && !values.default)\n    throw 'No patterns provided'\n  if (positionals.length === 0 && values.default)\n    positionals.push(values.default)\n  const patterns =\n    values.all ? positionals : positionals.filter(p => !existsSync(p))\n  const matches =\n    values.all ?\n      []\n    : positionals.filter(p => existsSync(p)).map(p => join(p))\n  const stream = globStream(patterns, {\n    absolute: values.absolute,\n    cwd: values.cwd,\n    dot: values.dot,\n    dotRelative: values['dot-relative'],\n    follow: values.follow,\n    ignore: values.ignore,\n    mark: values.mark,\n    matchBase: values['match-base'],\n    maxDepth: values['max-depth'],\n    nobrace: values.nobrace,\n    nocase: values.nocase,\n    nodir: values.nodir,\n    noext: values.noext,\n    noglobstar: values.noglobstar,\n    platform: values.platform as undefined | NodeJS.Platform,\n    realpath: values.realpath,\n    root: values.root,\n    stat: values.stat,\n    debug: values.debug,\n    posix: values.posix,\n  })\n\n  const cmd = values.cmd\n  if (!cmd) {\n    matches.forEach(m => console.log(m))\n    stream.on('data', f => console.log(f))\n  } else {\n    stream.on('data', f => matches.push(f))\n    stream.on('end', () => foregroundChild(cmd, matches, { shell: true }))\n  }\n} catch (e) {\n  console.error(j.usage())\n  console.error(e instanceof Error ? e.message : String(e))\n  process.exit(1)\n}\n"]}PK~\11glob/dist/esm/walker.jsnu[/**
 * Single-use utility classes to provide functionality to the {@link Glob}
 * methods.
 *
 * @module
 */
import { Minipass } from 'minipass';
import { Ignore } from './ignore.js';
import { Processor } from './processor.js';
const makeIgnore = (ignore, opts) => typeof ignore === 'string' ? new Ignore([ignore], opts)
    : Array.isArray(ignore) ? new Ignore(ignore, opts)
        : ignore;
/**
 * basic walking utilities that all the glob walker types use
 */
export class GlobUtil {
    path;
    patterns;
    opts;
    seen = new Set();
    paused = false;
    aborted = false;
    #onResume = [];
    #ignore;
    #sep;
    signal;
    maxDepth;
    includeChildMatches;
    constructor(patterns, path, opts) {
        this.patterns = patterns;
        this.path = path;
        this.opts = opts;
        this.#sep = !opts.posix && opts.platform === 'win32' ? '\\' : '/';
        this.includeChildMatches = opts.includeChildMatches !== false;
        if (opts.ignore || !this.includeChildMatches) {
            this.#ignore = makeIgnore(opts.ignore ?? [], opts);
            if (!this.includeChildMatches &&
                typeof this.#ignore.add !== 'function') {
                const m = 'cannot ignore child matches, ignore lacks add() method.';
                throw new Error(m);
            }
        }
        // ignore, always set with maxDepth, but it's optional on the
        // GlobOptions type
        /* c8 ignore start */
        this.maxDepth = opts.maxDepth || Infinity;
        /* c8 ignore stop */
        if (opts.signal) {
            this.signal = opts.signal;
            this.signal.addEventListener('abort', () => {
                this.#onResume.length = 0;
            });
        }
    }
    #ignored(path) {
        return this.seen.has(path) || !!this.#ignore?.ignored?.(path);
    }
    #childrenIgnored(path) {
        return !!this.#ignore?.childrenIgnored?.(path);
    }
    // backpressure mechanism
    pause() {
        this.paused = true;
    }
    resume() {
        /* c8 ignore start */
        if (this.signal?.aborted)
            return;
        /* c8 ignore stop */
        this.paused = false;
        let fn = undefined;
        while (!this.paused && (fn = this.#onResume.shift())) {
            fn();
        }
    }
    onResume(fn) {
        if (this.signal?.aborted)
            return;
        /* c8 ignore start */
        if (!this.paused) {
            fn();
        }
        else {
            /* c8 ignore stop */
            this.#onResume.push(fn);
        }
    }
    // do the requisite realpath/stat checking, and return the path
    // to add or undefined to filter it out.
    async matchCheck(e, ifDir) {
        if (ifDir && this.opts.nodir)
            return undefined;
        let rpc;
        if (this.opts.realpath) {
            rpc = e.realpathCached() || (await e.realpath());
            if (!rpc)
                return undefined;
            e = rpc;
        }
        const needStat = e.isUnknown() || this.opts.stat;
        const s = needStat ? await e.lstat() : e;
        if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {
            const target = await s.realpath();
            /* c8 ignore start */
            if (target && (target.isUnknown() || this.opts.stat)) {
                await target.lstat();
            }
            /* c8 ignore stop */
        }
        return this.matchCheckTest(s, ifDir);
    }
    matchCheckTest(e, ifDir) {
        return (e &&
            (this.maxDepth === Infinity || e.depth() <= this.maxDepth) &&
            (!ifDir || e.canReaddir()) &&
            (!this.opts.nodir || !e.isDirectory()) &&
            (!this.opts.nodir ||
                !this.opts.follow ||
                !e.isSymbolicLink() ||
                !e.realpathCached()?.isDirectory()) &&
            !this.#ignored(e)) ?
            e
            : undefined;
    }
    matchCheckSync(e, ifDir) {
        if (ifDir && this.opts.nodir)
            return undefined;
        let rpc;
        if (this.opts.realpath) {
            rpc = e.realpathCached() || e.realpathSync();
            if (!rpc)
                return undefined;
            e = rpc;
        }
        const needStat = e.isUnknown() || this.opts.stat;
        const s = needStat ? e.lstatSync() : e;
        if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {
            const target = s.realpathSync();
            if (target && (target?.isUnknown() || this.opts.stat)) {
                target.lstatSync();
            }
        }
        return this.matchCheckTest(s, ifDir);
    }
    matchFinish(e, absolute) {
        if (this.#ignored(e))
            return;
        // we know we have an ignore if this is false, but TS doesn't
        if (!this.includeChildMatches && this.#ignore?.add) {
            const ign = `${e.relativePosix()}/**`;
            this.#ignore.add(ign);
        }
        const abs = this.opts.absolute === undefined ? absolute : this.opts.absolute;
        this.seen.add(e);
        const mark = this.opts.mark && e.isDirectory() ? this.#sep : '';
        // ok, we have what we need!
        if (this.opts.withFileTypes) {
            this.matchEmit(e);
        }
        else if (abs) {
            const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath();
            this.matchEmit(abs + mark);
        }
        else {
            const rel = this.opts.posix ? e.relativePosix() : e.relative();
            const pre = this.opts.dotRelative && !rel.startsWith('..' + this.#sep) ?
                '.' + this.#sep
                : '';
            this.matchEmit(!rel ? '.' + mark : pre + rel + mark);
        }
    }
    async match(e, absolute, ifDir) {
        const p = await this.matchCheck(e, ifDir);
        if (p)
            this.matchFinish(p, absolute);
    }
    matchSync(e, absolute, ifDir) {
        const p = this.matchCheckSync(e, ifDir);
        if (p)
            this.matchFinish(p, absolute);
    }
    walkCB(target, patterns, cb) {
        /* c8 ignore start */
        if (this.signal?.aborted)
            cb();
        /* c8 ignore stop */
        this.walkCB2(target, patterns, new Processor(this.opts), cb);
    }
    walkCB2(target, patterns, processor, cb) {
        if (this.#childrenIgnored(target))
            return cb();
        if (this.signal?.aborted)
            cb();
        if (this.paused) {
            this.onResume(() => this.walkCB2(target, patterns, processor, cb));
            return;
        }
        processor.processPatterns(target, patterns);
        // done processing.  all of the above is sync, can be abstracted out.
        // subwalks is a map of paths to the entry filters they need
        // matches is a map of paths to [absolute, ifDir] tuples.
        let tasks = 1;
        const next = () => {
            if (--tasks === 0)
                cb();
        };
        for (const [m, absolute, ifDir] of processor.matches.entries()) {
            if (this.#ignored(m))
                continue;
            tasks++;
            this.match(m, absolute, ifDir).then(() => next());
        }
        for (const t of processor.subwalkTargets()) {
            if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {
                continue;
            }
            tasks++;
            const childrenCached = t.readdirCached();
            if (t.calledReaddir())
                this.walkCB3(t, childrenCached, processor, next);
            else {
                t.readdirCB((_, entries) => this.walkCB3(t, entries, processor, next), true);
            }
        }
        next();
    }
    walkCB3(target, entries, processor, cb) {
        processor = processor.filterEntries(target, entries);
        let tasks = 1;
        const next = () => {
            if (--tasks === 0)
                cb();
        };
        for (const [m, absolute, ifDir] of processor.matches.entries()) {
            if (this.#ignored(m))
                continue;
            tasks++;
            this.match(m, absolute, ifDir).then(() => next());
        }
        for (const [target, patterns] of processor.subwalks.entries()) {
            tasks++;
            this.walkCB2(target, patterns, processor.child(), next);
        }
        next();
    }
    walkCBSync(target, patterns, cb) {
        /* c8 ignore start */
        if (this.signal?.aborted)
            cb();
        /* c8 ignore stop */
        this.walkCB2Sync(target, patterns, new Processor(this.opts), cb);
    }
    walkCB2Sync(target, patterns, processor, cb) {
        if (this.#childrenIgnored(target))
            return cb();
        if (this.signal?.aborted)
            cb();
        if (this.paused) {
            this.onResume(() => this.walkCB2Sync(target, patterns, processor, cb));
            return;
        }
        processor.processPatterns(target, patterns);
        // done processing.  all of the above is sync, can be abstracted out.
        // subwalks is a map of paths to the entry filters they need
        // matches is a map of paths to [absolute, ifDir] tuples.
        let tasks = 1;
        const next = () => {
            if (--tasks === 0)
                cb();
        };
        for (const [m, absolute, ifDir] of processor.matches.entries()) {
            if (this.#ignored(m))
                continue;
            this.matchSync(m, absolute, ifDir);
        }
        for (const t of processor.subwalkTargets()) {
            if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {
                continue;
            }
            tasks++;
            const children = t.readdirSync();
            this.walkCB3Sync(t, children, processor, next);
        }
        next();
    }
    walkCB3Sync(target, entries, processor, cb) {
        processor = processor.filterEntries(target, entries);
        let tasks = 1;
        const next = () => {
            if (--tasks === 0)
                cb();
        };
        for (const [m, absolute, ifDir] of processor.matches.entries()) {
            if (this.#ignored(m))
                continue;
            this.matchSync(m, absolute, ifDir);
        }
        for (const [target, patterns] of processor.subwalks.entries()) {
            tasks++;
            this.walkCB2Sync(target, patterns, processor.child(), next);
        }
        next();
    }
}
export class GlobWalker extends GlobUtil {
    matches = new Set();
    constructor(patterns, path, opts) {
        super(patterns, path, opts);
    }
    matchEmit(e) {
        this.matches.add(e);
    }
    async walk() {
        if (this.signal?.aborted)
            throw this.signal.reason;
        if (this.path.isUnknown()) {
            await this.path.lstat();
        }
        await new Promise((res, rej) => {
            this.walkCB(this.path, this.patterns, () => {
                if (this.signal?.aborted) {
                    rej(this.signal.reason);
                }
                else {
                    res(this.matches);
                }
            });
        });
        return this.matches;
    }
    walkSync() {
        if (this.signal?.aborted)
            throw this.signal.reason;
        if (this.path.isUnknown()) {
            this.path.lstatSync();
        }
        // nothing for the callback to do, because this never pauses
        this.walkCBSync(this.path, this.patterns, () => {
            if (this.signal?.aborted)
                throw this.signal.reason;
        });
        return this.matches;
    }
}
export class GlobStream extends GlobUtil {
    results;
    constructor(patterns, path, opts) {
        super(patterns, path, opts);
        this.results = new Minipass({
            signal: this.signal,
            objectMode: true,
        });
        this.results.on('drain', () => this.resume());
        this.results.on('resume', () => this.resume());
    }
    matchEmit(e) {
        this.results.write(e);
        if (!this.results.flowing)
            this.pause();
    }
    stream() {
        const target = this.path;
        if (target.isUnknown()) {
            target.lstat().then(() => {
                this.walkCB(target, this.patterns, () => this.results.end());
            });
        }
        else {
            this.walkCB(target, this.patterns, () => this.results.end());
        }
        return this.results;
    }
    streamSync() {
        if (this.path.isUnknown()) {
            this.path.lstatSync();
        }
        this.walkCBSync(this.path, this.patterns, () => this.results.end());
        return this.results;
    }
}
//# sourceMappingURL=walker.js.mapPK~\?eeglob/dist/esm/ignore.d.tsnu[/// 
import { Minimatch, MinimatchOptions } from 'minimatch';
import { Path } from 'path-scurry';
import { GlobWalkerOpts } from './walker.js';
export interface IgnoreLike {
    ignored?: (p: Path) => boolean;
    childrenIgnored?: (p: Path) => boolean;
    add?: (ignore: string) => void;
}
/**
 * Class used to process ignored patterns
 */
export declare class Ignore implements IgnoreLike {
    relative: Minimatch[];
    relativeChildren: Minimatch[];
    absolute: Minimatch[];
    absoluteChildren: Minimatch[];
    platform: NodeJS.Platform;
    mmopts: MinimatchOptions;
    constructor(ignored: string[], { nobrace, nocase, noext, noglobstar, platform, }: GlobWalkerOpts);
    add(ign: string): void;
    ignored(p: Path): boolean;
    childrenIgnored(p: Path): boolean;
}
//# sourceMappingURL=ignore.d.ts.mapPK~\9Mglob/dist/esm/pattern.jsnu[// this is just a very light wrapper around 2 arrays with an offset index
import { GLOBSTAR } from 'minimatch';
const isPatternList = (pl) => pl.length >= 1;
const isGlobList = (gl) => gl.length >= 1;
/**
 * An immutable-ish view on an array of glob parts and their parsed
 * results
 */
export class Pattern {
    #patternList;
    #globList;
    #index;
    length;
    #platform;
    #rest;
    #globString;
    #isDrive;
    #isUNC;
    #isAbsolute;
    #followGlobstar = true;
    constructor(patternList, globList, index, platform) {
        if (!isPatternList(patternList)) {
            throw new TypeError('empty pattern list');
        }
        if (!isGlobList(globList)) {
            throw new TypeError('empty glob list');
        }
        if (globList.length !== patternList.length) {
            throw new TypeError('mismatched pattern list and glob list lengths');
        }
        this.length = patternList.length;
        if (index < 0 || index >= this.length) {
            throw new TypeError('index out of range');
        }
        this.#patternList = patternList;
        this.#globList = globList;
        this.#index = index;
        this.#platform = platform;
        // normalize root entries of absolute patterns on initial creation.
        if (this.#index === 0) {
            // c: => ['c:/']
            // C:/ => ['C:/']
            // C:/x => ['C:/', 'x']
            // //host/share => ['//host/share/']
            // //host/share/ => ['//host/share/']
            // //host/share/x => ['//host/share/', 'x']
            // /etc => ['/', 'etc']
            // / => ['/']
            if (this.isUNC()) {
                // '' / '' / 'host' / 'share'
                const [p0, p1, p2, p3, ...prest] = this.#patternList;
                const [g0, g1, g2, g3, ...grest] = this.#globList;
                if (prest[0] === '') {
                    // ends in /
                    prest.shift();
                    grest.shift();
                }
                const p = [p0, p1, p2, p3, ''].join('/');
                const g = [g0, g1, g2, g3, ''].join('/');
                this.#patternList = [p, ...prest];
                this.#globList = [g, ...grest];
                this.length = this.#patternList.length;
            }
            else if (this.isDrive() || this.isAbsolute()) {
                const [p1, ...prest] = this.#patternList;
                const [g1, ...grest] = this.#globList;
                if (prest[0] === '') {
                    // ends in /
                    prest.shift();
                    grest.shift();
                }
                const p = p1 + '/';
                const g = g1 + '/';
                this.#patternList = [p, ...prest];
                this.#globList = [g, ...grest];
                this.length = this.#patternList.length;
            }
        }
    }
    /**
     * The first entry in the parsed list of patterns
     */
    pattern() {
        return this.#patternList[this.#index];
    }
    /**
     * true of if pattern() returns a string
     */
    isString() {
        return typeof this.#patternList[this.#index] === 'string';
    }
    /**
     * true of if pattern() returns GLOBSTAR
     */
    isGlobstar() {
        return this.#patternList[this.#index] === GLOBSTAR;
    }
    /**
     * true if pattern() returns a regexp
     */
    isRegExp() {
        return this.#patternList[this.#index] instanceof RegExp;
    }
    /**
     * The /-joined set of glob parts that make up this pattern
     */
    globString() {
        return (this.#globString =
            this.#globString ||
                (this.#index === 0 ?
                    this.isAbsolute() ?
                        this.#globList[0] + this.#globList.slice(1).join('/')
                        : this.#globList.join('/')
                    : this.#globList.slice(this.#index).join('/')));
    }
    /**
     * true if there are more pattern parts after this one
     */
    hasMore() {
        return this.length > this.#index + 1;
    }
    /**
     * The rest of the pattern after this part, or null if this is the end
     */
    rest() {
        if (this.#rest !== undefined)
            return this.#rest;
        if (!this.hasMore())
            return (this.#rest = null);
        this.#rest = new Pattern(this.#patternList, this.#globList, this.#index + 1, this.#platform);
        this.#rest.#isAbsolute = this.#isAbsolute;
        this.#rest.#isUNC = this.#isUNC;
        this.#rest.#isDrive = this.#isDrive;
        return this.#rest;
    }
    /**
     * true if the pattern represents a //unc/path/ on windows
     */
    isUNC() {
        const pl = this.#patternList;
        return this.#isUNC !== undefined ?
            this.#isUNC
            : (this.#isUNC =
                this.#platform === 'win32' &&
                    this.#index === 0 &&
                    pl[0] === '' &&
                    pl[1] === '' &&
                    typeof pl[2] === 'string' &&
                    !!pl[2] &&
                    typeof pl[3] === 'string' &&
                    !!pl[3]);
    }
    // pattern like C:/...
    // split = ['C:', ...]
    // XXX: would be nice to handle patterns like `c:*` to test the cwd
    // in c: for *, but I don't know of a way to even figure out what that
    // cwd is without actually chdir'ing into it?
    /**
     * True if the pattern starts with a drive letter on Windows
     */
    isDrive() {
        const pl = this.#patternList;
        return this.#isDrive !== undefined ?
            this.#isDrive
            : (this.#isDrive =
                this.#platform === 'win32' &&
                    this.#index === 0 &&
                    this.length > 1 &&
                    typeof pl[0] === 'string' &&
                    /^[a-z]:$/i.test(pl[0]));
    }
    // pattern = '/' or '/...' or '/x/...'
    // split = ['', ''] or ['', ...] or ['', 'x', ...]
    // Drive and UNC both considered absolute on windows
    /**
     * True if the pattern is rooted on an absolute path
     */
    isAbsolute() {
        const pl = this.#patternList;
        return this.#isAbsolute !== undefined ?
            this.#isAbsolute
            : (this.#isAbsolute =
                (pl[0] === '' && pl.length > 1) ||
                    this.isDrive() ||
                    this.isUNC());
    }
    /**
     * consume the root of the pattern, and return it
     */
    root() {
        const p = this.#patternList[0];
        return (typeof p === 'string' && this.isAbsolute() && this.#index === 0) ?
            p
            : '';
    }
    /**
     * Check to see if the current globstar pattern is allowed to follow
     * a symbolic link.
     */
    checkFollowGlobstar() {
        return !(this.#index === 0 ||
            !this.isGlobstar() ||
            !this.#followGlobstar);
    }
    /**
     * Mark that the current globstar pattern is following a symbolic link
     */
    markFollowGlobstar() {
        if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar)
            return false;
        this.#followGlobstar = false;
        return true;
    }
}
//# sourceMappingURL=pattern.js.mapPK~\}glob/dist/esm/glob.d.ts.mapnu[{"version":3,"file":"glob.d.ts","source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A;IAClB,IAAI,EAAE,OAAO,CAAA;IACb,MAAM,CAAC,EAAE,WAAW,CAAA;IACpB,oBAAoB,EAAE,OAAO,CAAA;IAC7B,aAAa,EAAE,SAAS,CAAC,IAAI,CAAC,CAAA;IAC9B,mBAAmB,EAAE,OAAO,CAAA;IAE5B;;OAEG;IACH,IAAI,EAAE,IAAI,CAAA;IAEV;;OAEG;IACH,QAAQ,EAAE,OAAO,EAAE,CAAA;IAEnB;;;;;;;;;;;OAWG;gBACS,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,EAAE,IAAI,EAAE,IAAI;IA2HlD;;OAEG;IACG,IAAI,IAAI,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IAoBpC;;OAEG;IACH,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IAgBzB;;OAEG;IACH,MAAM,IAAI,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;IAc9C;;OAEG;IACH,UAAU,IAAI,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;IAclD;;;OAGG;IACH,WAAW,IAAI,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC;IAGlD,CAAC,MAAM,CAAC,QAAQ,CAAC;IAIjB;;;OAGG;IACH,OAAO,IAAI,cAAc,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC;IAGnD,CAAC,MAAM,CAAC,aAAa,CAAC;CAGvB"}PK~\nUglob/dist/esm/index.d.tsnu[import { Minipass } from 'minipass';
import { Path } from 'path-scurry';
import type { GlobOptions, GlobOptionsWithFileTypesFalse, GlobOptionsWithFileTypesTrue, GlobOptionsWithFileTypesUnset } from './glob.js';
import { Glob } from './glob.js';
export { escape, unescape } from 'minimatch';
export type { FSOption, Path, WalkOptions, WalkOptionsWithFileTypesTrue, WalkOptionsWithFileTypesUnset, } from 'path-scurry';
export { Glob } from './glob.js';
export type { GlobOptions, GlobOptionsWithFileTypesFalse, GlobOptionsWithFileTypesTrue, GlobOptionsWithFileTypesUnset, } from './glob.js';
export { hasMagic } from './has-magic.js';
export { Ignore } from './ignore.js';
export type { IgnoreLike } from './ignore.js';
export type { MatchStream } from './walker.js';
/**
 * Syncronous form of {@link globStream}. Will read all the matches as fast as
 * you consume them, even all in a single tick if you consume them immediately,
 * but will still respond to backpressure if they're not consumed immediately.
 */
export declare function globStreamSync(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): Minipass;
export declare function globStreamSync(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): Minipass;
export declare function globStreamSync(pattern: string | string[], options: GlobOptionsWithFileTypesUnset): Minipass;
export declare function globStreamSync(pattern: string | string[], options: GlobOptions): Minipass | Minipass;
/**
 * Return a stream that emits all the strings or `Path` objects and
 * then emits `end` when completed.
 */
export declare function globStream(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): Minipass;
export declare function globStream(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): Minipass;
export declare function globStream(pattern: string | string[], options?: GlobOptionsWithFileTypesUnset | undefined): Minipass;
export declare function globStream(pattern: string | string[], options: GlobOptions): Minipass | Minipass;
/**
 * Synchronous form of {@link glob}
 */
export declare function globSync(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): string[];
export declare function globSync(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): Path[];
export declare function globSync(pattern: string | string[], options?: GlobOptionsWithFileTypesUnset | undefined): string[];
export declare function globSync(pattern: string | string[], options: GlobOptions): Path[] | string[];
/**
 * Perform an asynchronous glob search for the pattern(s) specified. Returns
 * [Path](https://isaacs.github.io/path-scurry/classes/PathBase) objects if the
 * {@link withFileTypes} option is set to `true`. See {@link GlobOptions} for
 * full option descriptions.
 */
declare function glob_(pattern: string | string[], options?: GlobOptionsWithFileTypesUnset | undefined): Promise;
declare function glob_(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): Promise;
declare function glob_(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): Promise;
declare function glob_(pattern: string | string[], options: GlobOptions): Promise;
/**
 * Return a sync iterator for walking glob pattern matches.
 */
export declare function globIterateSync(pattern: string | string[], options?: GlobOptionsWithFileTypesUnset | undefined): Generator;
export declare function globIterateSync(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): Generator;
export declare function globIterateSync(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): Generator;
export declare function globIterateSync(pattern: string | string[], options: GlobOptions): Generator | Generator;
/**
 * Return an async iterator for walking glob pattern matches.
 */
export declare function globIterate(pattern: string | string[], options?: GlobOptionsWithFileTypesUnset | undefined): AsyncGenerator;
export declare function globIterate(pattern: string | string[], options: GlobOptionsWithFileTypesTrue): AsyncGenerator;
export declare function globIterate(pattern: string | string[], options: GlobOptionsWithFileTypesFalse): AsyncGenerator;
export declare function globIterate(pattern: string | string[], options: GlobOptions): AsyncGenerator | AsyncGenerator;
export declare const streamSync: typeof globStreamSync;
export declare const stream: typeof globStream & {
    sync: typeof globStreamSync;
};
export declare const iterateSync: typeof globIterateSync;
export declare const iterate: typeof globIterate & {
    sync: typeof globIterateSync;
};
export declare const sync: typeof globSync & {
    stream: typeof globStreamSync;
    iterate: typeof globIterateSync;
};
export declare const glob: typeof glob_ & {
    glob: typeof glob_;
    globSync: typeof globSync;
    sync: typeof globSync & {
        stream: typeof globStreamSync;
        iterate: typeof globIterateSync;
    };
    globStream: typeof globStream;
    stream: typeof globStream & {
        sync: typeof globStreamSync;
    };
    globStreamSync: typeof globStreamSync;
    streamSync: typeof globStreamSync;
    globIterate: typeof globIterate;
    iterate: typeof globIterate & {
        sync: typeof globIterateSync;
    };
    globIterateSync: typeof globIterateSync;
    iterateSync: typeof globIterateSync;
    Glob: typeof Glob;
    hasMagic: (pattern: string | string[], options?: GlobOptions) => boolean;
    escape: (s: string, { windowsPathsNoEscape, }?: Pick | undefined) => string;
    unescape: (s: string, { windowsPathsNoEscape, }?: Pick | undefined) => string;
};
//# sourceMappingURL=index.d.ts.mapPK~\glob/dist/esm/ignore.jsnu[// give it a pattern, and it'll be able to tell you if
// a given path should be ignored.
// Ignoring a path ignores its children if the pattern ends in /**
// Ignores are always parsed in dot:true mode
import { Minimatch } from 'minimatch';
import { Pattern } from './pattern.js';
const defaultPlatform = (typeof process === 'object' &&
    process &&
    typeof process.platform === 'string') ?
    process.platform
    : 'linux';
/**
 * Class used to process ignored patterns
 */
export class Ignore {
    relative;
    relativeChildren;
    absolute;
    absoluteChildren;
    platform;
    mmopts;
    constructor(ignored, { nobrace, nocase, noext, noglobstar, platform = defaultPlatform, }) {
        this.relative = [];
        this.absolute = [];
        this.relativeChildren = [];
        this.absoluteChildren = [];
        this.platform = platform;
        this.mmopts = {
            dot: true,
            nobrace,
            nocase,
            noext,
            noglobstar,
            optimizationLevel: 2,
            platform,
            nocomment: true,
            nonegate: true,
        };
        for (const ign of ignored)
            this.add(ign);
    }
    add(ign) {
        // this is a little weird, but it gives us a clean set of optimized
        // minimatch matchers, without getting tripped up if one of them
        // ends in /** inside a brace section, and it's only inefficient at
        // the start of the walk, not along it.
        // It'd be nice if the Pattern class just had a .test() method, but
        // handling globstars is a bit of a pita, and that code already lives
        // in minimatch anyway.
        // Another way would be if maybe Minimatch could take its set/globParts
        // as an option, and then we could at least just use Pattern to test
        // for absolute-ness.
        // Yet another way, Minimatch could take an array of glob strings, and
        // a cwd option, and do the right thing.
        const mm = new Minimatch(ign, this.mmopts);
        for (let i = 0; i < mm.set.length; i++) {
            const parsed = mm.set[i];
            const globParts = mm.globParts[i];
            /* c8 ignore start */
            if (!parsed || !globParts) {
                throw new Error('invalid pattern object');
            }
            // strip off leading ./ portions
            // https://github.com/isaacs/node-glob/issues/570
            while (parsed[0] === '.' && globParts[0] === '.') {
                parsed.shift();
                globParts.shift();
            }
            /* c8 ignore stop */
            const p = new Pattern(parsed, globParts, 0, this.platform);
            const m = new Minimatch(p.globString(), this.mmopts);
            const children = globParts[globParts.length - 1] === '**';
            const absolute = p.isAbsolute();
            if (absolute)
                this.absolute.push(m);
            else
                this.relative.push(m);
            if (children) {
                if (absolute)
                    this.absoluteChildren.push(m);
                else
                    this.relativeChildren.push(m);
            }
        }
    }
    ignored(p) {
        const fullpath = p.fullpath();
        const fullpaths = `${fullpath}/`;
        const relative = p.relative() || '.';
        const relatives = `${relative}/`;
        for (const m of this.relative) {
            if (m.match(relative) || m.match(relatives))
                return true;
        }
        for (const m of this.absolute) {
            if (m.match(fullpath) || m.match(fullpaths))
                return true;
        }
        return false;
    }
    childrenIgnored(p) {
        const fullpath = p.fullpath() + '/';
        const relative = (p.relative() || '.') + '/';
        for (const m of this.relativeChildren) {
            if (m.match(relative))
                return true;
        }
        for (const m of this.absoluteChildren) {
            if (m.match(fullpath))
                return true;
        }
        return false;
    }
}
//# sourceMappingURL=ignore.js.mapPK~\!ĩ  glob/dist/esm/index.js.mapnu[{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AAS5C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAA;AAEzC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA;AAQ5C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAOhC,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAA;AACzC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AAyBpC,MAAM,UAAU,cAAc,CAC5B,OAA0B,EAC1B,UAAuB,EAAE;IAEzB,OAAO,IAAI,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,UAAU,EAAE,CAAA;AAChD,CAAC;AAsBD,MAAM,UAAU,UAAU,CACxB,OAA0B,EAC1B,UAAuB,EAAE;I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,CAAC,KAAK,EAAE;IACvC,IAAI,EAAE,KAAK;IACX,QAAQ;IACR,IAAI;IACJ,UAAU;IACV,MAAM;IACN,cAAc;IACd,UAAU;IACV,WAAW;IACX,OAAO;IACP,eAAe;IACf,WAAW;IACX,IAAI;IACJ,QAAQ;IACR,MAAM;IACN,QAAQ;CACT,CAAC,CAAA;AACF,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA","sourcesContent":["import { escape, unescape } from 'minimatch'\nimport { Minipass } from 'minipass'\nimport { Path } from 'path-scurry'\nimport type {\n  GlobOptions,\n  GlobOptionsWithFileTypesFalse,\n  GlobOptionsWithFileTypesTrue,\n  GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nimport { Glob } from './glob.js'\nimport { hasMagic } from './has-magic.js'\n\nexport { escape, unescape } from 'minimatch'\nexport type {\n  FSOption,\n  Path,\n  WalkOptions,\n  WalkOptionsWithFileTypesTrue,\n  WalkOptionsWithFileTypesUnset,\n} from 'path-scurry'\nexport { Glob } from './glob.js'\nexport type {\n  GlobOptions,\n  GlobOptionsWithFileTypesFalse,\n  GlobOptionsWithFileTypesTrue,\n  GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nexport { hasMagic } from './has-magic.js'\nexport { Ignore } from './ignore.js'\nexport type { IgnoreLike } from './ignore.js'\nexport type { MatchStream } from './walker.js'\n\n/**\n * Syncronous form of {@link globStream}. Will read all the matches as fast as\n * you consume them, even all in a single tick if you consume them immediately,\n * but will still respond to backpressure if they're not consumed immediately.\n */\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesUnset,\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptions,\n): Minipass | Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).streamSync()\n}\n\n/**\n * Return a stream that emits all the strings or `Path` objects and\n * then emits `end` when completed.\n */\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptions,\n): Minipass | Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).stream()\n}\n\n/**\n * Synchronous form of {@link glob}\n */\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Path[]\nexport function globSync(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptions,\n): Path[] | string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).walkSync()\n}\n\n/**\n * Perform an asynchronous glob search for the pattern(s) specified. Returns\n * [Path](https://isaacs.github.io/path-scurry/classes/PathBase) objects if the\n * {@link withFileTypes} option is set to `true`. See {@link GlobOptions} for\n * full option descriptions.\n */\nasync function glob_(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptions,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).walk()\n}\n\n/**\n * Return a sync iterator for walking glob pattern matches.\n */\nexport function globIterateSync(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptions,\n): Generator | Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).iterateSync()\n}\n\n/**\n * Return an async iterator for walking glob pattern matches.\n */\nexport function globIterate(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptions,\n): AsyncGenerator | AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).iterate()\n}\n\n// aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc\nexport const streamSync = globStreamSync\nexport const stream = Object.assign(globStream, { sync: globStreamSync })\nexport const iterateSync = globIterateSync\nexport const iterate = Object.assign(globIterate, {\n  sync: globIterateSync,\n})\nexport const sync = Object.assign(globSync, {\n  stream: globStreamSync,\n  iterate: globIterateSync,\n})\n\nexport const glob = Object.assign(glob_, {\n  glob: glob_,\n  globSync,\n  sync,\n  globStream,\n  stream,\n  globStreamSync,\n  streamSync,\n  globIterate,\n  iterate,\n  globIterateSync,\n  iterateSync,\n  Glob,\n  hasMagic,\n  escape,\n  unescape,\n})\nglob.glob = glob\n"]}PK~\Ûnnglob/dist/esm/glob.js.mapnu[{"version":3,"file":"glob.js","sourceRoot":"","sources":["../../src/glob.ts"],"names":[],"mappings":"AAAA,OAAO,EAA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a,CAAC;QACpB,OAAO,IAAI,CAAC,OAAO,EAAE,CAAA;IACvB,CAAC;CACF","sourcesContent":["import { Minimatch, MinimatchOptions } from 'minimatch'\nimport { Minipass } from 'minipass'\nimport { fileURLToPath } from 'node:url'\nimport {\n  FSOption,\n  Path,\n  PathScurry,\n  PathScurryDarwin,\n  PathScurryPosix,\n  PathScurryWin32,\n} from 'path-scurry'\nimport { IgnoreLike } from './ignore.js'\nimport { Pattern } from './pattern.js'\nimport { GlobStream, GlobWalker } from './walker.js'\n\nexport type MatchSet = Minimatch['set']\nexport type GlobParts = Exclude\n\n// if no process global, just call it linux.\n// so we default to case-sensitive, / separators\nconst defaultPlatform: NodeJS.Platform =\n  (\n    typeof process === 'object' &&\n    process &&\n    typeof process.platform === 'string'\n  ) ?\n    process.platform\n  : 'linux'\n\n/**\n * A `GlobOptions` object may be provided to any of the exported methods, and\n * must be provided to the `Glob` constructor.\n *\n * All options are optional, boolean, and false by default, unless otherwise\n * noted.\n *\n * All resolved options are added to the Glob object as properties.\n *\n * If you are running many `glob` operations, you can pass a Glob object as the\n * `options` argument to a subsequent operation to share the previously loaded\n * cache.\n */\nexport interface GlobOptions {\n  /**\n   * Set to `true` to always receive absolute paths for\n   * matched files. Set to `false` to always return relative paths.\n   *\n   * When this option is not set, absolute paths are returned for patterns\n   * that are absolute, and otherwise paths are returned that are relative\n   * to the `cwd` setting.\n   *\n   * This does _not_ make an extra system call to get\n   * the realpath, it only does string path resolution.\n   *\n   * Conflicts with {@link withFileTypes}\n   */\n  absolute?: boolean\n\n  /**\n   * Set to false to enable {@link windowsPathsNoEscape}\n   *\n   * @deprecated\n   */\n  allowWindowsEscape?: boolean\n\n  /**\n   * The current working directory in which to search. Defaults to\n   * `process.cwd()`.\n   *\n   * May be eiher a string path or a `file://` URL object or string.\n   */\n  cwd?: string | URL\n\n  /**\n   * Include `.dot` files in normal matches and `globstar`\n   * matches. Note that an explicit dot in a portion of the pattern\n   * will always match dot files.\n   */\n  dot?: boolean\n\n  /**\n   * Prepend all relative path strings with `./` (or `.\\` on Windows).\n   *\n   * Without this option, returned relative paths are \"bare\", so instead of\n   * returning `'./foo/bar'`, they are returned as `'foo/bar'`.\n   *\n   * Relative patterns starting with `'../'` are not prepended with `./`, even\n   * if this option is set.\n   */\n  dotRelative?: boolean\n\n  /**\n   * Follow symlinked directories when expanding `**`\n   * patterns. This can result in a lot of duplicate references in\n   * the presence of cyclic links, and make performance quite bad.\n   *\n   * By default, a `**` in a pattern will follow 1 symbolic link if\n   * it is not the first item in the pattern, or none if it is the\n   * first item in the pattern, following the same behavior as Bash.\n   */\n  follow?: boolean\n\n  /**\n   * string or string[], or an object with `ignore` and `ignoreChildren`\n   * methods.\n   *\n   * If a string or string[] is provided, then this is treated as a glob\n   * pattern or array of glob patterns to exclude from matches. To ignore all\n   * children within a directory, as well as the entry itself, append `'/**'`\n   * to the ignore pattern.\n   *\n   * **Note** `ignore` patterns are _always_ in `dot:true` mode, regardless of\n   * any other settings.\n   *\n   * If an object is provided that has `ignored(path)` and/or\n   * `childrenIgnored(path)` methods, then these methods will be called to\n   * determine whether any Path is a match or if its children should be\n   * traversed, respectively.\n   */\n  ignore?: string | string[] | IgnoreLike\n\n  /**\n   * Treat brace expansion like `{a,b}` as a \"magic\" pattern. Has no\n   * effect if {@link nobrace} is set.\n   *\n   * Only has effect on the {@link hasMagic} function.\n   */\n  magicalBraces?: boolean\n\n  /**\n   * Add a `/` character to directory matches. Note that this requires\n   * additional stat calls in some cases.\n   */\n  mark?: boolean\n\n  /**\n   * Perform a basename-only match if the pattern does not contain any slash\n   * characters. That is, `*.js` would be treated as equivalent to\n   * `**\\/*.js`, matching all js files in all directories.\n   */\n  matchBase?: boolean\n\n  /**\n   * Limit the directory traversal to a given depth below the cwd.\n   * Note that this does NOT prevent traversal to sibling folders,\n   * root patterns, and so on. It only limits the maximum folder depth\n   * that the walk will descend, relative to the cwd.\n   */\n  maxDepth?: number\n\n  /**\n   * Do not expand `{a,b}` and `{1..3}` brace sets.\n   */\n  nobrace?: boolean\n\n  /**\n   * Perform a case-insensitive match. This defaults to `true` on macOS and\n   * Windows systems, and `false` on all others.\n   *\n   * **Note** `nocase` should only be explicitly set when it is\n   * known that the filesystem's case sensitivity differs from the\n   * platform default. If set `true` on case-sensitive file\n   * systems, or `false` on case-insensitive file systems, then the\n   * walk may return more or less results than expected.\n   */\n  nocase?: boolean\n\n  /**\n   * Do not match directories, only files. (Note: to match\n   * _only_ directories, put a `/` at the end of the pattern.)\n   */\n  nodir?: boolean\n\n  /**\n   * Do not match \"extglob\" patterns such as `+(a|b)`.\n   */\n  noext?: boolean\n\n  /**\n   * Do not match `**` against multiple filenames. (Ie, treat it as a normal\n   * `*` instead.)\n   *\n   * Conflicts with {@link matchBase}\n   */\n  noglobstar?: boolean\n\n  /**\n   * Defaults to value of `process.platform` if available, or `'linux'` if\n   * not. Setting `platform:'win32'` on non-Windows systems may cause strange\n   * behavior.\n   */\n  platform?: NodeJS.Platform\n\n  /**\n   * Set to true to call `fs.realpath` on all of the\n   * results. In the case of an entry that cannot be resolved, the\n   * entry is omitted. This incurs a slight performance penalty, of\n   * course, because of the added system calls.\n   */\n  realpath?: boolean\n\n  /**\n   *\n   * A string path resolved against the `cwd` option, which\n   * is used as the starting point for absolute patterns that start\n   * with `/`, (but not drive letters or UNC paths on Windows).\n   *\n   * Note that this _doesn't_ necessarily limit the walk to the\n   * `root` directory, and doesn't affect the cwd starting point for\n   * non-absolute patterns. A pattern containing `..` will still be\n   * able to traverse out of the root directory, if it is not an\n   * actual root directory on the filesystem, and any non-absolute\n   * patterns will be matched in the `cwd`. For example, the\n   * pattern `/../*` with `{root:'/some/path'}` will return all\n   * files in `/some`, not all files in `/some/path`. The pattern\n   * `*` with `{root:'/some/path'}` will return all the entries in\n   * the cwd, not the entries in `/some/path`.\n   *\n   * To start absolute and non-absolute patterns in the same\n   * path, you can use `{root:''}`. However, be aware that on\n   * Windows systems, a pattern like `x:/*` or `//host/share/*` will\n   * _always_ start in the `x:/` or `//host/share` directory,\n   * regardless of the `root` setting.\n   */\n  root?: string\n\n  /**\n   * A [PathScurry](http://npm.im/path-scurry) object used\n   * to traverse the file system. If the `nocase` option is set\n   * explicitly, then any provided `scurry` object must match this\n   * setting.\n   */\n  scurry?: PathScurry\n\n  /**\n   * Call `lstat()` on all entries, whether required or not to determine\n   * if it's a valid match. When used with {@link withFileTypes}, this means\n   * that matches will include data such as modified time, permissions, and\n   * so on.  Note that this will incur a performance cost due to the added\n   * system calls.\n   */\n  stat?: boolean\n\n  /**\n   * An AbortSignal which will cancel the Glob walk when\n   * triggered.\n   */\n  signal?: AbortSignal\n\n  /**\n   * Use `\\\\` as a path separator _only_, and\n   *  _never_ as an escape character. If set, all `\\\\` characters are\n   *  replaced with `/` in the pattern.\n   *\n   *  Note that this makes it **impossible** to match against paths\n   *  containing literal glob pattern characters, but allows matching\n   *  with patterns constructed using `path.join()` and\n   *  `path.resolve()` on Windows platforms, mimicking the (buggy!)\n   *  behavior of Glob v7 and before on Windows. Please use with\n   *  caution, and be mindful of [the caveat below about Windows\n   *  paths](#windows). (For legacy reasons, this is also set if\n   *  `allowWindowsEscape` is set to the exact value `false`.)\n   */\n  windowsPathsNoEscape?: boolean\n\n  /**\n   * Return [PathScurry](http://npm.im/path-scurry)\n   * `Path` objects instead of strings. These are similar to a\n   * NodeJS `Dirent` object, but with additional methods and\n   * properties.\n   *\n   * Conflicts with {@link absolute}\n   */\n  withFileTypes?: boolean\n\n  /**\n   * An fs implementation to override some or all of the defaults.  See\n   * http://npm.im/path-scurry for details about what can be overridden.\n   */\n  fs?: FSOption\n\n  /**\n   * Just passed along to Minimatch.  Note that this makes all pattern\n   * matching operations slower and *extremely* noisy.\n   */\n  debug?: boolean\n\n  /**\n   * Return `/` delimited paths, even on Windows.\n   *\n   * On posix systems, this has no effect.  But, on Windows, it means that\n   * paths will be `/` delimited, and absolute paths will be their full\n   * resolved UNC forms, eg instead of `'C:\\\\foo\\\\bar'`, it would return\n   * `'//?/C:/foo/bar'`\n   */\n  posix?: boolean\n\n  /**\n   * Do not match any children of any matches. For example, the pattern\n   * `**\\/foo` would match `a/foo`, but not `a/foo/b/foo` in this mode.\n   *\n   * This is especially useful for cases like \"find all `node_modules`\n   * folders, but not the ones in `node_modules`\".\n   *\n   * In order to support this, the `Ignore` implementation must support an\n   * `add(pattern: string)` method. If using the default `Ignore` class, then\n   * this is fine, but if this is set to `false`, and a custom `Ignore` is\n   * provided that does not have an `add()` method, then it will throw an\n   * error.\n   *\n   * **Caveat** It *only* ignores matches that would be a descendant of a\n   * previous match, and only if that descendant is matched *after* the\n   * ancestor is encountered. Since the file system walk happens in\n   * indeterminate order, it's possible that a match will already be added\n   * before its ancestor, if multiple or braced patterns are used.\n   *\n   * For example:\n   *\n   * ```ts\n   * const results = await glob([\n   *   // likely to match first, since it's just a stat\n   *   'a/b/c/d/e/f',\n   *\n   *   // this pattern is more complicated! It must to various readdir()\n   *   // calls and test the results against a regular expression, and that\n   *   // is certainly going to take a little bit longer.\n   *   //\n   *   // So, later on, it encounters a match at 'a/b/c/d/e', but it's too\n   *   // late to ignore a/b/c/d/e/f, because it's already been emitted.\n   *   'a/[bdf]/?/[a-z]/*',\n   * ], { includeChildMatches: false })\n   * ```\n   *\n   * It's best to only set this to `false` if you can be reasonably sure that\n   * no components of the pattern will potentially match one another's file\n   * system descendants, or if the occasional included child entry will not\n   * cause problems.\n   *\n   * @default true\n   */\n  includeChildMatches?: boolean\n}\n\nexport type GlobOptionsWithFileTypesTrue = GlobOptions & {\n  withFileTypes: true\n  // string options not relevant if returning Path objects.\n  absolute?: undefined\n  mark?: undefined\n  posix?: undefined\n}\n\nexport type GlobOptionsWithFileTypesFalse = GlobOptions & {\n  withFileTypes?: false\n}\n\nexport type GlobOptionsWithFileTypesUnset = GlobOptions & {\n  withFileTypes?: undefined\n}\n\nexport type Result =\n  Opts extends GlobOptionsWithFileTypesTrue ? Path\n  : Opts extends GlobOptionsWithFileTypesFalse ? string\n  : Opts extends GlobOptionsWithFileTypesUnset ? string\n  : string | Path\nexport type Results = Result[]\n\nexport type FileTypes =\n  Opts extends GlobOptionsWithFileTypesTrue ? true\n  : Opts extends GlobOptionsWithFileTypesFalse ? false\n  : Opts extends GlobOptionsWithFileTypesUnset ? false\n  : boolean\n\n/**\n * An object that can perform glob pattern traversals.\n */\nexport class Glob implements GlobOptions {\n  absolute?: boolean\n  cwd: string\n  root?: string\n  dot: boolean\n  dotRelative: boolean\n  follow: boolean\n  ignore?: string | string[] | IgnoreLike\n  magicalBraces: boolean\n  mark?: boolean\n  matchBase: boolean\n  maxDepth: number\n  nobrace: boolean\n  nocase: boolean\n  nodir: boolean\n  noext: boolean\n  noglobstar: boolean\n  pattern: string[]\n  platform: NodeJS.Platform\n  realpath: boolean\n  scurry: PathScurry\n  stat: boolean\n  signal?: AbortSignal\n  windowsPathsNoEscape: boolean\n  withFileTypes: FileTypes\n  includeChildMatches: boolean\n\n  /**\n   * The options provided to the constructor.\n   */\n  opts: Opts\n\n  /**\n   * An array of parsed immutable {@link Pattern} objects.\n   */\n  patterns: Pattern[]\n\n  /**\n   * All options are stored as properties on the `Glob` object.\n   *\n   * See {@link GlobOptions} for full options descriptions.\n   *\n   * Note that a previous `Glob` object can be passed as the\n   * `GlobOptions` to another `Glob` instantiation to re-use settings\n   * and caches with a new pattern.\n   *\n   * Traversal functions can be called multiple times to run the walk\n   * again.\n   */\n  constructor(pattern: string | string[], opts: Opts) {\n    /* c8 ignore start */\n    if (!opts) throw new TypeError('glob options required')\n    /* c8 ignore stop */\n    this.withFileTypes = !!opts.withFileTypes as FileTypes\n    this.signal = opts.signal\n    this.follow = !!opts.follow\n    this.dot = !!opts.dot\n    this.dotRelative = !!opts.dotRelative\n    this.nodir = !!opts.nodir\n    this.mark = !!opts.mark\n    if (!opts.cwd) {\n      this.cwd = ''\n    } else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) {\n      opts.cwd = fileURLToPath(opts.cwd)\n    }\n    this.cwd = opts.cwd || ''\n    this.root = opts.root\n    this.magicalBraces = !!opts.magicalBraces\n    this.nobrace = !!opts.nobrace\n    this.noext = !!opts.noext\n    this.realpath = !!opts.realpath\n    this.absolute = opts.absolute\n    this.includeChildMatches = opts.includeChildMatches !== false\n\n    this.noglobstar = !!opts.noglobstar\n    this.matchBase = !!opts.matchBase\n    this.maxDepth =\n      typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity\n    this.stat = !!opts.stat\n    this.ignore = opts.ignore\n\n    if (this.withFileTypes && this.absolute !== undefined) {\n      throw new Error('cannot set absolute and withFileTypes:true')\n    }\n\n    if (typeof pattern === 'string') {\n      pattern = [pattern]\n    }\n\n    this.windowsPathsNoEscape =\n      !!opts.windowsPathsNoEscape ||\n      (opts as { allowWindowsEscape?: boolean }).allowWindowsEscape ===\n        false\n\n    if (this.windowsPathsNoEscape) {\n      pattern = pattern.map(p => p.replace(/\\\\/g, '/'))\n    }\n\n    if (this.matchBase) {\n      if (opts.noglobstar) {\n        throw new TypeError('base matching requires globstar')\n      }\n      pattern = pattern.map(p => (p.includes('/') ? p : `./**/${p}`))\n    }\n\n    this.pattern = pattern\n\n    this.platform = opts.platform || defaultPlatform\n    this.opts = { ...opts, platform: this.platform }\n    if (opts.scurry) {\n      this.scurry = opts.scurry\n      if (\n        opts.nocase !== undefined &&\n        opts.nocase !== opts.scurry.nocase\n      ) {\n        throw new Error('nocase option contradicts provided scurry option')\n      }\n    } else {\n      const Scurry =\n        opts.platform === 'win32' ? PathScurryWin32\n        : opts.platform === 'darwin' ? PathScurryDarwin\n        : opts.platform ? PathScurryPosix\n        : PathScurry\n      this.scurry = new Scurry(this.cwd, {\n        nocase: opts.nocase,\n        fs: opts.fs,\n      })\n    }\n    this.nocase = this.scurry.nocase\n\n    // If you do nocase:true on a case-sensitive file system, then\n    // we need to use regexps instead of strings for non-magic\n    // path portions, because statting `aBc` won't return results\n    // for the file `AbC` for example.\n    const nocaseMagicOnly =\n      this.platform === 'darwin' || this.platform === 'win32'\n\n    const mmo: MinimatchOptions = {\n      // default nocase based on platform\n      ...opts,\n      dot: this.dot,\n      matchBase: this.matchBase,\n      nobrace: this.nobrace,\n      nocase: this.nocase,\n      nocaseMagicOnly,\n      nocomment: true,\n      noext: this.noext,\n      nonegate: true,\n      optimizationLevel: 2,\n      platform: this.platform,\n      windowsPathsNoEscape: this.windowsPathsNoEscape,\n      debug: !!this.opts.debug,\n    }\n\n    const mms = this.pattern.map(p => new Minimatch(p, mmo))\n    const [matchSet, globParts] = mms.reduce(\n      (set: [MatchSet, GlobParts], m) => {\n        set[0].push(...m.set)\n        set[1].push(...m.globParts)\n        return set\n      },\n      [[], []],\n    )\n    this.patterns = matchSet.map((set, i) => {\n      const g = globParts[i]\n      /* c8 ignore start */\n      if (!g) throw new Error('invalid pattern object')\n      /* c8 ignore stop */\n      return new Pattern(set, g, 0, this.platform)\n    })\n  }\n\n  /**\n   * Returns a Promise that resolves to the results array.\n   */\n  async walk(): Promise>\n  async walk(): Promise<(string | Path)[]> {\n    // Walkers always return array of Path objects, so we just have to\n    // coerce them into the right shape.  It will have already called\n    // realpath() if the option was set to do so, so we know that's cached.\n    // start out knowing the cwd, at least\n    return [\n      ...(await new GlobWalker(this.patterns, this.scurry.cwd, {\n        ...this.opts,\n        maxDepth:\n          this.maxDepth !== Infinity ?\n            this.maxDepth + this.scurry.cwd.depth()\n          : Infinity,\n        platform: this.platform,\n        nocase: this.nocase,\n        includeChildMatches: this.includeChildMatches,\n      }).walk()),\n    ]\n  }\n\n  /**\n   * synchronous {@link Glob.walk}\n   */\n  walkSync(): Results\n  walkSync(): (string | Path)[] {\n    return [\n      ...new GlobWalker(this.patterns, this.scurry.cwd, {\n        ...this.opts,\n        maxDepth:\n          this.maxDepth !== Infinity ?\n            this.maxDepth + this.scurry.cwd.depth()\n          : Infinity,\n        platform: this.platform,\n        nocase: this.nocase,\n        includeChildMatches: this.includeChildMatches,\n      }).walkSync(),\n    ]\n  }\n\n  /**\n   * Stream results asynchronously.\n   */\n  stream(): Minipass, Result>\n  stream(): Minipass {\n    return new GlobStream(this.patterns, this.scurry.cwd, {\n      ...this.opts,\n      maxDepth:\n        this.maxDepth !== Infinity ?\n          this.maxDepth + this.scurry.cwd.depth()\n        : Infinity,\n      platform: this.platform,\n      nocase: this.nocase,\n      includeChildMatches: this.includeChildMatches,\n    }).stream()\n  }\n\n  /**\n   * Stream results synchronously.\n   */\n  streamSync(): Minipass, Result>\n  streamSync(): Minipass {\n    return new GlobStream(this.patterns, this.scurry.cwd, {\n      ...this.opts,\n      maxDepth:\n        this.maxDepth !== Infinity ?\n          this.maxDepth + this.scurry.cwd.depth()\n        : Infinity,\n      platform: this.platform,\n      nocase: this.nocase,\n      includeChildMatches: this.includeChildMatches,\n    }).streamSync()\n  }\n\n  /**\n   * Default sync iteration function. Returns a Generator that\n   * iterates over the results.\n   */\n  iterateSync(): Generator, void, void> {\n    return this.streamSync()[Symbol.iterator]()\n  }\n  [Symbol.iterator]() {\n    return this.iterateSync()\n  }\n\n  /**\n   * Default async iteration function. Returns an AsyncGenerator that\n   * iterates over the results.\n   */\n  iterate(): AsyncGenerator, void, void> {\n    return this.stream()[Symbol.asyncIterator]()\n  }\n  [Symbol.asyncIterator]() {\n    return this.iterate()\n  }\n}\n"]}PK~\8\hXXglob/dist/esm/processor.d.tsnu[import { MMRegExp } from 'minimatch';
import { Path } from 'path-scurry';
import { Pattern } from './pattern.js';
import { GlobWalkerOpts } from './walker.js';
/**
 * A cache of which patterns have been processed for a given Path
 */
export declare class HasWalkedCache {
    store: Map>;
    constructor(store?: Map>);
    copy(): HasWalkedCache;
    hasWalked(target: Path, pattern: Pattern): boolean | undefined;
    storeWalked(target: Path, pattern: Pattern): void;
}
/**
 * A record of which paths have been matched in a given walk step,
 * and whether they only are considered a match if they are a directory,
 * and whether their absolute or relative path should be returned.
 */
export declare class MatchRecord {
    store: Map;
    add(target: Path, absolute: boolean, ifDir: boolean): void;
    entries(): [Path, boolean, boolean][];
}
/**
 * A collection of patterns that must be processed in a subsequent step
 * for a given path.
 */
export declare class SubWalks {
    store: Map;
    add(target: Path, pattern: Pattern): void;
    get(target: Path): Pattern[];
    entries(): [Path, Pattern[]][];
    keys(): Path[];
}
/**
 * The class that processes patterns for a given path.
 *
 * Handles child entry filtering, and determining whether a path's
 * directory contents must be read.
 */
export declare class Processor {
    hasWalkedCache: HasWalkedCache;
    matches: MatchRecord;
    subwalks: SubWalks;
    patterns?: Pattern[];
    follow: boolean;
    dot: boolean;
    opts: GlobWalkerOpts;
    constructor(opts: GlobWalkerOpts, hasWalkedCache?: HasWalkedCache);
    processPatterns(target: Path, patterns: Pattern[]): this;
    subwalkTargets(): Path[];
    child(): Processor;
    filterEntries(parent: Path, entries: Path[]): Processor;
    testGlobstar(e: Path, pattern: Pattern, rest: Pattern | null, absolute: boolean): void;
    testRegExp(e: Path, p: MMRegExp, rest: Pattern | null, absolute: boolean): void;
    testString(e: Path, p: string, rest: Pattern | null, absolute: boolean): void;
}
//# sourceMappingURL=processor.d.ts.mapPK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AAI,CAAC,gBAAgB,EAAE,CAAC;YACtC,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC;gBAAE,OAAO,IAAI,CAAA;QACpC,CAAC;QACD,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACtC,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC;gBAAE,OAAO,IAAI,CAAA;QACpC,CAAC;QACD,OAAO,KAAK,CAAA;IACd,CAAC;CACF","sourcesContent":["// give it a pattern, and it'll be able to tell you if\n// a given path should be ignored.\n// Ignoring a path ignores its children if the pattern ends in /**\n// Ignores are always parsed in dot:true mode\n\nimport { Minimatch, MinimatchOptions } from 'minimatch'\nimport { Path } from 'path-scurry'\nimport { Pattern } from './pattern.js'\nimport { GlobWalkerOpts } from './walker.js'\n\nexport interface IgnoreLike {\n  ignored?: (p: Path) => boolean\n  childrenIgnored?: (p: Path) => boolean\n  add?: (ignore: string) => void\n}\n\nconst defaultPlatform: NodeJS.Platform =\n  (\n    typeof process === 'object' &&\n    process &&\n    typeof process.platform === 'string'\n  ) ?\n    process.platform\n  : 'linux'\n\n/**\n * Class used to process ignored patterns\n */\nexport class Ignore implements IgnoreLike {\n  relative: Minimatch[]\n  relativeChildren: Minimatch[]\n  absolute: Minimatch[]\n  absoluteChildren: Minimatch[]\n  platform: NodeJS.Platform\n  mmopts: MinimatchOptions\n\n  constructor(\n    ignored: string[],\n    {\n      nobrace,\n      nocase,\n      noext,\n      noglobstar,\n      platform = defaultPlatform,\n    }: GlobWalkerOpts,\n  ) {\n    this.relative = []\n    this.absolute = []\n    this.relativeChildren = []\n    this.absoluteChildren = []\n    this.platform = platform\n    this.mmopts = {\n      dot: true,\n      nobrace,\n      nocase,\n      noext,\n      noglobstar,\n      optimizationLevel: 2,\n      platform,\n      nocomment: true,\n      nonegate: true,\n    }\n    for (const ign of ignored) this.add(ign)\n  }\n\n  add(ign: string) {\n    // this is a little weird, but it gives us a clean set of optimized\n    // minimatch matchers, without getting tripped up if one of them\n    // ends in /** inside a brace section, and it's only inefficient at\n    // the start of the walk, not along it.\n    // It'd be nice if the Pattern class just had a .test() method, but\n    // handling globstars is a bit of a pita, and that code already lives\n    // in minimatch anyway.\n    // Another way would be if maybe Minimatch could take its set/globParts\n    // as an option, and then we could at least just use Pattern to test\n    // for absolute-ness.\n    // Yet another way, Minimatch could take an array of glob strings, and\n    // a cwd option, and do the right thing.\n    const mm = new Minimatch(ign, this.mmopts)\n    for (let i = 0; i < mm.set.length; i++) {\n      const parsed = mm.set[i]\n      const globParts = mm.globParts[i]\n      /* c8 ignore start */\n      if (!parsed || !globParts) {\n        throw new Error('invalid pattern object')\n      }\n      // strip off leading ./ portions\n      // https://github.com/isaacs/node-glob/issues/570\n      while (parsed[0] === '.' && globParts[0] === '.') {\n        parsed.shift()\n        globParts.shift()\n      }\n      /* c8 ignore stop */\n      const p = new Pattern(parsed, globParts, 0, this.platform)\n      const m = new Minimatch(p.globString(), this.mmopts)\n      const children = globParts[globParts.length - 1] === '**'\n      const absolute = p.isAbsolute()\n      if (absolute) this.absolute.push(m)\n      else this.relative.push(m)\n      if (children) {\n        if (absolute) this.absoluteChildren.push(m)\n        else this.relativeChildren.push(m)\n      }\n    }\n  }\n\n  ignored(p: Path): boolean {\n    const fullpath = p.fullpath()\n    const fullpaths = `${fullpath}/`\n    const relative = p.relative() || '.'\n    const relatives = `${relative}/`\n    for (const m of this.relative) {\n      if (m.match(relative) || m.match(relatives)) return true\n    }\n    for (const m of this.absolute) {\n      if (m.match(fullpath) || m.match(fullpaths)) return true\n    }\n    return false\n  }\n\n  childrenIgnored(p: Path): boolean {\n    const fullpath = p.fullpath() + '/'\n    const relative = (p.relative() || '.') + '/'\n    for (const m of this.relativeChildren) {\n      if (m.match(relative)) return true\n    }\n    for (const m of this.absoluteChildren) {\n      if (m.match(fullpath)) return true\n    }\n    return false\n  }\n}\n"]}PK~\sglob/README.mdnu[# Glob

Match files using the patterns the shell uses.

The most correct and second fastest glob implementation in
JavaScript. (See **Comparison to Other JavaScript Glob
Implementations** at the bottom of this readme.)

![a fun cartoon logo made of glob characters](https://github.com/isaacs/node-glob/raw/main/logo/glob.png)

## Usage

Install with npm

```
npm i glob
```

**Note** the npm package name is _not_ `node-glob` that's a
different thing that was abandoned years ago. Just `glob`.

```js
// load using import
import { glob, globSync, globStream, globStreamSync, Glob } from 'glob'
// or using commonjs, that's fine, too
const {
  glob,
  globSync,
  globStream,
  globStreamSync,
  Glob,
} = require('glob')

// the main glob() and globSync() resolve/return array of filenames

// all js files, but don't look in node_modules
const jsfiles = await glob('**/*.js', { ignore: 'node_modules/**' })

// pass in a signal to cancel the glob walk
const stopAfter100ms = await glob('**/*.css', {
  signal: AbortSignal.timeout(100),
})

// multiple patterns supported as well
const images = await glob(['css/*.{png,jpeg}', 'public/*.{png,jpeg}'])

// but of course you can do that with the glob pattern also
// the sync function is the same, just returns a string[] instead
// of Promise
const imagesAlt = globSync('{css,public}/*.{png,jpeg}')

// you can also stream them, this is a Minipass stream
const filesStream = globStream(['**/*.dat', 'logs/**/*.log'])

// construct a Glob object if you wanna do it that way, which
// allows for much faster walks if you have to look in the same
// folder multiple times.
const g = new Glob('**/foo', {})
// glob objects are async iterators, can also do globIterate() or
// g.iterate(), same deal
for await (const file of g) {
  console.log('found a foo file:', file)
}
// pass a glob as the glob options to reuse its settings and caches
const g2 = new Glob('**/bar', g)
// sync iteration works as well
for (const file of g2) {
  console.log('found a bar file:', file)
}

// you can also pass withFileTypes: true to get Path objects
// these are like a Dirent, but with some more added powers
// check out http://npm.im/path-scurry for more info on their API
const g3 = new Glob('**/baz/**', { withFileTypes: true })
g3.stream().on('data', path => {
  console.log(
    'got a path object',
    path.fullpath(),
    path.isDirectory(),
    path.readdirSync().map(e => e.name),
  )
})

// if you use stat:true and withFileTypes, you can sort results
// by things like modified time, filter by permission mode, etc.
// All Stats fields will be available in that case. Slightly
// slower, though.
// For example:
const results = await glob('**', { stat: true, withFileTypes: true })

const timeSortedFiles = results
  .sort((a, b) => a.mtimeMs - b.mtimeMs)
  .map(path => path.fullpath())

const groupReadableFiles = results
  .filter(path => path.mode & 0o040)
  .map(path => path.fullpath())

// custom ignores can be done like this, for example by saying
// you'll ignore all markdown files, and all folders named 'docs'
const customIgnoreResults = await glob('**', {
  ignore: {
    ignored: p => /\.md$/.test(p.name),
    childrenIgnored: p => p.isNamed('docs'),
  },
})

// another fun use case, only return files with the same name as
// their parent folder, plus either `.ts` or `.js`
const folderNamedModules = await glob('**/*.{ts,js}', {
  ignore: {
    ignored: p => {
      const pp = p.parent
      return !(p.isNamed(pp.name + '.ts') || p.isNamed(pp.name + '.js'))
    },
  },
})

// find all files edited in the last hour, to do this, we ignore
// all of them that are more than an hour old
const newFiles = await glob('**', {
  // need stat so we have mtime
  stat: true,
  // only want the files, not the dirs
  nodir: true,
  ignore: {
    ignored: p => {
      return new Date() - p.mtime > 60 * 60 * 1000
    },
    // could add similar childrenIgnored here as well, but
    // directory mtime is inconsistent across platforms, so
    // probably better not to, unless you know the system
    // tracks this reliably.
  },
})
```

**Note** Glob patterns should always use `/` as a path separator,
even on Windows systems, as `\` is used to escape glob
characters. If you wish to use `\` as a path separator _instead
of_ using it as an escape character on Windows platforms, you may
set `windowsPathsNoEscape:true` in the options. In this mode,
special glob characters cannot be escaped, making it impossible
to match a literal `*` `?` and so on in filenames.

## Command Line Interface

```
$ glob -h

Usage:
  glob [options] [ [ ...]]

Expand the positional glob expression arguments into any matching file system
paths found.

  -c --cmd=
                         Run the command provided, passing the glob expression
                         matches as arguments.

  -A --all               By default, the glob cli command will not expand any
                         arguments that are an exact match to a file on disk.

                         This prevents double-expanding, in case the shell
                         expands an argument whose filename is a glob
                         expression.

                         For example, if 'app/*.ts' would match 'app/[id].ts',
                         then on Windows powershell or cmd.exe, 'glob app/*.ts'
                         will expand to 'app/[id].ts', as expected. However, in
                         posix shells such as bash or zsh, the shell will first
                         expand 'app/*.ts' to a list of filenames. Then glob
                         will look for a file matching 'app/[id].ts' (ie,
                         'app/i.ts' or 'app/d.ts'), which is unexpected.

                         Setting '--all' prevents this behavior, causing glob to
                         treat ALL patterns as glob expressions to be expanded,
                         even if they are an exact match to a file on disk.

                         When setting this option, be sure to enquote arguments
                         so that the shell will not expand them prior to passing
                         them to the glob command process.

  -a --absolute          Expand to absolute paths
  -d --dot-relative      Prepend './' on relative matches
  -m --mark              Append a / on any directories matched
  -x --posix             Always resolve to posix style paths, using '/' as the
                         directory separator, even on Windows. Drive letter
                         absolute matches on Windows will be expanded to their
                         full resolved UNC maths, eg instead of 'C:\foo\bar', it
                         will expand to '//?/C:/foo/bar'.

  -f --follow            Follow symlinked directories when expanding '**'
  -R --realpath          Call 'fs.realpath' on all of the results. In the case
                         of an entry that cannot be resolved, the entry is
                         omitted. This incurs a slight performance penalty, of
                         course, because of the added system calls.

  -s --stat              Call 'fs.lstat' on all entries, whether required or not
                         to determine if it's a valid match.

  -b --match-base        Perform a basename-only match if the pattern does not
                         contain any slash characters. That is, '*.js' would be
                         treated as equivalent to '**/*.js', matching js files
                         in all directories.

  --dot                  Allow patterns to match files/directories that start
                         with '.', even if the pattern does not start with '.'

  --nobrace              Do not expand {...} patterns
  --nocase               Perform a case-insensitive match. This defaults to
                         'true' on macOS and Windows platforms, and false on all
                         others.

                         Note: 'nocase' should only be explicitly set when it is
                         known that the filesystem's case sensitivity differs
                         from the platform default. If set 'true' on
                         case-insensitive file systems, then the walk may return
                         more or less results than expected.

  --nodir                Do not match directories, only files.

                         Note: to *only* match directories, append a '/' at the
                         end of the pattern.

  --noext                Do not expand extglob patterns, such as '+(a|b)'
  --noglobstar           Do not expand '**' against multiple path portions. Ie,
                         treat it as a normal '*' instead.

  --windows-path-no-escape
                         Use '\' as a path separator *only*, and *never* as an
                         escape character. If set, all '\' characters are
                         replaced with '/' in the pattern.

  -D --max-depth=  Maximum depth to traverse from the current working
                         directory

  -C --cwd=    Current working directory to execute/match in
  -r --root= A string path resolved against the 'cwd', which is used
                         as the starting point for absolute patterns that start
                         with '/' (but not drive letters or UNC paths on
                         Windows).

                         Note that this *doesn't* necessarily limit the walk to
                         the 'root' directory, and doesn't affect the cwd
                         starting point for non-absolute patterns. A pattern
                         containing '..' will still be able to traverse out of
                         the root directory, if it is not an actual root
                         directory on the filesystem, and any non-absolute
                         patterns will still be matched in the 'cwd'.

                         To start absolute and non-absolute patterns in the same
                         path, you can use '--root=' to set it to the empty
                         string. However, be aware that on Windows systems, a
                         pattern like 'x:/*' or '//host/share/*' will *always*
                         start in the 'x:/' or '//host/share/' directory,
                         regardless of the --root setting.

  --platform=  Defaults to the value of 'process.platform' if
                         available, or 'linux' if not. Setting --platform=win32
                         on non-Windows systems may cause strange behavior!

  -i --ignore=
                         Glob patterns to ignore Can be set multiple times
  -v --debug             Output a huge amount of noisy debug information about
                         patterns as they are parsed and used to match files.

  -h --help              Show this usage information
```

## `glob(pattern: string | string[], options?: GlobOptions) => Promise`

Perform an asynchronous glob search for the pattern(s) specified.
Returns
[Path](https://isaacs.github.io/path-scurry/classes/PathBase)
objects if the `withFileTypes` option is set to `true`. See below
for full options field desciptions.

## `globSync(pattern: string | string[], options?: GlobOptions) => string[] | Path[]`

Synchronous form of `glob()`.

Alias: `glob.sync()`

## `globIterate(pattern: string | string[], options?: GlobOptions) => AsyncGenerator`

Return an async iterator for walking glob pattern matches.

Alias: `glob.iterate()`

## `globIterateSync(pattern: string | string[], options?: GlobOptions) => Generator`

Return a sync iterator for walking glob pattern matches.

Alias: `glob.iterate.sync()`, `glob.sync.iterate()`

## `globStream(pattern: string | string[], options?: GlobOptions) => Minipass`

Return a stream that emits all the strings or `Path` objects and
then emits `end` when completed.

Alias: `glob.stream()`

## `globStreamSync(pattern: string | string[], options?: GlobOptions) => Minipass`

Syncronous form of `globStream()`. Will read all the matches as
fast as you consume them, even all in a single tick if you
consume them immediately, but will still respond to backpressure
if they're not consumed immediately.

Alias: `glob.stream.sync()`, `glob.sync.stream()`

## `hasMagic(pattern: string | string[], options?: GlobOptions) => boolean`

Returns `true` if the provided pattern contains any "magic" glob
characters, given the options provided.

Brace expansion is not considered "magic" unless the
`magicalBraces` option is set, as brace expansion just turns one
string into an array of strings. So a pattern like `'x{a,b}y'`
would return `false`, because `'xay'` and `'xby'` both do not
contain any magic glob characters, and it's treated the same as
if you had called it on `['xay', 'xby']`. When
`magicalBraces:true` is in the options, brace expansion _is_
treated as a pattern having magic.

## `escape(pattern: string, options?: GlobOptions) => string`

Escape all magic characters in a glob pattern, so that it will
only ever match literal strings

If the `windowsPathsNoEscape` option is used, then characters are
escaped by wrapping in `[]`, because a magic character wrapped in
a character class can only be satisfied by that exact character.

Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot
be escaped or unescaped.

## `unescape(pattern: string, options?: GlobOptions) => string`

Un-escape a glob string that may contain some escaped characters.

If the `windowsPathsNoEscape` option is used, then square-brace
escapes are removed, but not backslash escapes. For example, it
will turn the string `'[*]'` into `*`, but it will not turn
`'\\*'` into `'*'`, because `\` is a path separator in
`windowsPathsNoEscape` mode.

When `windowsPathsNoEscape` is not set, then both brace escapes
and backslash escapes are removed.

Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot
be escaped or unescaped.

## Class `Glob`

An object that can perform glob pattern traversals.

### `const g = new Glob(pattern: string | string[], options: GlobOptions)`

Options object is required.

See full options descriptions below.

Note that a previous `Glob` object can be passed as the
`GlobOptions` to another `Glob` instantiation to re-use settings
and caches with a new pattern.

Traversal functions can be called multiple times to run the walk
again.

### `g.stream()`

Stream results asynchronously,

### `g.streamSync()`

Stream results synchronously.

### `g.iterate()`

Default async iteration function. Returns an AsyncGenerator that
iterates over the results.

### `g.iterateSync()`

Default sync iteration function. Returns a Generator that
iterates over the results.

### `g.walk()`

Returns a Promise that resolves to the results array.

### `g.walkSync()`

Returns a results array.

### Properties

All options are stored as properties on the `Glob` object.

- `opts` The options provided to the constructor.
- `patterns` An array of parsed immutable `Pattern` objects.

## Options

Exported as `GlobOptions` TypeScript interface. A `GlobOptions`
object may be provided to any of the exported methods, and must
be provided to the `Glob` constructor.

All options are optional, boolean, and false by default, unless
otherwise noted.

All resolved options are added to the Glob object as properties.

If you are running many `glob` operations, you can pass a Glob
object as the `options` argument to a subsequent operation to
share the previously loaded cache.

- `cwd` String path or `file://` string or URL object. The
  current working directory in which to search. Defaults to
  `process.cwd()`. See also: "Windows, CWDs, Drive Letters, and
  UNC Paths", below.

  This option may be either a string path or a `file://` URL
  object or string.

- `root` A string path resolved against the `cwd` option, which
  is used as the starting point for absolute patterns that start
  with `/`, (but not drive letters or UNC paths on Windows).

  Note that this _doesn't_ necessarily limit the walk to the
  `root` directory, and doesn't affect the cwd starting point for
  non-absolute patterns. A pattern containing `..` will still be
  able to traverse out of the root directory, if it is not an
  actual root directory on the filesystem, and any non-absolute
  patterns will be matched in the `cwd`. For example, the
  pattern `/../*` with `{root:'/some/path'}` will return all
  files in `/some`, not all files in `/some/path`. The pattern
  `*` with `{root:'/some/path'}` will return all the entries in
  the cwd, not the entries in `/some/path`.

  To start absolute and non-absolute patterns in the same
  path, you can use `{root:''}`. However, be aware that on
  Windows systems, a pattern like `x:/*` or `//host/share/*` will
  _always_ start in the `x:/` or `//host/share` directory,
  regardless of the `root` setting.

- `windowsPathsNoEscape` Use `\\` as a path separator _only_, and
  _never_ as an escape character. If set, all `\\` characters are
  replaced with `/` in the pattern.

  Note that this makes it **impossible** to match against paths
  containing literal glob pattern characters, but allows matching
  with patterns constructed using `path.join()` and
  `path.resolve()` on Windows platforms, mimicking the (buggy!)
  behavior of Glob v7 and before on Windows. Please use with
  caution, and be mindful of [the caveat below about Windows
  paths](#windows). (For legacy reasons, this is also set if
  `allowWindowsEscape` is set to the exact value `false`.)

- `dot` Include `.dot` files in normal matches and `globstar`
  matches. Note that an explicit dot in a portion of the pattern
  will always match dot files.

- `magicalBraces` Treat brace expansion like `{a,b}` as a "magic"
  pattern. Has no effect if {@link nobrace} is set.

  Only has effect on the {@link hasMagic} function, no effect on
  glob pattern matching itself.

- `dotRelative` Prepend all relative path strings with `./` (or
  `.\` on Windows).

  Without this option, returned relative paths are "bare", so
  instead of returning `'./foo/bar'`, they are returned as
  `'foo/bar'`.

  Relative patterns starting with `'../'` are not prepended with
  `./`, even if this option is set.

- `mark` Add a `/` character to directory matches. Note that this
  requires additional stat calls.

- `nobrace` Do not expand `{a,b}` and `{1..3}` brace sets.

- `noglobstar` Do not match `**` against multiple filenames. (Ie,
  treat it as a normal `*` instead.)

- `noext` Do not match "extglob" patterns such as `+(a|b)`.

- `nocase` Perform a case-insensitive match. This defaults to
  `true` on macOS and Windows systems, and `false` on all others.

  **Note** `nocase` should only be explicitly set when it is
  known that the filesystem's case sensitivity differs from the
  platform default. If set `true` on case-sensitive file
  systems, or `false` on case-insensitive file systems, then the
  walk may return more or less results than expected.

- `maxDepth` Specify a number to limit the depth of the directory
  traversal to this many levels below the `cwd`.

- `matchBase` Perform a basename-only match if the pattern does
  not contain any slash characters. That is, `*.js` would be
  treated as equivalent to `**/*.js`, matching all js files in
  all directories.

- `nodir` Do not match directories, only files. (Note: to match
  _only_ directories, put a `/` at the end of the pattern.)

  Note: when `follow` and `nodir` are both set, then symbolic
  links to directories are also omitted.

- `stat` Call `lstat()` on all entries, whether required or not
  to determine whether it's a valid match. When used with
  `withFileTypes`, this means that matches will include data such
  as modified time, permissions, and so on. Note that this will
  incur a performance cost due to the added system calls.

- `ignore` string or string[], or an object with `ignore` and
  `ignoreChildren` methods.

  If a string or string[] is provided, then this is treated as a
  glob pattern or array of glob patterns to exclude from matches.
  To ignore all children within a directory, as well as the entry
  itself, append `'/**'` to the ignore pattern.

  **Note** `ignore` patterns are _always_ in `dot:true` mode,
  regardless of any other settings.

  If an object is provided that has `ignored(path)` and/or
  `childrenIgnored(path)` methods, then these methods will be
  called to determine whether any Path is a match or if its
  children should be traversed, respectively.

- `follow` Follow symlinked directories when expanding `**`
  patterns. This can result in a lot of duplicate references in
  the presence of cyclic links, and make performance quite bad.

  By default, a `**` in a pattern will follow 1 symbolic link if
  it is not the first item in the pattern, or none if it is the
  first item in the pattern, following the same behavior as Bash.

  Note: when `follow` and `nodir` are both set, then symbolic
  links to directories are also omitted.

- `realpath` Set to true to call `fs.realpath` on all of the
  results. In the case of an entry that cannot be resolved, the
  entry is omitted. This incurs a slight performance penalty, of
  course, because of the added system calls.

- `absolute` Set to true to always receive absolute paths for
  matched files. Set to `false` to always receive relative paths
  for matched files.

  By default, when this option is not set, absolute paths are
  returned for patterns that are absolute, and otherwise paths
  are returned that are relative to the `cwd` setting.

  This does _not_ make an extra system call to get the realpath,
  it only does string path resolution.

  `absolute` may not be used along with `withFileTypes`.

- `posix` Set to true to use `/` as the path separator in
  returned results. On posix systems, this has no effect. On
  Windows systems, this will return `/` delimited path results,
  and absolute paths will be returned in their full resolved UNC
  path form, eg insted of `'C:\\foo\\bar'`, it will return
  `//?/C:/foo/bar`.

- `platform` Defaults to value of `process.platform` if
  available, or `'linux'` if not. Setting `platform:'win32'` on
  non-Windows systems may cause strange behavior.

- `withFileTypes` Return [PathScurry](http://npm.im/path-scurry)
  `Path` objects instead of strings. These are similar to a
  NodeJS `Dirent` object, but with additional methods and
  properties.

  `withFileTypes` may not be used along with `absolute`.

- `signal` An AbortSignal which will cancel the Glob walk when
  triggered.

- `fs` An override object to pass in custom filesystem methods.
  See [PathScurry docs](http://npm.im/path-scurry) for what can
  be overridden.

- `scurry` A [PathScurry](http://npm.im/path-scurry) object used
  to traverse the file system. If the `nocase` option is set
  explicitly, then any provided `scurry` object must match this
  setting.

- `includeChildMatches` boolean, default `true`. Do not match any
  children of any matches. For example, the pattern `**\/foo`
  would match `a/foo`, but not `a/foo/b/foo` in this mode.

  This is especially useful for cases like "find all
  `node_modules` folders, but not the ones in `node_modules`".

  In order to support this, the `Ignore` implementation must
  support an `add(pattern: string)` method. If using the default
  `Ignore` class, then this is fine, but if this is set to
  `false`, and a custom `Ignore` is provided that does not have
  an `add()` method, then it will throw an error.

  **Caveat** It _only_ ignores matches that would be a descendant
  of a previous match, and only if that descendant is matched
  _after_ the ancestor is encountered. Since the file system walk
  happens in indeterminate order, it's possible that a match will
  already be added before its ancestor, if multiple or braced
  patterns are used.

  For example:

  ```js
  const results = await glob(
    [
      // likely to match first, since it's just a stat
      'a/b/c/d/e/f',

      // this pattern is more complicated! It must to various readdir()
      // calls and test the results against a regular expression, and that
      // is certainly going to take a little bit longer.
      //
      // So, later on, it encounters a match at 'a/b/c/d/e', but it's too
      // late to ignore a/b/c/d/e/f, because it's already been emitted.
      'a/[bdf]/?/[a-z]/*',
    ],
    { includeChildMatches: false },
  )
  ```

  It's best to only set this to `false` if you can be reasonably
  sure that no components of the pattern will potentially match
  one another's file system descendants, or if the occasional
  included child entry will not cause problems.

## Glob Primer

Much more information about glob pattern expansion can be found
by running `man bash` and searching for `Pattern Matching`.

"Globs" are the patterns you type when you do stuff like `ls
*.js` on the command line, or put `build/*` in a `.gitignore`
file.

Before parsing the path part patterns, braced sections are
expanded into a set. Braced sections start with `{` and end with
`}`, with 2 or more comma-delimited sections within. Braced
sections may contain slash characters, so `a{/b/c,bcd}` would
expand into `a/b/c` and `abcd`.

The following characters have special magic meaning when used in
a path portion. With the exception of `**`, none of these match
path separators (ie, `/` on all platforms, and `\` on Windows).

- `*` Matches 0 or more characters in a single path portion.
  When alone in a path portion, it must match at least 1
  character. If `dot:true` is not specified, then `*` will not
  match against a `.` character at the start of a path portion.
- `?` Matches 1 character. If `dot:true` is not specified, then
  `?` will not match against a `.` character at the start of a
  path portion.
- `[...]` Matches a range of characters, similar to a RegExp
  range. If the first character of the range is `!` or `^` then
  it matches any character not in the range. If the first
  character is `]`, then it will be considered the same as `\]`,
  rather than the end of the character class.
- `!(pattern|pattern|pattern)` Matches anything that does not
  match any of the patterns provided. May _not_ contain `/`
  characters. Similar to `*`, if alone in a path portion, then
  the path portion must have at least one character.
- `?(pattern|pattern|pattern)` Matches zero or one occurrence of
  the patterns provided. May _not_ contain `/` characters.
- `+(pattern|pattern|pattern)` Matches one or more occurrences of
  the patterns provided. May _not_ contain `/` characters.
- `*(a|b|c)` Matches zero or more occurrences of the patterns
  provided. May _not_ contain `/` characters.
- `@(pattern|pat*|pat?erN)` Matches exactly one of the patterns
  provided. May _not_ contain `/` characters.
- `**` If a "globstar" is alone in a path portion, then it
  matches zero or more directories and subdirectories searching
  for matches. It does not crawl symlinked directories, unless
  `{follow:true}` is passed in the options object. A pattern
  like `a/b/**` will only match `a/b` if it is a directory.
  Follows 1 symbolic link if not the first item in the pattern,
  or 0 if it is the first item, unless `follow:true` is set, in
  which case it follows all symbolic links.

`[:class:]` patterns are supported by this implementation, but
`[=c=]` and `[.symbol.]` style class patterns are not.

### Dots

If a file or directory path portion has a `.` as the first
character, then it will not match any glob pattern unless that
pattern's corresponding path part also has a `.` as its first
character.

For example, the pattern `a/.*/c` would match the file at
`a/.b/c`. However the pattern `a/*/c` would not, because `*` does
not start with a dot character.

You can make glob treat dots as normal characters by setting
`dot:true` in the options.

### Basename Matching

If you set `matchBase:true` in the options, and the pattern has
no slashes in it, then it will seek for any file anywhere in the
tree with a matching basename. For example, `*.js` would match
`test/simple/basic.js`.

### Empty Sets

If no matching files are found, then an empty array is returned.
This differs from the shell, where the pattern itself is
returned. For example:

```sh
$ echo a*s*d*f
a*s*d*f
```

## Comparisons to other fnmatch/glob implementations

While strict compliance with the existing standards is a
worthwhile goal, some discrepancies exist between node-glob and
other implementations, and are intentional.

The double-star character `**` is supported by default, unless
the `noglobstar` flag is set. This is supported in the manner of
bsdglob and bash 5, where `**` only has special significance if
it is the only thing in a path part. That is, `a/**/b` will match
`a/x/y/b`, but `a/**b` will not.

Note that symlinked directories are not traversed as part of a
`**`, though their contents may match against subsequent portions
of the pattern. This prevents infinite loops and duplicates and
the like. You can force glob to traverse symlinks with `**` by
setting `{follow:true}` in the options.

There is no equivalent of the `nonull` option. A pattern that
does not find any matches simply resolves to nothing. (An empty
array, immediately ended stream, etc.)

If brace expansion is not disabled, then it is performed before
any other interpretation of the glob pattern. Thus, a pattern
like `+(a|{b),c)}`, which would not be valid in bash or zsh, is
expanded **first** into the set of `+(a|b)` and `+(a|c)`, and
those patterns are checked for validity. Since those two are
valid, matching proceeds.

The character class patterns `[:class:]` (posix standard named
classes) style class patterns are supported and unicode-aware,
but `[=c=]` (locale-specific character collation weight), and
`[.symbol.]` (collating symbol), are not.

### Repeated Slashes

Unlike Bash and zsh, repeated `/` are always coalesced into a
single path separator.

### Comments and Negation

Previously, this module let you mark a pattern as a "comment" if
it started with a `#` character, or a "negated" pattern if it
started with a `!` character.

These options were deprecated in version 5, and removed in
version 6.

To specify things that should not match, use the `ignore` option.

## Windows

**Please only use forward-slashes in glob expressions.**

Though windows uses either `/` or `\` as its path separator, only
`/` characters are used by this glob implementation. You must use
forward-slashes **only** in glob expressions. Back-slashes will
always be interpreted as escape characters, not path separators.

Results from absolute patterns such as `/foo/*` are mounted onto
the root setting using `path.join`. On windows, this will by
default result in `/foo/*` matching `C:\foo\bar.txt`.

To automatically coerce all `\` characters to `/` in pattern
strings, **thus making it impossible to escape literal glob
characters**, you may set the `windowsPathsNoEscape` option to
`true`.

### Windows, CWDs, Drive Letters, and UNC Paths

On posix systems, when a pattern starts with `/`, any `cwd`
option is ignored, and the traversal starts at `/`, plus any
non-magic path portions specified in the pattern.

On Windows systems, the behavior is similar, but the concept of
an "absolute path" is somewhat more involved.

#### UNC Paths

A UNC path may be used as the start of a pattern on Windows
platforms. For example, a pattern like: `//?/x:/*` will return
all file entries in the root of the `x:` drive. A pattern like
`//ComputerName/Share/*` will return all files in the associated
share.

UNC path roots are always compared case insensitively.

#### Drive Letters

A pattern starting with a drive letter, like `c:/*`, will search
in that drive, regardless of any `cwd` option provided.

If the pattern starts with `/`, and is not a UNC path, and there
is an explicit `cwd` option set with a drive letter, then the
drive letter in the `cwd` is used as the root of the directory
traversal.

For example, `glob('/tmp', { cwd: 'c:/any/thing' })` will return
`['c:/tmp']` as the result.

If an explicit `cwd` option is not provided, and the pattern
starts with `/`, then the traversal will run on the root of the
drive provided as the `cwd` option. (That is, it is the result of
`path.resolve('/')`.)

## Race Conditions

Glob searching, by its very nature, is susceptible to race
conditions, since it relies on directory walking.

As a result, it is possible that a file that exists when glob
looks for it may have been deleted or modified by the time it
returns the result.

By design, this implementation caches all readdir calls that it
makes, in order to cut down on system overhead. However, this
also makes it even more susceptible to races, especially if the
cache object is reused between glob calls.

Users are thus advised not to use a glob result as a guarantee of
filesystem state in the face of rapid changes. For the vast
majority of operations, this is never a problem.

### See Also:

- `man sh`
- `man bash` [Pattern
  Matching](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html)
- `man 3 fnmatch`
- `man 5 gitignore`
- [minimatch documentation](https://github.com/isaacs/minimatch)

## Glob Logo

Glob's logo was created by [Tanya
Brassie](http://tanyabrassie.com/). Logo files can be found
[here](https://github.com/isaacs/node-glob/tree/master/logo).

The logo is licensed under a [Creative Commons
Attribution-ShareAlike 4.0 International
License](https://creativecommons.org/licenses/by-sa/4.0/).

## Contributing

Any change to behavior (including bugfixes) must come with a
test.

Patches that fail tests or reduce performance will be rejected.

```sh
# to run tests
npm test

# to re-generate test fixtures
npm run test-regen

# run the benchmarks
npm run bench

# to profile javascript
npm run prof
```

## Comparison to Other JavaScript Glob Implementations

**tl;dr**

- If you want glob matching that is as faithful as possible to
  Bash pattern expansion semantics, and as fast as possible
  within that constraint, _use this module_.
- If you are reasonably sure that the patterns you will encounter
  are relatively simple, and want the absolutely fastest glob
  matcher out there, _use [fast-glob](http://npm.im/fast-glob)_.
- If you are reasonably sure that the patterns you will encounter
  are relatively simple, and want the convenience of
  automatically respecting `.gitignore` files, _use
  [globby](http://npm.im/globby)_.

There are some other glob matcher libraries on npm, but these
three are (in my opinion, as of 2023) the best.

---

**full explanation**

Every library reflects a set of opinions and priorities in the
trade-offs it makes. Other than this library, I can personally
recommend both [globby](http://npm.im/globby) and
[fast-glob](http://npm.im/fast-glob), though they differ in their
benefits and drawbacks.

Both have very nice APIs and are reasonably fast.

`fast-glob` is, as far as I am aware, the fastest glob
implementation in JavaScript today. However, there are many
cases where the choices that `fast-glob` makes in pursuit of
speed mean that its results differ from the results returned by
Bash and other sh-like shells, which may be surprising.

In my testing, `fast-glob` is around 10-20% faster than this
module when walking over 200k files nested 4 directories
deep[1](#fn-webscale). However, there are some inconsistencies
with Bash matching behavior that this module does not suffer
from:

- `**` only matches files, not directories
- `..` path portions are not handled unless they appear at the
  start of the pattern
- `./!()` will not match any files that _start_ with
  ``, even if they do not match ``. For
  example, `!(9).txt` will not match `9999.txt`.
- Some brace patterns in the middle of a pattern will result in
  failing to find certain matches.
- Extglob patterns are allowed to contain `/` characters.

Globby exhibits all of the same pattern semantics as fast-glob,
(as it is a wrapper around fast-glob) and is slightly slower than
node-glob (by about 10-20% in the benchmark test set, or in other
words, anywhere from 20-50% slower than fast-glob). However, it
adds some API conveniences that may be worth the costs.

- Support for `.gitignore` and other ignore files.
- Support for negated globs (ie, patterns starting with `!`
  rather than using a separate `ignore` option).

The priority of this module is "correctness" in the sense of
performing a glob pattern expansion as faithfully as possible to
the behavior of Bash and other sh-like shells, with as much speed
as possible.

Note that prior versions of `node-glob` are _not_ on this list.
Former versions of this module are far too slow for any cases
where performance matters at all, and were designed with APIs
that are extremely dated by current JavaScript standards.

---

[1]: In the cases where this module
returns results and `fast-glob` doesn't, it's even faster, of
course.

![lumpy space princess saying 'oh my GLOB'](https://github.com/isaacs/node-glob/raw/main/oh-my-glob.gif)

### Benchmark Results

First number is time, smaller is better.

Second number is the count of results returned.

```
--- pattern: '**' ---
~~ sync ~~
node fast-glob sync             0m0.598s  200364
node globby sync                0m0.765s  200364
node current globSync mjs       0m0.683s  222656
node current glob syncStream    0m0.649s  222656
~~ async ~~
node fast-glob async            0m0.350s  200364
node globby async               0m0.509s  200364
node current glob async mjs     0m0.463s  222656
node current glob stream        0m0.411s  222656

--- pattern: '**/..' ---
~~ sync ~~
node fast-glob sync             0m0.486s  0
node globby sync                0m0.769s  200364
node current globSync mjs       0m0.564s  2242
node current glob syncStream    0m0.583s  2242
~~ async ~~
node fast-glob async            0m0.283s  0
node globby async               0m0.512s  200364
node current glob async mjs     0m0.299s  2242
node current glob stream        0m0.312s  2242

--- pattern: './**/0/**/0/**/0/**/0/**/*.txt' ---
~~ sync ~~
node fast-glob sync             0m0.490s  10
node globby sync                0m0.517s  10
node current globSync mjs       0m0.540s  10
node current glob syncStream    0m0.550s  10
~~ async ~~
node fast-glob async            0m0.290s  10
node globby async               0m0.296s  10
node current glob async mjs     0m0.278s  10
node current glob stream        0m0.302s  10

--- pattern: './**/[01]/**/[12]/**/[23]/**/[45]/**/*.txt' ---
~~ sync ~~
node fast-glob sync             0m0.500s  160
node globby sync                0m0.528s  160
node current globSync mjs       0m0.556s  160
node current glob syncStream    0m0.573s  160
~~ async ~~
node fast-glob async            0m0.283s  160
node globby async               0m0.301s  160
node current glob async mjs     0m0.306s  160
node current glob stream        0m0.322s  160

--- pattern: './**/0/**/0/**/*.txt' ---
~~ sync ~~
node fast-glob sync             0m0.502s  5230
node globby sync                0m0.527s  5230
node current globSync mjs       0m0.544s  5230
node current glob syncStream    0m0.557s  5230
~~ async ~~
node fast-glob async            0m0.285s  5230
node globby async               0m0.305s  5230
node current glob async mjs     0m0.304s  5230
node current glob stream        0m0.310s  5230

--- pattern: '**/*.txt' ---
~~ sync ~~
node fast-glob sync             0m0.580s  200023
node globby sync                0m0.771s  200023
node current globSync mjs       0m0.685s  200023
node current glob syncStream    0m0.649s  200023
~~ async ~~
node fast-glob async            0m0.349s  200023
node globby async               0m0.509s  200023
node current glob async mjs     0m0.427s  200023
node current glob stream        0m0.388s  200023

--- pattern: '{**/*.txt,**/?/**/*.txt,**/?/**/?/**/*.txt,**/?/**/?/**/?/**/*.txt,**/?/**/?/**/?/**/?/**/*.txt}' ---
~~ sync ~~
node fast-glob sync             0m0.589s  200023
node globby sync                0m0.771s  200023
node current globSync mjs       0m0.716s  200023
node current glob syncStream    0m0.684s  200023
~~ async ~~
node fast-glob async            0m0.351s  200023
node globby async               0m0.518s  200023
node current glob async mjs     0m0.462s  200023
node current glob stream        0m0.468s  200023

--- pattern: '**/5555/0000/*.txt' ---
~~ sync ~~
node fast-glob sync             0m0.496s  1000
node globby sync                0m0.519s  1000
node current globSync mjs       0m0.539s  1000
node current glob syncStream    0m0.567s  1000
~~ async ~~
node fast-glob async            0m0.285s  1000
node globby async               0m0.299s  1000
node current glob async mjs     0m0.305s  1000
node current glob stream        0m0.301s  1000

--- pattern: './**/0/**/../[01]/**/0/../**/0/*.txt' ---
~~ sync ~~
node fast-glob sync             0m0.484s  0
node globby sync                0m0.507s  0
node current globSync mjs       0m0.577s  4880
node current glob syncStream    0m0.586s  4880
~~ async ~~
node fast-glob async            0m0.280s  0
node globby async               0m0.298s  0
node current glob async mjs     0m0.327s  4880
node current glob stream        0m0.324s  4880

--- pattern: '**/????/????/????/????/*.txt' ---
~~ sync ~~
node fast-glob sync             0m0.547s  100000
node globby sync                0m0.673s  100000
node current globSync mjs       0m0.626s  100000
node current glob syncStream    0m0.618s  100000
~~ async ~~
node fast-glob async            0m0.315s  100000
node globby async               0m0.414s  100000
node current glob async mjs     0m0.366s  100000
node current glob stream        0m0.345s  100000

--- pattern: './{**/?{/**/?{/**/?{/**/?,,,,},,,,},,,,},,,}/**/*.txt' ---
~~ sync ~~
node fast-glob sync             0m0.588s  100000
node globby sync                0m0.670s  100000
node current globSync mjs       0m0.717s  200023
node current glob syncStream    0m0.687s  200023
~~ async ~~
node fast-glob async            0m0.343s  100000
node globby async               0m0.418s  100000
node current glob async mjs     0m0.519s  200023
node current glob stream        0m0.451s  200023

--- pattern: '**/!(0|9).txt' ---
~~ sync ~~
node fast-glob sync             0m0.573s  160023
node globby sync                0m0.731s  160023
node current globSync mjs       0m0.680s  180023
node current glob syncStream    0m0.659s  180023
~~ async ~~
node fast-glob async            0m0.345s  160023
node globby async               0m0.476s  160023
node current glob async mjs     0m0.427s  180023
node current glob stream        0m0.388s  180023

--- pattern: './{*/**/../{*/**/../{*/**/../{*/**/../{*/**,,,,},,,,},,,,},,,,},,,,}/*.txt' ---
~~ sync ~~
node fast-glob sync             0m0.483s  0
node globby sync                0m0.512s  0
node current globSync mjs       0m0.811s  200023
node current glob syncStream    0m0.773s  200023
~~ async ~~
node fast-glob async            0m0.280s  0
node globby async               0m0.299s  0
node current glob async mjs     0m0.617s  200023
node current glob stream        0m0.568s  200023

--- pattern: './*/**/../*/**/../*/**/../*/**/../*/**/../*/**/../*/**/../*/**/*.txt' ---
~~ sync ~~
node fast-glob sync             0m0.485s  0
node globby sync                0m0.507s  0
node current globSync mjs       0m0.759s  200023
node current glob syncStream    0m0.740s  200023
~~ async ~~
node fast-glob async            0m0.281s  0
node globby async               0m0.297s  0
node current glob async mjs     0m0.544s  200023
node current glob stream        0m0.464s  200023

--- pattern: './*/**/../*/**/../*/**/../*/**/../*/**/*.txt' ---
~~ sync ~~
node fast-glob sync             0m0.486s  0
node globby sync                0m0.513s  0
node current globSync mjs       0m0.734s  200023
node current glob syncStream    0m0.696s  200023
~~ async ~~
node fast-glob async            0m0.286s  0
node globby async               0m0.296s  0
node current glob async mjs     0m0.506s  200023
node current glob stream        0m0.483s  200023

--- pattern: './0/**/../1/**/../2/**/../3/**/../4/**/../5/**/../6/**/../7/**/*.txt' ---
~~ sync ~~
node fast-glob sync             0m0.060s  0
node globby sync                0m0.074s  0
node current globSync mjs       0m0.067s  0
node current glob syncStream    0m0.066s  0
~~ async ~~
node fast-glob async            0m0.060s  0
node globby async               0m0.075s  0
node current glob async mjs     0m0.066s  0
node current glob stream        0m0.067s  0

--- pattern: './**/?/**/?/**/?/**/?/**/*.txt' ---
~~ sync ~~
node fast-glob sync             0m0.568s  100000
node globby sync                0m0.651s  100000
node current globSync mjs       0m0.619s  100000
node current glob syncStream    0m0.617s  100000
~~ async ~~
node fast-glob async            0m0.332s  100000
node globby async               0m0.409s  100000
node current glob async mjs     0m0.372s  100000
node current glob stream        0m0.351s  100000

--- pattern: '**/*/**/*/**/*/**/*/**' ---
~~ sync ~~
node fast-glob sync             0m0.603s  200113
node globby sync                0m0.798s  200113
node current globSync mjs       0m0.730s  222137
node current glob syncStream    0m0.693s  222137
~~ async ~~
node fast-glob async            0m0.356s  200113
node globby async               0m0.525s  200113
node current glob async mjs     0m0.508s  222137
node current glob stream        0m0.455s  222137

--- pattern: './**/*/**/*/**/*/**/*/**/*.txt' ---
~~ sync ~~
node fast-glob sync             0m0.622s  200000
node globby sync                0m0.792s  200000
node current globSync mjs       0m0.722s  200000
node current glob syncStream    0m0.695s  200000
~~ async ~~
node fast-glob async            0m0.369s  200000
node globby async               0m0.527s  200000
node current glob async mjs     0m0.502s  200000
node current glob stream        0m0.481s  200000

--- pattern: '**/*.txt' ---
~~ sync ~~
node fast-glob sync             0m0.588s  200023
node globby sync                0m0.771s  200023
node current globSync mjs       0m0.684s  200023
node current glob syncStream    0m0.658s  200023
~~ async ~~
node fast-glob async            0m0.352s  200023
node globby async               0m0.516s  200023
node current glob async mjs     0m0.432s  200023
node current glob stream        0m0.384s  200023

--- pattern: './**/**/**/**/**/**/**/**/*.txt' ---
~~ sync ~~
node fast-glob sync             0m0.589s  200023
node globby sync                0m0.766s  200023
node current globSync mjs       0m0.682s  200023
node current glob syncStream    0m0.652s  200023
~~ async ~~
node fast-glob async            0m0.352s  200023
node globby async               0m0.523s  200023
node current glob async mjs     0m0.436s  200023
node current glob stream        0m0.380s  200023

--- pattern: '**/*/*.txt' ---
~~ sync ~~
node fast-glob sync             0m0.592s  200023
node globby sync                0m0.776s  200023
node current globSync mjs       0m0.691s  200023
node current glob syncStream    0m0.659s  200023
~~ async ~~
node fast-glob async            0m0.357s  200023
node globby async               0m0.513s  200023
node current glob async mjs     0m0.471s  200023
node current glob stream        0m0.424s  200023

--- pattern: '**/*/**/*.txt' ---
~~ sync ~~
node fast-glob sync             0m0.585s  200023
node globby sync                0m0.766s  200023
node current globSync mjs       0m0.694s  200023
node current glob syncStream    0m0.664s  200023
~~ async ~~
node fast-glob async            0m0.350s  200023
node globby async               0m0.514s  200023
node current glob async mjs     0m0.472s  200023
node current glob stream        0m0.424s  200023

--- pattern: '**/[0-9]/**/*.txt' ---
~~ sync ~~
node fast-glob sync             0m0.544s  100000
node globby sync                0m0.636s  100000
node current globSync mjs       0m0.626s  100000
node current glob syncStream    0m0.621s  100000
~~ async ~~
node fast-glob async            0m0.322s  100000
node globby async               0m0.404s  100000
node current glob async mjs     0m0.360s  100000
node current glob stream        0m0.352s  100000
```
PK~\vz-!sprintf-js/src/angular-sprintf.jsnu[/* global angular, sprintf, vsprintf */

!function() {
    'use strict'

    angular.
        module('sprintf', []).
        filter('sprintf', function() {
            return function() {
                return sprintf.apply(null, arguments)
            }
        }).
        filter('fmt', ['$filter', function($filter) {
            return $filter('sprintf')
        }]).
        filter('vsprintf', function() {
            return function(format, argv) {
                return vsprintf(format, argv)
            }
        }).
        filter('vfmt', ['$filter', function($filter) {
            return $filter('vsprintf')
        }])
}(); // eslint-disable-line
PK~\	c>T"$"$sprintf-js/src/sprintf.jsnu[/* global window, exports, define */

!function() {
    'use strict'

    var re = {
        not_string: /[^s]/,
        not_bool: /[^t]/,
        not_type: /[^T]/,
        not_primitive: /[^v]/,
        number: /[diefg]/,
        numeric_arg: /[bcdiefguxX]/,
        json: /[j]/,
        not_json: /[^j]/,
        text: /^[^\x25]+/,
        modulo: /^\x25{2}/,
        placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,
        key: /^([a-z_][a-z_\d]*)/i,
        key_access: /^\.([a-z_][a-z_\d]*)/i,
        index_access: /^\[(\d+)\]/,
        sign: /^[+-]/
    }

    function sprintf(key) {
        // `arguments` is not an array, but should be fine for this call
        return sprintf_format(sprintf_parse(key), arguments)
    }

    function vsprintf(fmt, argv) {
        return sprintf.apply(null, [fmt].concat(argv || []))
    }

    function sprintf_format(parse_tree, argv) {
        var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, ph, pad, pad_character, pad_length, is_positive, sign
        for (i = 0; i < tree_length; i++) {
            if (typeof parse_tree[i] === 'string') {
                output += parse_tree[i]
            }
            else if (typeof parse_tree[i] === 'object') {
                ph = parse_tree[i] // convenience purposes only
                if (ph.keys) { // keyword argument
                    arg = argv[cursor]
                    for (k = 0; k < ph.keys.length; k++) {
                        if (arg == undefined) {
                            throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k-1]))
                        }
                        arg = arg[ph.keys[k]]
                    }
                }
                else if (ph.param_no) { // positional argument (explicit)
                    arg = argv[ph.param_no]
                }
                else { // positional argument (implicit)
                    arg = argv[cursor++]
                }

                if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {
                    arg = arg()
                }

                if (re.numeric_arg.test(ph.type) && (typeof arg !== 'number' && isNaN(arg))) {
                    throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg))
                }

                if (re.number.test(ph.type)) {
                    is_positive = arg >= 0
                }

                switch (ph.type) {
                    case 'b':
                        arg = parseInt(arg, 10).toString(2)
                        break
                    case 'c':
                        arg = String.fromCharCode(parseInt(arg, 10))
                        break
                    case 'd':
                    case 'i':
                        arg = parseInt(arg, 10)
                        break
                    case 'j':
                        arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0)
                        break
                    case 'e':
                        arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential()
                        break
                    case 'f':
                        arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg)
                        break
                    case 'g':
                        arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg)
                        break
                    case 'o':
                        arg = (parseInt(arg, 10) >>> 0).toString(8)
                        break
                    case 's':
                        arg = String(arg)
                        arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
                        break
                    case 't':
                        arg = String(!!arg)
                        arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
                        break
                    case 'T':
                        arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase()
                        arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
                        break
                    case 'u':
                        arg = parseInt(arg, 10) >>> 0
                        break
                    case 'v':
                        arg = arg.valueOf()
                        arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
                        break
                    case 'x':
                        arg = (parseInt(arg, 10) >>> 0).toString(16)
                        break
                    case 'X':
                        arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase()
                        break
                }
                if (re.json.test(ph.type)) {
                    output += arg
                }
                else {
                    if (re.number.test(ph.type) && (!is_positive || ph.sign)) {
                        sign = is_positive ? '+' : '-'
                        arg = arg.toString().replace(re.sign, '')
                    }
                    else {
                        sign = ''
                    }
                    pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' '
                    pad_length = ph.width - (sign + arg).length
                    pad = ph.width ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : ''
                    output += ph.align ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg)
                }
            }
        }
        return output
    }

    var sprintf_cache = Object.create(null)

    function sprintf_parse(fmt) {
        if (sprintf_cache[fmt]) {
            return sprintf_cache[fmt]
        }

        var _fmt = fmt, match, parse_tree = [], arg_names = 0
        while (_fmt) {
            if ((match = re.text.exec(_fmt)) !== null) {
                parse_tree.push(match[0])
            }
            else if ((match = re.modulo.exec(_fmt)) !== null) {
                parse_tree.push('%')
            }
            else if ((match = re.placeholder.exec(_fmt)) !== null) {
                if (match[2]) {
                    arg_names |= 1
                    var field_list = [], replacement_field = match[2], field_match = []
                    if ((field_match = re.key.exec(replacement_field)) !== null) {
                        field_list.push(field_match[1])
                        while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
                            if ((field_match = re.key_access.exec(replacement_field)) !== null) {
                                field_list.push(field_match[1])
                            }
                            else if ((field_match = re.index_access.exec(replacement_field)) !== null) {
                                field_list.push(field_match[1])
                            }
                            else {
                                throw new SyntaxError('[sprintf] failed to parse named argument key')
                            }
                        }
                    }
                    else {
                        throw new SyntaxError('[sprintf] failed to parse named argument key')
                    }
                    match[2] = field_list
                }
                else {
                    arg_names |= 2
                }
                if (arg_names === 3) {
                    throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported')
                }

                parse_tree.push(
                    {
                        placeholder: match[0],
                        param_no:    match[1],
                        keys:        match[2],
                        sign:        match[3],
                        pad_char:    match[4],
                        align:       match[5],
                        width:       match[6],
                        precision:   match[7],
                        type:        match[8]
                    }
                )
            }
            else {
                throw new SyntaxError('[sprintf] unexpected placeholder')
            }
            _fmt = _fmt.substring(match[0].length)
        }
        return sprintf_cache[fmt] = parse_tree
    }

    /**
     * export to either browser or node.js
     */
    /* eslint-disable quote-props */
    if (typeof exports !== 'undefined') {
        exports['sprintf'] = sprintf
        exports['vsprintf'] = vsprintf
    }
    if (typeof window !== 'undefined') {
        window['sprintf'] = sprintf
        window['vsprintf'] = vsprintf

        if (typeof define === 'function' && define['amd']) {
            define(function() {
                return {
                    'sprintf': sprintf,
                    'vsprintf': vsprintf
                }
            })
        }
    }
    /* eslint-enable quote-props */
}(); // eslint-disable-line
PK~\+Ksprintf-js/demo/angular.htmlnu[


    
    
    


    
{{ "%+010d"|sprintf:-123 }}
{{ "%+010d"|vsprintf:[-123] }}
{{ "%+010d"|fmt:-123 }}
{{ "%+010d"|vfmt:[-123] }}
{{ "I've got %2$d apples and %1$d oranges."|fmt:4:2 }}
{{ "I've got %(apples)d apples and %(oranges)d oranges."|fmt:{apples: 2, oranges: 4} }}
PK ~\ +Osprintf-js/package.jsonnu[{ "_id": "sprintf-js@1.1.3", "_inBundle": true, "_location": "/npm/sprintf-js", "_phantomChildren": {}, "_requiredBy": [ "/npm/ip-address" ], "author": { "name": "Alexandru Mărășteanu", "email": "hello@alexei.ro" }, "bugs": { "url": "https://github.com/alexei/sprintf.js/issues" }, "description": "JavaScript sprintf implementation", "devDependencies": { "benchmark": "^2.1.4", "eslint": "^5.10.0", "gulp": "^3.9.1", "gulp-benchmark": "^1.1.1", "gulp-eslint": "^5.0.0", "gulp-header": "^2.0.5", "gulp-mocha": "^6.0.0", "gulp-rename": "^1.4.0", "gulp-sourcemaps": "^2.6.4", "gulp-uglify": "^3.0.1", "mocha": "^5.2.0" }, "homepage": "https://github.com/alexei/sprintf.js#readme", "license": "BSD-3-Clause", "main": "src/sprintf.js", "name": "sprintf-js", "overrides": { "graceful-fs": "^4.2.11" }, "repository": { "type": "git", "url": "git+https://github.com/alexei/sprintf.js.git" }, "scripts": { "lint": "eslint .", "lint:fix": "eslint --fix .", "pretest": "npm run lint", "test": "mocha test/*.js" }, "version": "1.1.3" } PK ~\q9sprintf-js/gruntfile.jsnu[module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON("package.json"), uglify: { options: { banner: "/*! <%= pkg.name %> | <%= pkg.author %> | <%= pkg.license %> */\n", sourceMap: true }, build: { files: [ { src: "src/sprintf.js", dest: "dist/sprintf.min.js" }, { src: "src/angular-sprintf.js", dest: "dist/angular-sprintf.min.js" } ] } }, watch: { js: { files: "src/*.js", tasks: ["uglify"] } } }) grunt.loadNpmTasks("grunt-contrib-uglify") grunt.loadNpmTasks("grunt-contrib-watch") grunt.registerTask("default", ["uglify", "watch"]) } PK ~\ zsprintf-js/test/test.jsnu[var assert = require("assert"), sprintfjs = require("../src/sprintf.js"), sprintf = sprintfjs.sprintf, vsprintf = sprintfjs.vsprintf describe("sprintfjs", function() { var pi = 3.141592653589793 it("should return formated strings for simple placeholders", function() { assert.equal("%", sprintf("%%")) assert.equal("10", sprintf("%b", 2)) assert.equal("A", sprintf("%c", 65)) assert.equal("2", sprintf("%d", 2)) assert.equal("2", sprintf("%i", 2)) assert.equal("2", sprintf("%d", "2")) assert.equal("2", sprintf("%i", "2")) assert.equal('{"foo":"bar"}', sprintf("%j", {foo: "bar"})) assert.equal('["foo","bar"]', sprintf("%j", ["foo", "bar"])) assert.equal("2e+0", sprintf("%e", 2)) assert.equal("2", sprintf("%u", 2)) assert.equal("4294967294", sprintf("%u", -2)) assert.equal("2.2", sprintf("%f", 2.2)) assert.equal("3.141592653589793", sprintf("%g", pi)) assert.equal("10", sprintf("%o", 8)) assert.equal("%s", sprintf("%s", "%s")) assert.equal("ff", sprintf("%x", 255)) assert.equal("FF", sprintf("%X", 255)) assert.equal("Polly wants a cracker", sprintf("%2$s %3$s a %1$s", "cracker", "Polly", "wants")) assert.equal("Hello world!", sprintf("Hello %(who)s!", {"who": "world"})) }) it("should return formated strings for complex placeholders", function() { // sign assert.equal("2", sprintf("%d", 2)) assert.equal("-2", sprintf("%d", -2)) assert.equal("+2", sprintf("%+d", 2)) assert.equal("-2", sprintf("%+d", -2)) assert.equal("2", sprintf("%i", 2)) assert.equal("-2", sprintf("%i", -2)) assert.equal("+2", sprintf("%+i", 2)) assert.equal("-2", sprintf("%+i", -2)) assert.equal("2.2", sprintf("%f", 2.2)) assert.equal("-2.2", sprintf("%f", -2.2)) assert.equal("+2.2", sprintf("%+f", 2.2)) assert.equal("-2.2", sprintf("%+f", -2.2)) assert.equal("-2.3", sprintf("%+.1f", -2.34)) assert.equal("-0.0", sprintf("%+.1f", -0.01)) assert.equal("3.14159", sprintf("%.6g", pi)) assert.equal("3.14", sprintf("%.3g", pi)) assert.equal("3", sprintf("%.1g", pi)) assert.equal("-000000123", sprintf("%+010d", -123)) assert.equal("______-123", sprintf("%+'_10d", -123)) assert.equal("-234.34 123.2", sprintf("%f %f", -234.34, 123.2)) // padding assert.equal("-0002", sprintf("%05d", -2)) assert.equal("-0002", sprintf("%05i", -2)) assert.equal(" <", sprintf("%5s", "<")) assert.equal("0000<", sprintf("%05s", "<")) assert.equal("____<", sprintf("%'_5s", "<")) assert.equal("> ", sprintf("%-5s", ">")) assert.equal(">0000", sprintf("%0-5s", ">")) assert.equal(">____", sprintf("%'_-5s", ">")) assert.equal("xxxxxx", sprintf("%5s", "xxxxxx")) assert.equal("1234", sprintf("%02u", 1234)) assert.equal(" -10.235", sprintf("%8.3f", -10.23456)) assert.equal("-12.34 xxx", sprintf("%f %s", -12.34, "xxx")) assert.equal('{\n "foo": "bar"\n}', sprintf("%2j", {foo: "bar"})) assert.equal('[\n "foo",\n "bar"\n]', sprintf("%2j", ["foo", "bar"])) // precision assert.equal("2.3", sprintf("%.1f", 2.345)) assert.equal("xxxxx", sprintf("%5.5s", "xxxxxx")) assert.equal(" x", sprintf("%5.1s", "xxxxxx")) }) it("should return formated strings for callbacks", function() { assert.equal("foobar", sprintf("%s", function() { return "foobar" })) assert.equal(Date.now(), sprintf("%s", Date.now)) // should pass... }) }) PK ~\Ubhsprintf-js/LICENSEnu[Copyright (c) 2007-present, Alexandru Mărășteanu All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of this software nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. PK ~\56jjsprintf-js/dist/.gitattributesnu[#ignore all generated files from diff #also skip line ending check *.js -diff -text *.map -diff -text PK ~\6] &sprintf-js/dist/angular-sprintf.min.jsnu[/*! sprintf-js v1.1.3 | Copyright (c) 2007-present, Alexandru Mărășteanu | BSD-3-Clause */ !function(){"use strict";angular.module("sprintf",[]).filter("sprintf",function(){return function(){return sprintf.apply(null,arguments)}}).filter("fmt",["$filter",function(t){return t("sprintf")}]).filter("vsprintf",function(){return function(t,n){return vsprintf(t,n)}}).filter("vfmt",["$filter",function(t){return t("vsprintf")}])}(); //# sourceMappingURL=angular-sprintf.min.js.map PK ~\g[[sprintf-js/dist/sprintf.min.jsnu[/*! sprintf-js v1.1.3 | Copyright (c) 2007-present, Alexandru Mărășteanu | BSD-3-Clause */ !function(){"use strict";var g={not_string:/[^s]/,not_bool:/[^t]/,not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[+-]/};function y(e){return function(e,t){var r,n,i,s,a,o,p,c,l,u=1,f=e.length,d="";for(n=0;n>>0).toString(8);break;case"s":r=String(r),r=s.precision?r.substring(0,s.precision):r;break;case"t":r=String(!!r),r=s.precision?r.substring(0,s.precision):r;break;case"T":r=Object.prototype.toString.call(r).slice(8,-1).toLowerCase(),r=s.precision?r.substring(0,s.precision):r;break;case"u":r=parseInt(r,10)>>>0;break;case"v":r=r.valueOf(),r=s.precision?r.substring(0,s.precision):r;break;case"x":r=(parseInt(r,10)>>>0).toString(16);break;case"X":r=(parseInt(r,10)>>>0).toString(16).toUpperCase()}g.json.test(s.type)?d+=r:(!g.number.test(s.type)||c&&!s.sign?l="":(l=c?"+":"-",r=r.toString().replace(g.sign,"")),o=s.pad_char?"0"===s.pad_char?"0":s.pad_char.charAt(1):" ",p=s.width-(l+r).length,a=s.width&&0 (http://alexei.ro/)"], "homepage": "https://github.com/alexei/sprintf.js", "repository": { "type": "git", "url": "git://github.com/alexei/sprintf.js.git" } } PK ~\q׻ ip-address/package.jsonnu[{ "_id": "ip-address@9.0.5", "_inBundle": true, "_location": "/npm/ip-address", "_phantomChildren": {}, "_requiredBy": [ "/npm/socks" ], "author": { "name": "Beau Gunderson", "email": "beau@beaugunderson.com", "url": "https://beaugunderson.com/" }, "bugs": { "url": "https://github.com/beaugunderson/ip-address/issues" }, "dependencies": { "jsbn": "1.1.0", "sprintf-js": "^1.1.3" }, "description": "A library for parsing IPv4 and IPv6 IP addresses in node and the browser.", "devDependencies": { "@types/chai": "^4.2.18", "@types/jsbn": "^1.2.31", "@types/mocha": "^10.0.1", "@types/sprintf-js": "^1.1.2", "@typescript-eslint/eslint-plugin": "^6.7.2", "@typescript-eslint/parser": "^6.7.2", "browserify": "^17.0.0", "chai": "^4.3.4", "codecov": "^3.8.2", "documentation": "^14.0.2", "eslint": "^8.50.0", "eslint-config-airbnb": "^19.0.4", "eslint-config-prettier": "^9.0.0", "eslint-plugin-filenames": "^1.3.2", "eslint-plugin-import": "^2.23.4", "eslint-plugin-jsx-a11y": "^6.4.1", "eslint-plugin-prettier": "^5.0.0", "eslint-plugin-react": "^7.24.0", "eslint-plugin-react-hooks": "^4.2.0", "eslint-plugin-sort-imports-es6-autofix": "^0.6.0", "mocha": "^10.2.0", "nyc": "^15.1.0", "prettier": "^3.0.3", "release-it": "^16.2.0", "source-map-support": "^0.5.19", "ts-node": "^10.0.0", "typescript": "^5.2.2" }, "engines": { "node": ">= 12" }, "files": [ "src", "dist" ], "homepage": "https://github.com/beaugunderson/ip-address#readme", "keywords": [ "ipv6", "ipv4", "browser", "validation" ], "license": "MIT", "main": "dist/ip-address.js", "name": "ip-address", "nyc": { "extension": [ ".ts" ], "exclude": [ "**/*.d.ts", ".eslintrc.js", "coverage/", "dist/", "test/", "tmp/" ], "reporter": [ "html", "lcov", "text" ], "all": true }, "repository": { "type": "git", "url": "git://github.com/beaugunderson/ip-address.git" }, "scripts": { "build": "rm -rf dist; mkdir dist; tsc", "docs": "documentation build --github --output docs --format html ./ip-address.js", "prepack": "npm run build", "release": "release-it", "test": "mocha", "test-ci": "nyc mocha", "watch": "mocha --watch" }, "types": "dist/ip-address.d.ts", "version": "9.0.5" } PK ~\u%%ip-address/LICENSEnu[Copyright (C) 2011 by Beau Gunderson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\D3ip-address/dist/v4/constants.jsnu["use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RE_SUBNET_STRING = exports.RE_ADDRESS = exports.GROUPS = exports.BITS = void 0; exports.BITS = 32; exports.GROUPS = 4; exports.RE_ADDRESS = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g; exports.RE_SUBNET_STRING = /\/\d{1,2}$/; //# sourceMappingURL=constants.js.mapPK ~\fip-address/dist/ipv6.jsnu["use strict"; /* eslint-disable prefer-destructuring */ /* eslint-disable no-param-reassign */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Address6 = void 0; const common = __importStar(require("./common")); const constants4 = __importStar(require("./v4/constants")); const constants6 = __importStar(require("./v6/constants")); const helpers = __importStar(require("./v6/helpers")); const ipv4_1 = require("./ipv4"); const regular_expressions_1 = require("./v6/regular-expressions"); const address_error_1 = require("./address-error"); const jsbn_1 = require("jsbn"); const sprintf_js_1 = require("sprintf-js"); function assert(condition) { if (!condition) { throw new Error('Assertion failed.'); } } function addCommas(number) { const r = /(\d+)(\d{3})/; while (r.test(number)) { number = number.replace(r, '$1,$2'); } return number; } function spanLeadingZeroes4(n) { n = n.replace(/^(0{1,})([1-9]+)$/, '$1$2'); n = n.replace(/^(0{1,})(0)$/, '$1$2'); return n; } /* * A helper function to compact an array */ function compact(address, slice) { const s1 = []; const s2 = []; let i; for (i = 0; i < address.length; i++) { if (i < slice[0]) { s1.push(address[i]); } else if (i > slice[1]) { s2.push(address[i]); } } return s1.concat(['compact']).concat(s2); } function paddedHex(octet) { return (0, sprintf_js_1.sprintf)('%04x', parseInt(octet, 16)); } function unsignByte(b) { // eslint-disable-next-line no-bitwise return b & 0xff; } /** * Represents an IPv6 address * @class Address6 * @param {string} address - An IPv6 address string * @param {number} [groups=8] - How many octets to parse * @example * var address = new Address6('2001::/32'); */ class Address6 { constructor(address, optionalGroups) { this.addressMinusSuffix = ''; this.parsedSubnet = ''; this.subnet = '/128'; this.subnetMask = 128; this.v4 = false; this.zone = ''; // #region Attributes /** * Returns true if the given address is in the subnet of the current address * @memberof Address6 * @instance * @returns {boolean} */ this.isInSubnet = common.isInSubnet; /** * Returns true if the address is correct, false otherwise * @memberof Address6 * @instance * @returns {boolean} */ this.isCorrect = common.isCorrect(constants6.BITS); if (optionalGroups === undefined) { this.groups = constants6.GROUPS; } else { this.groups = optionalGroups; } this.address = address; const subnet = constants6.RE_SUBNET_STRING.exec(address); if (subnet) { this.parsedSubnet = subnet[0].replace('/', ''); this.subnetMask = parseInt(this.parsedSubnet, 10); this.subnet = `/${this.subnetMask}`; if (Number.isNaN(this.subnetMask) || this.subnetMask < 0 || this.subnetMask > constants6.BITS) { throw new address_error_1.AddressError('Invalid subnet mask.'); } address = address.replace(constants6.RE_SUBNET_STRING, ''); } else if (/\//.test(address)) { throw new address_error_1.AddressError('Invalid subnet mask.'); } const zone = constants6.RE_ZONE_STRING.exec(address); if (zone) { this.zone = zone[0]; address = address.replace(constants6.RE_ZONE_STRING, ''); } this.addressMinusSuffix = address; this.parsedAddress = this.parse(this.addressMinusSuffix); } static isValid(address) { try { // eslint-disable-next-line no-new new Address6(address); return true; } catch (e) { return false; } } /** * Convert a BigInteger to a v6 address object * @memberof Address6 * @static * @param {BigInteger} bigInteger - a BigInteger to convert * @returns {Address6} * @example * var bigInteger = new BigInteger('1000000000000'); * var address = Address6.fromBigInteger(bigInteger); * address.correctForm(); // '::e8:d4a5:1000' */ static fromBigInteger(bigInteger) { const hex = bigInteger.toString(16).padStart(32, '0'); const groups = []; let i; for (i = 0; i < constants6.GROUPS; i++) { groups.push(hex.slice(i * 4, (i + 1) * 4)); } return new Address6(groups.join(':')); } /** * Convert a URL (with optional port number) to an address object * @memberof Address6 * @static * @param {string} url - a URL with optional port number * @example * var addressAndPort = Address6.fromURL('http://[ffff::]:8080/foo/'); * addressAndPort.address.correctForm(); // 'ffff::' * addressAndPort.port; // 8080 */ static fromURL(url) { let host; let port = null; let result; // If we have brackets parse them and find a port if (url.indexOf('[') !== -1 && url.indexOf(']:') !== -1) { result = constants6.RE_URL_WITH_PORT.exec(url); if (result === null) { return { error: 'failed to parse address with port', address: null, port: null, }; } host = result[1]; port = result[2]; // If there's a URL extract the address } else if (url.indexOf('/') !== -1) { // Remove the protocol prefix url = url.replace(/^[a-z0-9]+:\/\//, ''); // Parse the address result = constants6.RE_URL.exec(url); if (result === null) { return { error: 'failed to parse address from URL', address: null, port: null, }; } host = result[1]; // Otherwise just assign the URL to the host and let the library parse it } else { host = url; } // If there's a port convert it to an integer if (port) { port = parseInt(port, 10); // squelch out of range ports if (port < 0 || port > 65536) { port = null; } } else { // Standardize `undefined` to `null` port = null; } return { address: new Address6(host), port, }; } /** * Create an IPv6-mapped address given an IPv4 address * @memberof Address6 * @static * @param {string} address - An IPv4 address string * @returns {Address6} * @example * var address = Address6.fromAddress4('192.168.0.1'); * address.correctForm(); // '::ffff:c0a8:1' * address.to4in6(); // '::ffff:192.168.0.1' */ static fromAddress4(address) { const address4 = new ipv4_1.Address4(address); const mask6 = constants6.BITS - (constants4.BITS - address4.subnetMask); return new Address6(`::ffff:${address4.correctForm()}/${mask6}`); } /** * Return an address from ip6.arpa form * @memberof Address6 * @static * @param {string} arpaFormAddress - an 'ip6.arpa' form address * @returns {Adress6} * @example * var address = Address6.fromArpa(e.f.f.f.3.c.2.6.f.f.f.e.6.6.8.e.1.0.6.7.9.4.e.c.0.0.0.0.1.0.0.2.ip6.arpa.) * address.correctForm(); // '2001:0:ce49:7601:e866:efff:62c3:fffe' */ static fromArpa(arpaFormAddress) { // remove ending ".ip6.arpa." or just "." let address = arpaFormAddress.replace(/(\.ip6\.arpa)?\.$/, ''); const semicolonAmount = 7; // correct ip6.arpa form with ending removed will be 63 characters if (address.length !== 63) { throw new address_error_1.AddressError("Invalid 'ip6.arpa' form."); } const parts = address.split('.').reverse(); for (let i = semicolonAmount; i > 0; i--) { const insertIndex = i * 4; parts.splice(insertIndex, 0, ':'); } address = parts.join(''); return new Address6(address); } /** * Return the Microsoft UNC transcription of the address * @memberof Address6 * @instance * @returns {String} the Microsoft UNC transcription of the address */ microsoftTranscription() { return (0, sprintf_js_1.sprintf)('%s.ipv6-literal.net', this.correctForm().replace(/:/g, '-')); } /** * Return the first n bits of the address, defaulting to the subnet mask * @memberof Address6 * @instance * @param {number} [mask=subnet] - the number of bits to mask * @returns {String} the first n bits of the address as a string */ mask(mask = this.subnetMask) { return this.getBitsBase2(0, mask); } /** * Return the number of possible subnets of a given size in the address * @memberof Address6 * @instance * @param {number} [size=128] - the subnet size * @returns {String} */ // TODO: probably useful to have a numeric version of this too possibleSubnets(subnetSize = 128) { const availableBits = constants6.BITS - this.subnetMask; const subnetBits = Math.abs(subnetSize - constants6.BITS); const subnetPowers = availableBits - subnetBits; if (subnetPowers < 0) { return '0'; } return addCommas(new jsbn_1.BigInteger('2', 10).pow(subnetPowers).toString(10)); } /** * Helper function getting start address. * @memberof Address6 * @instance * @returns {BigInteger} */ _startAddress() { return new jsbn_1.BigInteger(this.mask() + '0'.repeat(constants6.BITS - this.subnetMask), 2); } /** * The first address in the range given by this address' subnet * Often referred to as the Network Address. * @memberof Address6 * @instance * @returns {Address6} */ startAddress() { return Address6.fromBigInteger(this._startAddress()); } /** * The first host address in the range given by this address's subnet ie * the first address after the Network Address * @memberof Address6 * @instance * @returns {Address6} */ startAddressExclusive() { const adjust = new jsbn_1.BigInteger('1'); return Address6.fromBigInteger(this._startAddress().add(adjust)); } /** * Helper function getting end address. * @memberof Address6 * @instance * @returns {BigInteger} */ _endAddress() { return new jsbn_1.BigInteger(this.mask() + '1'.repeat(constants6.BITS - this.subnetMask), 2); } /** * The last address in the range given by this address' subnet * Often referred to as the Broadcast * @memberof Address6 * @instance * @returns {Address6} */ endAddress() { return Address6.fromBigInteger(this._endAddress()); } /** * The last host address in the range given by this address's subnet ie * the last address prior to the Broadcast Address * @memberof Address6 * @instance * @returns {Address6} */ endAddressExclusive() { const adjust = new jsbn_1.BigInteger('1'); return Address6.fromBigInteger(this._endAddress().subtract(adjust)); } /** * Return the scope of the address * @memberof Address6 * @instance * @returns {String} */ getScope() { let scope = constants6.SCOPES[this.getBits(12, 16).intValue()]; if (this.getType() === 'Global unicast' && scope !== 'Link local') { scope = 'Global'; } return scope || 'Unknown'; } /** * Return the type of the address * @memberof Address6 * @instance * @returns {String} */ getType() { for (const subnet of Object.keys(constants6.TYPES)) { if (this.isInSubnet(new Address6(subnet))) { return constants6.TYPES[subnet]; } } return 'Global unicast'; } /** * Return the bits in the given range as a BigInteger * @memberof Address6 * @instance * @returns {BigInteger} */ getBits(start, end) { return new jsbn_1.BigInteger(this.getBitsBase2(start, end), 2); } /** * Return the bits in the given range as a base-2 string * @memberof Address6 * @instance * @returns {String} */ getBitsBase2(start, end) { return this.binaryZeroPad().slice(start, end); } /** * Return the bits in the given range as a base-16 string * @memberof Address6 * @instance * @returns {String} */ getBitsBase16(start, end) { const length = end - start; if (length % 4 !== 0) { throw new Error('Length of bits to retrieve must be divisible by four'); } return this.getBits(start, end) .toString(16) .padStart(length / 4, '0'); } /** * Return the bits that are set past the subnet mask length * @memberof Address6 * @instance * @returns {String} */ getBitsPastSubnet() { return this.getBitsBase2(this.subnetMask, constants6.BITS); } /** * Return the reversed ip6.arpa form of the address * @memberof Address6 * @param {Object} options * @param {boolean} options.omitSuffix - omit the "ip6.arpa" suffix * @instance * @returns {String} */ reverseForm(options) { if (!options) { options = {}; } const characters = Math.floor(this.subnetMask / 4); const reversed = this.canonicalForm() .replace(/:/g, '') .split('') .slice(0, characters) .reverse() .join('.'); if (characters > 0) { if (options.omitSuffix) { return reversed; } return (0, sprintf_js_1.sprintf)('%s.ip6.arpa.', reversed); } if (options.omitSuffix) { return ''; } return 'ip6.arpa.'; } /** * Return the correct form of the address * @memberof Address6 * @instance * @returns {String} */ correctForm() { let i; let groups = []; let zeroCounter = 0; const zeroes = []; for (i = 0; i < this.parsedAddress.length; i++) { const value = parseInt(this.parsedAddress[i], 16); if (value === 0) { zeroCounter++; } if (value !== 0 && zeroCounter > 0) { if (zeroCounter > 1) { zeroes.push([i - zeroCounter, i - 1]); } zeroCounter = 0; } } // Do we end with a string of zeroes? if (zeroCounter > 1) { zeroes.push([this.parsedAddress.length - zeroCounter, this.parsedAddress.length - 1]); } const zeroLengths = zeroes.map((n) => n[1] - n[0] + 1); if (zeroes.length > 0) { const index = zeroLengths.indexOf(Math.max(...zeroLengths)); groups = compact(this.parsedAddress, zeroes[index]); } else { groups = this.parsedAddress; } for (i = 0; i < groups.length; i++) { if (groups[i] !== 'compact') { groups[i] = parseInt(groups[i], 16).toString(16); } } let correct = groups.join(':'); correct = correct.replace(/^compact$/, '::'); correct = correct.replace(/^compact|compact$/, ':'); correct = correct.replace(/compact/, ''); return correct; } /** * Return a zero-padded base-2 string representation of the address * @memberof Address6 * @instance * @returns {String} * @example * var address = new Address6('2001:4860:4001:803::1011'); * address.binaryZeroPad(); * // '0010000000000001010010000110000001000000000000010000100000000011 * // 0000000000000000000000000000000000000000000000000001000000010001' */ binaryZeroPad() { return this.bigInteger().toString(2).padStart(constants6.BITS, '0'); } // TODO: Improve the semantics of this helper function parse4in6(address) { const groups = address.split(':'); const lastGroup = groups.slice(-1)[0]; const address4 = lastGroup.match(constants4.RE_ADDRESS); if (address4) { this.parsedAddress4 = address4[0]; this.address4 = new ipv4_1.Address4(this.parsedAddress4); for (let i = 0; i < this.address4.groups; i++) { if (/^0[0-9]+/.test(this.address4.parsedAddress[i])) { throw new address_error_1.AddressError("IPv4 addresses can't have leading zeroes.", address.replace(constants4.RE_ADDRESS, this.address4.parsedAddress.map(spanLeadingZeroes4).join('.'))); } } this.v4 = true; groups[groups.length - 1] = this.address4.toGroup6(); address = groups.join(':'); } return address; } // TODO: Make private? parse(address) { address = this.parse4in6(address); const badCharacters = address.match(constants6.RE_BAD_CHARACTERS); if (badCharacters) { throw new address_error_1.AddressError((0, sprintf_js_1.sprintf)('Bad character%s detected in address: %s', badCharacters.length > 1 ? 's' : '', badCharacters.join('')), address.replace(constants6.RE_BAD_CHARACTERS, '$1')); } const badAddress = address.match(constants6.RE_BAD_ADDRESS); if (badAddress) { throw new address_error_1.AddressError((0, sprintf_js_1.sprintf)('Address failed regex: %s', badAddress.join('')), address.replace(constants6.RE_BAD_ADDRESS, '$1')); } let groups = []; const halves = address.split('::'); if (halves.length === 2) { let first = halves[0].split(':'); let last = halves[1].split(':'); if (first.length === 1 && first[0] === '') { first = []; } if (last.length === 1 && last[0] === '') { last = []; } const remaining = this.groups - (first.length + last.length); if (!remaining) { throw new address_error_1.AddressError('Error parsing groups'); } this.elidedGroups = remaining; this.elisionBegin = first.length; this.elisionEnd = first.length + this.elidedGroups; groups = groups.concat(first); for (let i = 0; i < remaining; i++) { groups.push('0'); } groups = groups.concat(last); } else if (halves.length === 1) { groups = address.split(':'); this.elidedGroups = 0; } else { throw new address_error_1.AddressError('Too many :: groups found'); } groups = groups.map((group) => (0, sprintf_js_1.sprintf)('%x', parseInt(group, 16))); if (groups.length !== this.groups) { throw new address_error_1.AddressError('Incorrect number of groups found'); } return groups; } /** * Return the canonical form of the address * @memberof Address6 * @instance * @returns {String} */ canonicalForm() { return this.parsedAddress.map(paddedHex).join(':'); } /** * Return the decimal form of the address * @memberof Address6 * @instance * @returns {String} */ decimal() { return this.parsedAddress.map((n) => (0, sprintf_js_1.sprintf)('%05d', parseInt(n, 16))).join(':'); } /** * Return the address as a BigInteger * @memberof Address6 * @instance * @returns {BigInteger} */ bigInteger() { return new jsbn_1.BigInteger(this.parsedAddress.map(paddedHex).join(''), 16); } /** * Return the last two groups of this address as an IPv4 address string * @memberof Address6 * @instance * @returns {Address4} * @example * var address = new Address6('2001:4860:4001::1825:bf11'); * address.to4().correctForm(); // '24.37.191.17' */ to4() { const binary = this.binaryZeroPad().split(''); return ipv4_1.Address4.fromHex(new jsbn_1.BigInteger(binary.slice(96, 128).join(''), 2).toString(16)); } /** * Return the v4-in-v6 form of the address * @memberof Address6 * @instance * @returns {String} */ to4in6() { const address4 = this.to4(); const address6 = new Address6(this.parsedAddress.slice(0, 6).join(':'), 6); const correct = address6.correctForm(); let infix = ''; if (!/:$/.test(correct)) { infix = ':'; } return correct + infix + address4.address; } /** * Return an object containing the Teredo properties of the address * @memberof Address6 * @instance * @returns {Object} */ inspectTeredo() { /* - Bits 0 to 31 are set to the Teredo prefix (normally 2001:0000::/32). - Bits 32 to 63 embed the primary IPv4 address of the Teredo server that is used. - Bits 64 to 79 can be used to define some flags. Currently only the higher order bit is used; it is set to 1 if the Teredo client is located behind a cone NAT, 0 otherwise. For Microsoft's Windows Vista and Windows Server 2008 implementations, more bits are used. In those implementations, the format for these 16 bits is "CRAAAAUG AAAAAAAA", where "C" remains the "Cone" flag. The "R" bit is reserved for future use. The "U" bit is for the Universal/Local flag (set to 0). The "G" bit is Individual/Group flag (set to 0). The A bits are set to a 12-bit randomly generated number chosen by the Teredo client to introduce additional protection for the Teredo node against IPv6-based scanning attacks. - Bits 80 to 95 contains the obfuscated UDP port number. This is the port number that is mapped by the NAT to the Teredo client with all bits inverted. - Bits 96 to 127 contains the obfuscated IPv4 address. This is the public IPv4 address of the NAT with all bits inverted. */ const prefix = this.getBitsBase16(0, 32); const udpPort = this.getBits(80, 96).xor(new jsbn_1.BigInteger('ffff', 16)).toString(); const server4 = ipv4_1.Address4.fromHex(this.getBitsBase16(32, 64)); const client4 = ipv4_1.Address4.fromHex(this.getBits(96, 128).xor(new jsbn_1.BigInteger('ffffffff', 16)).toString(16)); const flags = this.getBits(64, 80); const flagsBase2 = this.getBitsBase2(64, 80); const coneNat = flags.testBit(15); const reserved = flags.testBit(14); const groupIndividual = flags.testBit(8); const universalLocal = flags.testBit(9); const nonce = new jsbn_1.BigInteger(flagsBase2.slice(2, 6) + flagsBase2.slice(8, 16), 2).toString(10); return { prefix: (0, sprintf_js_1.sprintf)('%s:%s', prefix.slice(0, 4), prefix.slice(4, 8)), server4: server4.address, client4: client4.address, flags: flagsBase2, coneNat, microsoft: { reserved, universalLocal, groupIndividual, nonce, }, udpPort, }; } /** * Return an object containing the 6to4 properties of the address * @memberof Address6 * @instance * @returns {Object} */ inspect6to4() { /* - Bits 0 to 15 are set to the 6to4 prefix (2002::/16). - Bits 16 to 48 embed the IPv4 address of the 6to4 gateway that is used. */ const prefix = this.getBitsBase16(0, 16); const gateway = ipv4_1.Address4.fromHex(this.getBitsBase16(16, 48)); return { prefix: (0, sprintf_js_1.sprintf)('%s', prefix.slice(0, 4)), gateway: gateway.address, }; } /** * Return a v6 6to4 address from a v6 v4inv6 address * @memberof Address6 * @instance * @returns {Address6} */ to6to4() { if (!this.is4()) { return null; } const addr6to4 = [ '2002', this.getBitsBase16(96, 112), this.getBitsBase16(112, 128), '', '/16', ].join(':'); return new Address6(addr6to4); } /** * Return a byte array * @memberof Address6 * @instance * @returns {Array} */ toByteArray() { const byteArray = this.bigInteger().toByteArray(); // work around issue where `toByteArray` returns a leading 0 element if (byteArray.length === 17 && byteArray[0] === 0) { return byteArray.slice(1); } return byteArray; } /** * Return an unsigned byte array * @memberof Address6 * @instance * @returns {Array} */ toUnsignedByteArray() { return this.toByteArray().map(unsignByte); } /** * Convert a byte array to an Address6 object * @memberof Address6 * @static * @returns {Address6} */ static fromByteArray(bytes) { return this.fromUnsignedByteArray(bytes.map(unsignByte)); } /** * Convert an unsigned byte array to an Address6 object * @memberof Address6 * @static * @returns {Address6} */ static fromUnsignedByteArray(bytes) { const BYTE_MAX = new jsbn_1.BigInteger('256', 10); let result = new jsbn_1.BigInteger('0', 10); let multiplier = new jsbn_1.BigInteger('1', 10); for (let i = bytes.length - 1; i >= 0; i--) { result = result.add(multiplier.multiply(new jsbn_1.BigInteger(bytes[i].toString(10), 10))); multiplier = multiplier.multiply(BYTE_MAX); } return Address6.fromBigInteger(result); } /** * Returns true if the address is in the canonical form, false otherwise * @memberof Address6 * @instance * @returns {boolean} */ isCanonical() { return this.addressMinusSuffix === this.canonicalForm(); } /** * Returns true if the address is a link local address, false otherwise * @memberof Address6 * @instance * @returns {boolean} */ isLinkLocal() { // Zeroes are required, i.e. we can't check isInSubnet with 'fe80::/10' if (this.getBitsBase2(0, 64) === '1111111010000000000000000000000000000000000000000000000000000000') { return true; } return false; } /** * Returns true if the address is a multicast address, false otherwise * @memberof Address6 * @instance * @returns {boolean} */ isMulticast() { return this.getType() === 'Multicast'; } /** * Returns true if the address is a v4-in-v6 address, false otherwise * @memberof Address6 * @instance * @returns {boolean} */ is4() { return this.v4; } /** * Returns true if the address is a Teredo address, false otherwise * @memberof Address6 * @instance * @returns {boolean} */ isTeredo() { return this.isInSubnet(new Address6('2001::/32')); } /** * Returns true if the address is a 6to4 address, false otherwise * @memberof Address6 * @instance * @returns {boolean} */ is6to4() { return this.isInSubnet(new Address6('2002::/16')); } /** * Returns true if the address is a loopback address, false otherwise * @memberof Address6 * @instance * @returns {boolean} */ isLoopback() { return this.getType() === 'Loopback'; } // #endregion // #region HTML /** * @returns {String} the address in link form with a default port of 80 */ href(optionalPort) { if (optionalPort === undefined) { optionalPort = ''; } else { optionalPort = (0, sprintf_js_1.sprintf)(':%s', optionalPort); } return (0, sprintf_js_1.sprintf)('http://[%s]%s/', this.correctForm(), optionalPort); } /** * @returns {String} a link suitable for conveying the address via a URL hash */ link(options) { if (!options) { options = {}; } if (options.className === undefined) { options.className = ''; } if (options.prefix === undefined) { options.prefix = '/#address='; } if (options.v4 === undefined) { options.v4 = false; } let formFunction = this.correctForm; if (options.v4) { formFunction = this.to4in6; } if (options.className) { return (0, sprintf_js_1.sprintf)('%2$s', options.prefix, formFunction.call(this), options.className); } return (0, sprintf_js_1.sprintf)('%2$s', options.prefix, formFunction.call(this)); } /** * Groups an address * @returns {String} */ group() { if (this.elidedGroups === 0) { // The simple case return helpers.simpleGroup(this.address).join(':'); } assert(typeof this.elidedGroups === 'number'); assert(typeof this.elisionBegin === 'number'); // The elided case const output = []; const [left, right] = this.address.split('::'); if (left.length) { output.push(...helpers.simpleGroup(left)); } else { output.push(''); } const classes = ['hover-group']; for (let i = this.elisionBegin; i < this.elisionBegin + this.elidedGroups; i++) { classes.push((0, sprintf_js_1.sprintf)('group-%d', i)); } output.push((0, sprintf_js_1.sprintf)('', classes.join(' '))); if (right.length) { output.push(...helpers.simpleGroup(right, this.elisionEnd)); } else { output.push(''); } if (this.is4()) { assert(this.address4 instanceof ipv4_1.Address4); output.pop(); output.push(this.address4.groupForV6()); } return output.join(':'); } // #endregion // #region Regular expressions /** * Generate a regular expression string that can be used to find or validate * all variations of this address * @memberof Address6 * @instance * @param {boolean} substringSearch * @returns {string} */ regularExpressionString(substringSearch = false) { let output = []; // TODO: revisit why this is necessary const address6 = new Address6(this.correctForm()); if (address6.elidedGroups === 0) { // The simple case output.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress)); } else if (address6.elidedGroups === constants6.GROUPS) { // A completely elided address output.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS)); } else { // A partially elided address const halves = address6.address.split('::'); if (halves[0].length) { output.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(':'))); } assert(typeof address6.elidedGroups === 'number'); output.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0)); if (halves[1].length) { output.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(':'))); } output = [output.join(':')]; } if (!substringSearch) { output = [ '(?=^|', regular_expressions_1.ADDRESS_BOUNDARY, '|[^\\w\\:])(', ...output, ')(?=[^\\w\\:]|', regular_expressions_1.ADDRESS_BOUNDARY, '|$)', ]; } return output.join(''); } /** * Generate a regular expression that can be used to find or validate all * variations of this address. * @memberof Address6 * @instance * @param {boolean} substringSearch * @returns {RegExp} */ regularExpression(substringSearch = false) { return new RegExp(this.regularExpressionString(substringSearch), 'i'); } } exports.Address6 = Address6; //# sourceMappingURL=ipv6.js.mapPK ~\zip-address/dist/ip-address.jsnu["use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.v6 = exports.AddressError = exports.Address6 = exports.Address4 = void 0; const ipv4_1 = require("./ipv4"); Object.defineProperty(exports, "Address4", { enumerable: true, get: function () { return ipv4_1.Address4; } }); const ipv6_1 = require("./ipv6"); Object.defineProperty(exports, "Address6", { enumerable: true, get: function () { return ipv6_1.Address6; } }); const address_error_1 = require("./address-error"); Object.defineProperty(exports, "AddressError", { enumerable: true, get: function () { return address_error_1.AddressError; } }); const helpers = __importStar(require("./v6/helpers")); exports.v6 = { helpers }; //# sourceMappingURL=ip-address.js.mapPK ~\|SPn)n)ip-address/dist/ipv4.jsnu["use strict"; /* eslint-disable no-param-reassign */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Address4 = void 0; const common = __importStar(require("./common")); const constants = __importStar(require("./v4/constants")); const address_error_1 = require("./address-error"); const jsbn_1 = require("jsbn"); const sprintf_js_1 = require("sprintf-js"); /** * Represents an IPv4 address * @class Address4 * @param {string} address - An IPv4 address string */ class Address4 { constructor(address) { this.groups = constants.GROUPS; this.parsedAddress = []; this.parsedSubnet = ''; this.subnet = '/32'; this.subnetMask = 32; this.v4 = true; /** * Returns true if the address is correct, false otherwise * @memberof Address4 * @instance * @returns {Boolean} */ this.isCorrect = common.isCorrect(constants.BITS); /** * Returns true if the given address is in the subnet of the current address * @memberof Address4 * @instance * @returns {boolean} */ this.isInSubnet = common.isInSubnet; this.address = address; const subnet = constants.RE_SUBNET_STRING.exec(address); if (subnet) { this.parsedSubnet = subnet[0].replace('/', ''); this.subnetMask = parseInt(this.parsedSubnet, 10); this.subnet = `/${this.subnetMask}`; if (this.subnetMask < 0 || this.subnetMask > constants.BITS) { throw new address_error_1.AddressError('Invalid subnet mask.'); } address = address.replace(constants.RE_SUBNET_STRING, ''); } this.addressMinusSuffix = address; this.parsedAddress = this.parse(address); } static isValid(address) { try { // eslint-disable-next-line no-new new Address4(address); return true; } catch (e) { return false; } } /* * Parses a v4 address */ parse(address) { const groups = address.split('.'); if (!address.match(constants.RE_ADDRESS)) { throw new address_error_1.AddressError('Invalid IPv4 address.'); } return groups; } /** * Returns the correct form of an address * @memberof Address4 * @instance * @returns {String} */ correctForm() { return this.parsedAddress.map((part) => parseInt(part, 10)).join('.'); } /** * Converts a hex string to an IPv4 address object * @memberof Address4 * @static * @param {string} hex - a hex string to convert * @returns {Address4} */ static fromHex(hex) { const padded = hex.replace(/:/g, '').padStart(8, '0'); const groups = []; let i; for (i = 0; i < 8; i += 2) { const h = padded.slice(i, i + 2); groups.push(parseInt(h, 16)); } return new Address4(groups.join('.')); } /** * Converts an integer into a IPv4 address object * @memberof Address4 * @static * @param {integer} integer - a number to convert * @returns {Address4} */ static fromInteger(integer) { return Address4.fromHex(integer.toString(16)); } /** * Return an address from in-addr.arpa form * @memberof Address4 * @static * @param {string} arpaFormAddress - an 'in-addr.arpa' form ipv4 address * @returns {Adress4} * @example * var address = Address4.fromArpa(42.2.0.192.in-addr.arpa.) * address.correctForm(); // '192.0.2.42' */ static fromArpa(arpaFormAddress) { // remove ending ".in-addr.arpa." or just "." const leader = arpaFormAddress.replace(/(\.in-addr\.arpa)?\.$/, ''); const address = leader.split('.').reverse().join('.'); return new Address4(address); } /** * Converts an IPv4 address object to a hex string * @memberof Address4 * @instance * @returns {String} */ toHex() { return this.parsedAddress.map((part) => (0, sprintf_js_1.sprintf)('%02x', parseInt(part, 10))).join(':'); } /** * Converts an IPv4 address object to an array of bytes * @memberof Address4 * @instance * @returns {Array} */ toArray() { return this.parsedAddress.map((part) => parseInt(part, 10)); } /** * Converts an IPv4 address object to an IPv6 address group * @memberof Address4 * @instance * @returns {String} */ toGroup6() { const output = []; let i; for (i = 0; i < constants.GROUPS; i += 2) { const hex = (0, sprintf_js_1.sprintf)('%02x%02x', parseInt(this.parsedAddress[i], 10), parseInt(this.parsedAddress[i + 1], 10)); output.push((0, sprintf_js_1.sprintf)('%x', parseInt(hex, 16))); } return output.join(':'); } /** * Returns the address as a BigInteger * @memberof Address4 * @instance * @returns {BigInteger} */ bigInteger() { return new jsbn_1.BigInteger(this.parsedAddress.map((n) => (0, sprintf_js_1.sprintf)('%02x', parseInt(n, 10))).join(''), 16); } /** * Helper function getting start address. * @memberof Address4 * @instance * @returns {BigInteger} */ _startAddress() { return new jsbn_1.BigInteger(this.mask() + '0'.repeat(constants.BITS - this.subnetMask), 2); } /** * The first address in the range given by this address' subnet. * Often referred to as the Network Address. * @memberof Address4 * @instance * @returns {Address4} */ startAddress() { return Address4.fromBigInteger(this._startAddress()); } /** * The first host address in the range given by this address's subnet ie * the first address after the Network Address * @memberof Address4 * @instance * @returns {Address4} */ startAddressExclusive() { const adjust = new jsbn_1.BigInteger('1'); return Address4.fromBigInteger(this._startAddress().add(adjust)); } /** * Helper function getting end address. * @memberof Address4 * @instance * @returns {BigInteger} */ _endAddress() { return new jsbn_1.BigInteger(this.mask() + '1'.repeat(constants.BITS - this.subnetMask), 2); } /** * The last address in the range given by this address' subnet * Often referred to as the Broadcast * @memberof Address4 * @instance * @returns {Address4} */ endAddress() { return Address4.fromBigInteger(this._endAddress()); } /** * The last host address in the range given by this address's subnet ie * the last address prior to the Broadcast Address * @memberof Address4 * @instance * @returns {Address4} */ endAddressExclusive() { const adjust = new jsbn_1.BigInteger('1'); return Address4.fromBigInteger(this._endAddress().subtract(adjust)); } /** * Converts a BigInteger to a v4 address object * @memberof Address4 * @static * @param {BigInteger} bigInteger - a BigInteger to convert * @returns {Address4} */ static fromBigInteger(bigInteger) { return Address4.fromInteger(parseInt(bigInteger.toString(), 10)); } /** * Returns the first n bits of the address, defaulting to the * subnet mask * @memberof Address4 * @instance * @returns {String} */ mask(mask) { if (mask === undefined) { mask = this.subnetMask; } return this.getBitsBase2(0, mask); } /** * Returns the bits in the given range as a base-2 string * @memberof Address4 * @instance * @returns {string} */ getBitsBase2(start, end) { return this.binaryZeroPad().slice(start, end); } /** * Return the reversed ip6.arpa form of the address * @memberof Address4 * @param {Object} options * @param {boolean} options.omitSuffix - omit the "in-addr.arpa" suffix * @instance * @returns {String} */ reverseForm(options) { if (!options) { options = {}; } const reversed = this.correctForm().split('.').reverse().join('.'); if (options.omitSuffix) { return reversed; } return (0, sprintf_js_1.sprintf)('%s.in-addr.arpa.', reversed); } /** * Returns true if the given address is a multicast address * @memberof Address4 * @instance * @returns {boolean} */ isMulticast() { return this.isInSubnet(new Address4('224.0.0.0/4')); } /** * Returns a zero-padded base-2 string representation of the address * @memberof Address4 * @instance * @returns {string} */ binaryZeroPad() { return this.bigInteger().toString(2).padStart(constants.BITS, '0'); } /** * Groups an IPv4 address for inclusion at the end of an IPv6 address * @returns {String} */ groupForV6() { const segments = this.parsedAddress; return this.address.replace(constants.RE_ADDRESS, (0, sprintf_js_1.sprintf)('%s.%s', segments.slice(0, 2).join('.'), segments.slice(2, 4).join('.'))); } } exports.Address4 = Address4; //# sourceMappingURL=ipv4.js.mapPK ~\_Ż)ip-address/dist/v6/regular-expressions.jsnu["use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.possibleElisions = exports.simpleRegularExpression = exports.ADDRESS_BOUNDARY = exports.padGroup = exports.groupPossibilities = void 0; const v6 = __importStar(require("./constants")); const sprintf_js_1 = require("sprintf-js"); function groupPossibilities(possibilities) { return (0, sprintf_js_1.sprintf)('(%s)', possibilities.join('|')); } exports.groupPossibilities = groupPossibilities; function padGroup(group) { if (group.length < 4) { return (0, sprintf_js_1.sprintf)('0{0,%d}%s', 4 - group.length, group); } return group; } exports.padGroup = padGroup; exports.ADDRESS_BOUNDARY = '[^A-Fa-f0-9:]'; function simpleRegularExpression(groups) { const zeroIndexes = []; groups.forEach((group, i) => { const groupInteger = parseInt(group, 16); if (groupInteger === 0) { zeroIndexes.push(i); } }); // You can technically elide a single 0, this creates the regular expressions // to match that eventuality const possibilities = zeroIndexes.map((zeroIndex) => groups .map((group, i) => { if (i === zeroIndex) { const elision = i === 0 || i === v6.GROUPS - 1 ? ':' : ''; return groupPossibilities([padGroup(group), elision]); } return padGroup(group); }) .join(':')); // The simplest case possibilities.push(groups.map(padGroup).join(':')); return groupPossibilities(possibilities); } exports.simpleRegularExpression = simpleRegularExpression; function possibleElisions(elidedGroups, moreLeft, moreRight) { const left = moreLeft ? '' : ':'; const right = moreRight ? '' : ':'; const possibilities = []; // 1. elision of everything (::) if (!moreLeft && !moreRight) { possibilities.push('::'); } // 2. complete elision of the middle if (moreLeft && moreRight) { possibilities.push(''); } if ((moreRight && !moreLeft) || (!moreRight && moreLeft)) { // 3. complete elision of one side possibilities.push(':'); } // 4. elision from the left side possibilities.push((0, sprintf_js_1.sprintf)('%s(:0{1,4}){1,%d}', left, elidedGroups - 1)); // 5. elision from the right side possibilities.push((0, sprintf_js_1.sprintf)('(0{1,4}:){1,%d}%s', elidedGroups - 1, right)); // 6. no elision possibilities.push((0, sprintf_js_1.sprintf)('(0{1,4}:){%d}0{1,4}', elidedGroups - 1)); // 7. elision (including sloppy elision) from the middle for (let groups = 1; groups < elidedGroups - 1; groups++) { for (let position = 1; position < elidedGroups - groups; position++) { possibilities.push((0, sprintf_js_1.sprintf)('(0{1,4}:){%d}:(0{1,4}:){%d}0{1,4}', position, elidedGroups - position - groups - 1)); } } return groupPossibilities(possibilities); } exports.possibleElisions = possibleElisions; //# sourceMappingURL=regular-expressions.js.mapPK ~\> > ip-address/dist/v6/constants.jsnu["use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RE_URL_WITH_PORT = exports.RE_URL = exports.RE_ZONE_STRING = exports.RE_SUBNET_STRING = exports.RE_BAD_ADDRESS = exports.RE_BAD_CHARACTERS = exports.TYPES = exports.SCOPES = exports.GROUPS = exports.BITS = void 0; exports.BITS = 128; exports.GROUPS = 8; /** * Represents IPv6 address scopes * @memberof Address6 * @static */ exports.SCOPES = { 0: 'Reserved', 1: 'Interface local', 2: 'Link local', 4: 'Admin local', 5: 'Site local', 8: 'Organization local', 14: 'Global', 15: 'Reserved', }; /** * Represents IPv6 address types * @memberof Address6 * @static */ exports.TYPES = { 'ff01::1/128': 'Multicast (All nodes on this interface)', 'ff01::2/128': 'Multicast (All routers on this interface)', 'ff02::1/128': 'Multicast (All nodes on this link)', 'ff02::2/128': 'Multicast (All routers on this link)', 'ff05::2/128': 'Multicast (All routers in this site)', 'ff02::5/128': 'Multicast (OSPFv3 AllSPF routers)', 'ff02::6/128': 'Multicast (OSPFv3 AllDR routers)', 'ff02::9/128': 'Multicast (RIP routers)', 'ff02::a/128': 'Multicast (EIGRP routers)', 'ff02::d/128': 'Multicast (PIM routers)', 'ff02::16/128': 'Multicast (MLDv2 reports)', 'ff01::fb/128': 'Multicast (mDNSv6)', 'ff02::fb/128': 'Multicast (mDNSv6)', 'ff05::fb/128': 'Multicast (mDNSv6)', 'ff02::1:2/128': 'Multicast (All DHCP servers and relay agents on this link)', 'ff05::1:2/128': 'Multicast (All DHCP servers and relay agents in this site)', 'ff02::1:3/128': 'Multicast (All DHCP servers on this link)', 'ff05::1:3/128': 'Multicast (All DHCP servers in this site)', '::/128': 'Unspecified', '::1/128': 'Loopback', 'ff00::/8': 'Multicast', 'fe80::/10': 'Link-local unicast', }; /** * A regular expression that matches bad characters in an IPv6 address * @memberof Address6 * @static */ exports.RE_BAD_CHARACTERS = /([^0-9a-f:/%])/gi; /** * A regular expression that matches an incorrect IPv6 address * @memberof Address6 * @static */ exports.RE_BAD_ADDRESS = /([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi; /** * A regular expression that matches an IPv6 subnet * @memberof Address6 * @static */ exports.RE_SUBNET_STRING = /\/\d{1,3}(?=%|$)/; /** * A regular expression that matches an IPv6 zone * @memberof Address6 * @static */ exports.RE_ZONE_STRING = /%.*$/; exports.RE_URL = new RegExp(/^\[{0,1}([0-9a-f:]+)\]{0,1}/); exports.RE_URL_WITH_PORT = new RegExp(/\[([0-9a-f:]+)\]:([0-9]{1,5})/); //# sourceMappingURL=constants.js.mapPK ~\"$ip-address/dist/v6/helpers.jsnu["use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.simpleGroup = exports.spanLeadingZeroes = exports.spanAll = exports.spanAllZeroes = void 0; const sprintf_js_1 = require("sprintf-js"); /** * @returns {String} the string with all zeroes contained in a */ function spanAllZeroes(s) { return s.replace(/(0+)/g, '$1'); } exports.spanAllZeroes = spanAllZeroes; /** * @returns {String} the string with each character contained in a */ function spanAll(s, offset = 0) { const letters = s.split(''); return letters .map((n, i) => (0, sprintf_js_1.sprintf)('%s', n, i + offset, spanAllZeroes(n)) // XXX Use #base-2 .value-0 instead? ) .join(''); } exports.spanAll = spanAll; function spanLeadingZeroesSimple(group) { return group.replace(/^(0+)/, '$1'); } /** * @returns {String} the string with leading zeroes contained in a */ function spanLeadingZeroes(address) { const groups = address.split(':'); return groups.map((g) => spanLeadingZeroesSimple(g)).join(':'); } exports.spanLeadingZeroes = spanLeadingZeroes; /** * Groups an address * @returns {String} a grouped address */ function simpleGroup(addressString, offset = 0) { const groups = addressString.split(':'); return groups.map((g, i) => { if (/group-v4/.test(g)) { return g; } return (0, sprintf_js_1.sprintf)('%s', i + offset, spanLeadingZeroesSimple(g)); }); } exports.simpleGroup = simpleGroup; //# sourceMappingURL=helpers.js.mapPK ~\qq<ip-address/dist/common.jsnu["use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isCorrect = exports.isInSubnet = void 0; function isInSubnet(address) { if (this.subnetMask < address.subnetMask) { return false; } if (this.mask(address.subnetMask) === address.mask()) { return true; } return false; } exports.isInSubnet = isInSubnet; function isCorrect(defaultBits) { return function () { if (this.addressMinusSuffix !== this.correctForm()) { return false; } if (this.subnetMask === defaultBits && !this.parsedSubnet) { return true; } return this.parsedSubnet === String(this.subnetMask); }; } exports.isCorrect = isCorrect; //# sourceMappingURL=common.js.mapPK ~\K9 ip-address/dist/address-error.jsnu["use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AddressError = void 0; class AddressError extends Error { constructor(message, parseMessage) { super(message); this.name = 'AddressError'; if (parseMessage !== null) { this.parseMessage = parseMessage; } } } exports.AddressError = AddressError; //# sourceMappingURL=address-error.js.mapPK ~\t'22treeverse/package.jsonnu[{ "_id": "treeverse@3.0.0", "_inBundle": true, "_location": "/npm/treeverse", "_phantomChildren": {}, "_requiredBy": [ "/npm", "/npm/@npmcli/arborist" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/treeverse/issues" }, "description": "Walk any kind of tree structure depth- or breadth-first. Supports promises and advanced map-reduce operations with a very small API.", "devDependencies": { "@npmcli/eslint-config": "^3.0.1", "@npmcli/template-oss": "4.5.1", "tap": "^16.0.1" }, "engines": { "node": "^14.17.0 || ^16.13.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/treeverse#readme", "keywords": [ "tree", "traversal", "depth first search", "breadth first search" ], "license": "ISC", "main": "lib/index.js", "name": "treeverse", "repository": { "type": "git", "url": "git+https://github.com/npm/treeverse.git" }, "scripts": { "lint": "eslint \"**/*.js\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "100": true, "coverage-map": "test/coverage-map.js", "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.5.1" }, "version": "3.0.0" } PK ~\SYYtreeverse/lib/index.jsnu[module.exports = { breadth: require('./breadth.js'), depth: require('./depth.js'), } PK ~\"W88treeverse/lib/depth.jsnu[// Perform a depth-first walk of a tree. // // `visit(node)` is called when the node is first encountered. // `leave(node, children)` is called when all of the node's children // have been left or (in the case of cyclic graphs) visited. // // Only one of visit or leave is required. (Technically both are optional, // but if you don't provide at least one, the tree is just walked without // doing anything, which is a bit pointless.) If visit is provided, and // leave is not, then this is a root->leaf traversal. If leave is provided, // and visit is not, then it's leaf->root. Both can be provided for a // map-reduce operation. // // If either visit or leave return a Promise for any node, then the // walk returns a Promise. const depthDescent = require('./depth-descent.js') const depth = ({ visit, leave, filter = () => true, seen = new Map(), getChildren, tree, }) => { if (!leave) { return depthDescent({ visit, filter, getChildren, tree }) } if (seen.has(tree)) { return seen.get(tree) } seen.set(tree, null) const visitNode = () => { const res = visit ? visit(tree) : tree if (isPromise(res)) { const fullResult = res.then(resThen => { seen.set(tree, resThen) return kidNodes() }) seen.set(tree, fullResult) return fullResult } else { seen.set(tree, res) return kidNodes() } } const kidNodes = () => { const kids = getChildren(tree, seen.get(tree)) return isPromise(kids) ? kids.then(processKids) : processKids(kids) } const processKids = nodes => { const kids = (nodes || []).filter(filter).map(kid => depth({ visit, leave, filter, seen, getChildren, tree: kid })) return kids.some(isPromise) ? Promise.all(kids).then(leaveNode) : leaveNode(kids) } const leaveNode = kids => { const res = leave(seen.get(tree), kids) seen.set(tree, res) // if it's a promise at this point, the caller deals with it return res } return visitNode() } const isPromise = p => p && typeof p.then === 'function' module.exports = depth PK ~\n  treeverse/lib/breadth.jsnu[// Perform a breadth-first walk of a tree, either logical or physical // This one only visits, it doesn't leave. That's because // in a breadth-first traversal, children may be visited long // after their parent, so the "exit" pass ends up being just // another breadth-first walk. // // Breadth-first traversals are good for either creating a tree (ie, // reifying a dep graph based on a package.json without a node_modules // or package-lock), or mutating it in-place. For a map-reduce type of // walk, it doesn't make a lot of sense, and is very expensive. const breadth = ({ visit, filter = () => true, getChildren, tree, }) => { const queue = [] const seen = new Map() const next = () => { while (queue.length) { const node = queue.shift() const res = visitNode(node) if (isPromise(res)) { return res.then(() => next()) } } return seen.get(tree) } const visitNode = (visitTree) => { if (seen.has(visitTree)) { return seen.get(visitTree) } seen.set(visitTree, null) const res = visit ? visit(visitTree) : visitTree if (isPromise(res)) { const fullResult = res.then(resThen => { seen.set(visitTree, resThen) return kidNodes(visitTree) }) seen.set(visitTree, fullResult) return fullResult } else { seen.set(visitTree, res) return kidNodes(visitTree) } } const kidNodes = (kidTree) => { const kids = getChildren(kidTree, seen.get(kidTree)) return isPromise(kids) ? kids.then(processKids) : processKids(kids) } const processKids = (kids) => { kids = (kids || []).filter(filter) queue.push(...kids) } queue.push(tree) return next() } const isPromise = p => p && typeof p.then === 'function' module.exports = breadth PK ~\=treeverse/lib/depth-descent.jsnu[// Perform a depth-first walk of a tree, ONLY doing the descent (visit) // // This uses a stack rather than recursion, so that it can handle deeply // nested trees without call stack overflows. (My kingdom for proper TCO!) // // This is only used for cases where leave() is not specified. // // a // +-- b // | +-- 1 // | +-- 2 // +-- c // +-- 3 // +-- 4 // // Expect: // visit a // visit b // visit 1 // visit 2 // visit c // visit 3 // visit 4 // // stack.push(tree) // while stack not empty // pop T from stack // VISIT(T) // get children C of T // push each C onto stack const depth = ({ visit, filter, getChildren, tree, }) => { const stack = [] const seen = new Map() const next = () => { while (stack.length) { const node = stack.pop() const res = visitNode(node) if (isPromise(res)) { return res.then(() => next()) } } return seen.get(tree) } const visitNode = (visitTree) => { if (seen.has(visitTree)) { return seen.get(visitTree) } seen.set(visitTree, null) const res = visit ? visit(visitTree) : visitTree if (isPromise(res)) { const fullResult = res.then(resThen => { seen.set(visitTree, resThen) return kidNodes(visitTree) }) seen.set(visitTree, fullResult) return fullResult } else { seen.set(visitTree, res) return kidNodes(visitTree) } } const kidNodes = (kidTree) => { const kids = getChildren(kidTree, seen.get(kidTree)) return isPromise(kids) ? kids.then(processKids) : processKids(kids) } const processKids = (kids) => { kids = (kids || []).filter(filter) stack.push(...kids) } stack.push(tree) return next() } const isPromise = p => p && typeof p.then === 'function' module.exports = depth PK ~\!treeverse/LICENSEnu[The ISC License Copyright (c) npm, Inc. and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\髃npm-registry-fetch/package.jsonnu[{ "_id": "npm-registry-fetch@17.0.1", "_inBundle": true, "_location": "/npm/npm-registry-fetch", "_phantomChildren": {}, "_requiredBy": [ "/npm", "/npm/@npmcli/arborist", "/npm/libnpmaccess", "/npm/libnpmhook", "/npm/libnpmorg", "/npm/libnpmpublish", "/npm/libnpmsearch", "/npm/libnpmteam", "/npm/npm-profile", "/npm/pacote" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/npm-registry-fetch/issues" }, "dependencies": { "@npmcli/redact": "^2.0.0", "make-fetch-happen": "^13.0.0", "minipass": "^7.0.2", "minipass-fetch": "^3.0.0", "minipass-json-stream": "^1.0.1", "minizlib": "^2.1.2", "npm-package-arg": "^11.0.0", "proc-log": "^4.0.0" }, "description": "Fetch-based http client for use with npm registry APIs", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.21.4", "cacache": "^18.0.0", "nock": "^13.2.4", "require-inject": "^1.4.4", "ssri": "^10.0.0", "tap": "^16.0.1" }, "engines": { "node": "^16.14.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/npm-registry-fetch#readme", "keywords": [ "npm", "registry", "fetch" ], "license": "ISC", "main": "lib", "name": "npm-registry-fetch", "repository": { "type": "git", "url": "git+https://github.com/npm/npm-registry-fetch.git" }, "scripts": { "eslint": "eslint", "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "npmclilint": "npmcli-lint", "postlint": "template-oss-check", "postsnap": "npm run lintfix --", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "check-coverage": true, "test-ignore": "test[\\\\/](util|cache)[\\\\/]", "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.21.4", "publish": "true" }, "version": "17.0.1" } PK ~\.-˂&npm-registry-fetch/lib/default-opts.jsnu[const pkg = require('../package.json') module.exports = { maxSockets: 12, method: 'GET', registry: 'https://registry.npmjs.org/', timeout: 5 * 60 * 1000, // 5 minutes strictSSL: true, noProxy: process.env.NOPROXY, userAgent: `${pkg.name }@${ pkg.version }/node@${ process.version }+${ process.arch } (${ process.platform })`, } PK ~\u (npm-registry-fetch/lib/check-response.jsnu['use strict' const errors = require('./errors.js') const { Response } = require('minipass-fetch') const defaultOpts = require('./default-opts.js') const { log } = require('proc-log') const { redact: cleanUrl } = require('@npmcli/redact') /* eslint-disable-next-line max-len */ const moreInfoUrl = 'https://github.com/npm/cli/wiki/No-auth-for-URI,-but-auth-present-for-scoped-registry' const checkResponse = async ({ method, uri, res, startTime, auth, opts }) => { opts = { ...defaultOpts, ...opts } if (res.headers.has('npm-notice') && !res.headers.has('x-local-cache')) { log.notice('', res.headers.get('npm-notice')) } if (res.status >= 400) { logRequest(method, res, startTime) if (auth && auth.scopeAuthKey && !auth.token && !auth.auth) { // we didn't have auth for THIS request, but we do have auth for // requests to the registry indicated by the spec's scope value. // Warn the user. log.warn('registry', `No auth for URI, but auth present for scoped registry. URI: ${uri} Scoped Registry Key: ${auth.scopeAuthKey} More info here: ${moreInfoUrl}`) } return checkErrors(method, res, startTime, opts) } else { res.body.on('end', () => logRequest(method, res, startTime, opts)) if (opts.ignoreBody) { res.body.resume() return new Response(null, res) } return res } } module.exports = checkResponse function logRequest (method, res, startTime) { const elapsedTime = Date.now() - startTime const attempt = res.headers.get('x-fetch-attempts') const attemptStr = attempt && attempt > 1 ? ` attempt #${attempt}` : '' const cacheStatus = res.headers.get('x-local-cache-status') const cacheStr = cacheStatus ? ` (cache ${cacheStatus})` : '' const urlStr = cleanUrl(res.url) log.http( 'fetch', `${method.toUpperCase()} ${res.status} ${urlStr} ${elapsedTime}ms${attemptStr}${cacheStr}` ) } function checkErrors (method, res, startTime, opts) { return res.buffer() .catch(() => null) .then(body => { let parsed = body try { parsed = JSON.parse(body.toString('utf8')) } catch { // ignore errors } if (res.status === 401 && res.headers.get('www-authenticate')) { const auth = res.headers.get('www-authenticate') .split(/,\s*/) .map(s => s.toLowerCase()) if (auth.indexOf('ipaddress') !== -1) { throw new errors.HttpErrorAuthIPAddress( method, res, parsed, opts.spec ) } else if (auth.indexOf('otp') !== -1) { throw new errors.HttpErrorAuthOTP( method, res, parsed, opts.spec ) } else { throw new errors.HttpErrorAuthUnknown( method, res, parsed, opts.spec ) } } else if ( res.status === 401 && body != null && /one-time pass/.test(body.toString('utf8')) ) { // Heuristic for malformed OTP responses that don't include the // www-authenticate header. throw new errors.HttpErrorAuthOTP( method, res, parsed, opts.spec ) } else { throw new errors.HttpErrorGeneral( method, res, parsed, opts.spec ) } }) } PK ~\60npm-registry-fetch/lib/index.jsnu['use strict' const { HttpErrorAuthOTP } = require('./errors.js') const checkResponse = require('./check-response.js') const getAuth = require('./auth.js') const fetch = require('make-fetch-happen') const JSONStream = require('minipass-json-stream') const npa = require('npm-package-arg') const qs = require('querystring') const url = require('url') const zlib = require('minizlib') const { Minipass } = require('minipass') const defaultOpts = require('./default-opts.js') // WhatWG URL throws if it's not fully resolved const urlIsValid = u => { try { return !!new url.URL(u) } catch (_) { return false } } module.exports = regFetch function regFetch (uri, /* istanbul ignore next */ opts_ = {}) { const opts = { ...defaultOpts, ...opts_, } // if we did not get a fully qualified URI, then we look at the registry // config or relevant scope to resolve it. const uriValid = urlIsValid(uri) let registry = opts.registry || defaultOpts.registry if (!uriValid) { registry = opts.registry = ( (opts.spec && pickRegistry(opts.spec, opts)) || opts.registry || registry ) uri = `${ registry.trim().replace(/\/?$/g, '') }/${ uri.trim().replace(/^\//, '') }` // asserts that this is now valid new url.URL(uri) } const method = opts.method || 'GET' // through that takes into account the scope, the prefix of `uri`, etc const startTime = Date.now() const auth = getAuth(uri, opts) const headers = getHeaders(uri, auth, opts) let body = opts.body const bodyIsStream = Minipass.isStream(body) const bodyIsPromise = body && typeof body === 'object' && typeof body.then === 'function' if ( body && !bodyIsStream && !bodyIsPromise && typeof body !== 'string' && !Buffer.isBuffer(body) ) { headers['content-type'] = headers['content-type'] || 'application/json' body = JSON.stringify(body) } else if (body && !headers['content-type']) { headers['content-type'] = 'application/octet-stream' } if (opts.gzip) { headers['content-encoding'] = 'gzip' if (bodyIsStream) { const gz = new zlib.Gzip() body.on('error', /* istanbul ignore next: unlikely and hard to test */ err => gz.emit('error', err)) body = body.pipe(gz) } else if (!bodyIsPromise) { body = new zlib.Gzip().end(body).concat() } } const parsed = new url.URL(uri) if (opts.query) { const q = typeof opts.query === 'string' ? qs.parse(opts.query) : opts.query Object.keys(q).forEach(key => { if (q[key] !== undefined) { parsed.searchParams.set(key, q[key]) } }) uri = url.format(parsed) } if (parsed.searchParams.get('write') === 'true' && method === 'GET') { // do not cache, because this GET is fetching a rev that will be // used for a subsequent PUT or DELETE, so we need to conditionally // update cache. opts.offline = false opts.preferOffline = false opts.preferOnline = true } const doFetch = async fetchBody => { const p = fetch(uri, { agent: opts.agent, algorithms: opts.algorithms, body: fetchBody, cache: getCacheMode(opts), cachePath: opts.cache, ca: opts.ca, cert: auth.cert || opts.cert, headers, integrity: opts.integrity, key: auth.key || opts.key, localAddress: opts.localAddress, maxSockets: opts.maxSockets, memoize: opts.memoize, method: method, noProxy: opts.noProxy, proxy: opts.httpsProxy || opts.proxy, retry: opts.retry ? opts.retry : { retries: opts.fetchRetries, factor: opts.fetchRetryFactor, minTimeout: opts.fetchRetryMintimeout, maxTimeout: opts.fetchRetryMaxtimeout, }, strictSSL: opts.strictSSL, timeout: opts.timeout || 30 * 1000, }).then(res => checkResponse({ method, uri, res, registry, startTime, auth, opts, })) if (typeof opts.otpPrompt === 'function') { return p.catch(async er => { if (er instanceof HttpErrorAuthOTP) { let otp // if otp fails to complete, we fail with that failure try { otp = await opts.otpPrompt() } catch (_) { // ignore this error } // if no otp provided, or otpPrompt errored, throw the original HTTP error if (!otp) { throw er } return regFetch(uri, { ...opts, otp }) } throw er }) } else { return p } } return Promise.resolve(body).then(doFetch) } module.exports.getAuth = getAuth module.exports.json = fetchJSON function fetchJSON (uri, opts) { return regFetch(uri, opts).then(res => res.json()) } module.exports.json.stream = fetchJSONStream function fetchJSONStream (uri, jsonPath, /* istanbul ignore next */ opts_ = {}) { const opts = { ...defaultOpts, ...opts_ } const parser = JSONStream.parse(jsonPath, opts.mapJSON) regFetch(uri, opts).then(res => res.body.on('error', /* istanbul ignore next: unlikely and difficult to test */ er => parser.emit('error', er)).pipe(parser) ).catch(er => parser.emit('error', er)) return parser } module.exports.pickRegistry = pickRegistry function pickRegistry (spec, opts = {}) { spec = npa(spec) let registry = spec.scope && opts[spec.scope.replace(/^@?/, '@') + ':registry'] if (!registry && opts.scope) { registry = opts[opts.scope.replace(/^@?/, '@') + ':registry'] } if (!registry) { registry = opts.registry || defaultOpts.registry } return registry } function getCacheMode (opts) { return opts.offline ? 'only-if-cached' : opts.preferOffline ? 'force-cache' : opts.preferOnline ? 'no-cache' : 'default' } function getHeaders (uri, auth, opts) { const headers = Object.assign({ 'user-agent': opts.userAgent, }, opts.headers || {}) if (opts.authType) { headers['npm-auth-type'] = opts.authType } if (opts.scope) { headers['npm-scope'] = opts.scope } if (opts.npmSession) { headers['npm-session'] = opts.npmSession } if (opts.npmCommand) { headers['npm-command'] = opts.npmCommand } // If a tarball is hosted on a different place than the manifest, only send // credentials on `alwaysAuth` if (auth.token) { headers.authorization = `Bearer ${auth.token}` } else if (auth.auth) { headers.authorization = `Basic ${auth.auth}` } if (opts.otp) { headers['npm-otp'] = opts.otp } return headers } PK ~\Ho} npm-registry-fetch/lib/errors.jsnu['use strict' const { URL } = require('node:url') function packageName (href) { try { let basePath = new URL(href).pathname.slice(1) if (!basePath.match(/^-/)) { basePath = basePath.split('/') var index = basePath.indexOf('_rewrite') if (index === -1) { index = basePath.length - 1 } else { index++ } return decodeURIComponent(basePath[index]) } } catch { // this is ok } } class HttpErrorBase extends Error { constructor (method, res, body, spec) { super() this.name = this.constructor.name this.headers = typeof res.headers?.raw === 'function' ? res.headers.raw() : res.headers this.statusCode = res.status this.code = `E${res.status}` this.method = method this.uri = res.url this.body = body this.pkgid = spec ? spec.toString() : packageName(res.url) Error.captureStackTrace(this, this.constructor) } } class HttpErrorGeneral extends HttpErrorBase { constructor (method, res, body, spec) { super(method, res, body, spec) this.message = `${res.status} ${res.statusText} - ${ this.method.toUpperCase() } ${ this.spec || this.uri }${ (body && body.error) ? ' - ' + body.error : '' }` } } class HttpErrorAuthOTP extends HttpErrorBase { constructor (method, res, body, spec) { super(method, res, body, spec) this.message = 'OTP required for authentication' this.code = 'EOTP' } } class HttpErrorAuthIPAddress extends HttpErrorBase { constructor (method, res, body, spec) { super(method, res, body, spec) this.message = 'Login is not allowed from your IP address' this.code = 'EAUTHIP' } } class HttpErrorAuthUnknown extends HttpErrorBase { constructor (method, res, body, spec) { super(method, res, body, spec) this.message = 'Unable to authenticate, need: ' + res.headers.get('www-authenticate') } } module.exports = { HttpErrorBase, HttpErrorGeneral, HttpErrorAuthOTP, HttpErrorAuthIPAddress, HttpErrorAuthUnknown, } PK ~\knpm-registry-fetch/lib/auth.jsnu['use strict' const fs = require('fs') const npa = require('npm-package-arg') const { URL } = require('url') // Find the longest registry key that is used for some kind of auth // in the options. Returns the registry key and the auth config. const regFromURI = (uri, opts) => { const parsed = new URL(uri) // try to find a config key indicating we have auth for this registry // can be one of :_authToken, :_auth, :_password and :username, or // :certfile and :keyfile // We walk up the "path" until we're left with just //[:], // stopping when we reach '//'. let regKey = `//${parsed.host}${parsed.pathname}` while (regKey.length > '//'.length) { const authKey = hasAuth(regKey, opts) // got some auth for this URI if (authKey) { return { regKey, authKey } } // can be either //host/some/path/:_auth or //host/some/path:_auth // walk up by removing EITHER what's after the slash OR the slash itself regKey = regKey.replace(/([^/]+|\/)$/, '') } return { regKey: false, authKey: null } } // Not only do we want to know if there is auth, but if we are calling `npm // logout` we want to know what config value specifically provided it. This is // so we can look up where the config came from to delete it (i.e. user vs // project) const hasAuth = (regKey, opts) => { if (opts[`${regKey}:_authToken`]) { return '_authToken' } if (opts[`${regKey}:_auth`]) { return '_auth' } if (opts[`${regKey}:username`] && opts[`${regKey}:_password`]) { // 'password' can be inferred to also be present return 'username' } if (opts[`${regKey}:certfile`] && opts[`${regKey}:keyfile`]) { // 'keyfile' can be inferred to also be present return 'certfile' } return false } const sameHost = (a, b) => { const parsedA = new URL(a) const parsedB = new URL(b) return parsedA.host === parsedB.host } const getRegistry = opts => { const { spec } = opts const { scope: specScope, subSpec } = spec ? npa(spec) : {} const subSpecScope = subSpec && subSpec.scope const scope = subSpec ? subSpecScope : specScope const scopeReg = scope && opts[`${scope}:registry`] return scopeReg || opts.registry } const maybeReadFile = file => { try { return fs.readFileSync(file, 'utf8') } catch (er) { if (er.code !== 'ENOENT') { throw er } return null } } const getAuth = (uri, opts = {}) => { const { forceAuth } = opts if (!uri) { throw new Error('URI is required') } const { regKey, authKey } = regFromURI(uri, forceAuth || opts) // we are only allowed to use what's in forceAuth if specified if (forceAuth && !regKey) { return new Auth({ // if we force auth we don't want to refer back to anything in config regKey: false, authKey: null, scopeAuthKey: null, token: forceAuth._authToken || forceAuth.token, username: forceAuth.username, password: forceAuth._password || forceAuth.password, auth: forceAuth._auth || forceAuth.auth, certfile: forceAuth.certfile, keyfile: forceAuth.keyfile, }) } // no auth for this URI, but might have it for the registry if (!regKey) { const registry = getRegistry(opts) if (registry && uri !== registry && sameHost(uri, registry)) { return getAuth(registry, opts) } else if (registry !== opts.registry) { // If making a tarball request to a different base URI than the // registry where we logged in, but the same auth SHOULD be sent // to that artifact host, then we track where it was coming in from, // and warn the user if we get a 4xx error on it. const { regKey: scopeAuthKey, authKey: _authKey } = regFromURI(registry, opts) return new Auth({ scopeAuthKey, regKey: scopeAuthKey, authKey: _authKey }) } } const { [`${regKey}:_authToken`]: token, [`${regKey}:username`]: username, [`${regKey}:_password`]: password, [`${regKey}:_auth`]: auth, [`${regKey}:certfile`]: certfile, [`${regKey}:keyfile`]: keyfile, } = opts return new Auth({ scopeAuthKey: null, regKey, authKey, token, auth, username, password, certfile, keyfile, }) } class Auth { constructor ({ token, auth, username, password, scopeAuthKey, certfile, keyfile, regKey, authKey, }) { // same as regKey but only present for scoped auth. Should have been named scopeRegKey this.scopeAuthKey = scopeAuthKey // `${regKey}:${authKey}` will get you back to the auth config that gave us auth this.regKey = regKey this.authKey = authKey this.token = null this.auth = null this.isBasicAuth = false this.cert = null this.key = null if (token) { this.token = token } else if (auth) { this.auth = auth } else if (username && password) { const p = Buffer.from(password, 'base64').toString('utf8') this.auth = Buffer.from(`${username}:${p}`, 'utf8').toString('base64') this.isBasicAuth = true } // mTLS may be used in conjunction with another auth method above if (certfile && keyfile) { const cert = maybeReadFile(certfile, 'utf-8') const key = maybeReadFile(keyfile, 'utf-8') if (cert && key) { this.cert = cert this.key = key } } } } module.exports = getAuth PK ~\rnpm-registry-fetch/LICENSE.mdnu[ ISC License Copyright npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND NPM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NPM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\l% % semver/package.jsonnu[{ "_id": "semver@7.6.2", "_inBundle": true, "_location": "/npm/semver", "_phantomChildren": {}, "_requiredBy": [ "/npm", "/npm/@npmcli/arborist", "/npm/@npmcli/config", "/npm/@npmcli/fs", "/npm/@npmcli/git", "/npm/@npmcli/metavuln-calculator", "/npm/@npmcli/package-json", "/npm/init-package-json", "/npm/libnpmexec", "/npm/libnpmpublish", "/npm/libnpmversion", "/npm/node-gyp", "/npm/normalize-package-data", "/npm/npm-install-checks", "/npm/npm-package-arg", "/npm/npm-pick-manifest" ], "author": { "name": "GitHub Inc." }, "bin": { "semver": "bin/semver.js" }, "bugs": { "url": "https://github.com/npm/node-semver/issues" }, "description": "The semantic version parser used by npm.", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.22.0", "benchmark": "^2.1.4", "tap": "^16.0.0" }, "engines": { "node": ">=10" }, "files": [ "bin/", "lib/", "classes/", "functions/", "internal/", "ranges/", "index.js", "preload.js", "range.bnf" ], "homepage": "https://github.com/npm/node-semver#readme", "license": "ISC", "main": "index.js", "name": "semver", "repository": { "type": "git", "url": "git+https://github.com/npm/node-semver.git" }, "scripts": { "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "timeout": 30, "coverage-map": "map.js", "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.22.0", "engines": ">=10", "distPaths": [ "classes/", "functions/", "internal/", "ranges/", "index.js", "preload.js", "range.bnf" ], "allowPaths": [ "/classes/", "/functions/", "/internal/", "/ranges/", "/index.js", "/preload.js", "/range.bnf", "/benchmarks" ], "publish": "true" }, "version": "7.6.2" } PK ~\D#EEsemver/preload.jsnu[// XXX remove in v8 or beyond module.exports = require('./index.js') PK ~\nDD semver/internal/parse-options.jsnu[// parse out just the options we care about const looseOption = Object.freeze({ loose: true }) const emptyOpts = Object.freeze({ }) const parseOptions = options => { if (!options) { return emptyOpts } if (typeof options !== 'object') { return looseOption } return options } module.exports = parseOptions PK ~\? Asemver/internal/lrucache.jsnu[class LRUCache { constructor () { this.max = 1000 this.map = new Map() } get (key) { const value = this.map.get(key) if (value === undefined) { return undefined } else { // Remove the key from the map and add it to the end this.map.delete(key) this.map.set(key, value) return value } } delete (key) { return this.map.delete(key) } set (key, value) { const deleted = this.delete(key) if (!deleted && value !== undefined) { // If cache is full, delete the least recently used item if (this.map.size >= this.max) { const firstKey = this.map.keys().next().value this.delete(firstKey) } this.map.set(key, value) } return this } } module.exports = LRUCache PK ~\semver/internal/identifiers.jsnu[const numeric = /^[0-9]+$/ const compareIdentifiers = (a, b) => { const anum = numeric.test(a) const bnum = numeric.test(b) if (anum && bnum) { a = +a b = +b } return a === b ? 0 : (anum && !bnum) ? -1 : (bnum && !anum) ? 1 : a < b ? -1 : 1 } const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) module.exports = { compareIdentifiers, rcompareIdentifiers, } PK ~\$Lsemver/internal/re.jsnu[const { MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_LENGTH, } = require('./constants') const debug = require('./debug') exports = module.exports = {} // The actual regexps go on exports.re const re = exports.re = [] const safeRe = exports.safeRe = [] const src = exports.src = [] const t = exports.t = {} let R = 0 const LETTERDASHNUMBER = '[a-zA-Z0-9-]' // Replace some greedy regex tokens to prevent regex dos issues. These regex are // used internally via the safeRe object since all inputs in this library get // normalized first to trim and collapse all extra whitespace. The original // regexes are exported for userland consumption and lower level usage. A // future breaking change could export the safer regex only with a note that // all input should have extra whitespace removed. const safeRegexReplacements = [ ['\\s', 1], ['\\d', MAX_LENGTH], [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], ] const makeSafeRegex = (value) => { for (const [token, max] of safeRegexReplacements) { value = value .split(`${token}*`).join(`${token}{0,${max}}`) .split(`${token}+`).join(`${token}{1,${max}}`) } return value } const createToken = (name, value, isGlobal) => { const safe = makeSafeRegex(value) const index = R++ debug(name, index, value) t[name] = index src[index] = value re[index] = new RegExp(value, isGlobal ? 'g' : undefined) safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) } // The following Regular Expressions can be used for tokenizing, // validating, and parsing SemVer version strings. // ## Numeric Identifier // A single `0`, or a non-zero digit followed by zero or more digits. createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') createToken('NUMERICIDENTIFIERLOOSE', '\\d+') // ## Non-numeric Identifier // Zero or more digits, followed by a letter or hyphen, and then zero or // more letters, digits, or hyphens. createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) // ## Main Version // Three dot-separated numeric identifiers. createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})`) createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] }|${src[t.NONNUMERICIDENTIFIER]})`) createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] }|${src[t.NONNUMERICIDENTIFIER]})`) // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version // identifiers. createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] }(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] }(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) // ## Build Metadata Identifier // Any combination of digits, letters, or hyphens. createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) // ## Build Metadata // Plus sign, followed by one or more period-separated build metadata // identifiers. createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] }(?:\\.${src[t.BUILDIDENTIFIER]})*))`) // ## Full Version String // A main version, followed optionally by a pre-release version and // build metadata. // Note that the only major, minor, patch, and pre-release sections of // the version string are capturing groups. The build metadata is not a // capturing group, because it should not ever be used in version // comparison. createToken('FULLPLAIN', `v?${src[t.MAINVERSION] }${src[t.PRERELEASE]}?${ src[t.BUILD]}?`) createToken('FULL', `^${src[t.FULLPLAIN]}$`) // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty // common in the npm registry. createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] }${src[t.PRERELEASELOOSE]}?${ src[t.BUILD]}?`) createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) createToken('GTLT', '((?:<|>)?=?)') // Something like "2.*" or "1.2.x". // Note that "x.x" is a valid xRange identifer, meaning "any version" // Only the first item is strictly required. createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:${src[t.PRERELEASE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:${src[t.PRERELEASELOOSE]})?${ src[t.BUILD]}?` + `)?)?`) createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) // Coercion. // Extract anything that could conceivably be a part of a valid semver createToken('COERCEPLAIN', `${'(^|[^\\d])' + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`) createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`) createToken('COERCEFULL', src[t.COERCEPLAIN] + `(?:${src[t.PRERELEASE]})?` + `(?:${src[t.BUILD]})?` + `(?:$|[^\\d])`) createToken('COERCERTL', src[t.COERCE], true) createToken('COERCERTLFULL', src[t.COERCEFULL], true) // Tilde ranges. // Meaning is "reasonably at or greater than" createToken('LONETILDE', '(?:~>?)') createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) exports.tildeTrimReplace = '$1~' createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) // Caret ranges. // Meaning is "at least and backwards compatible with" createToken('LONECARET', '(?:\\^)') createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) exports.caretTrimReplace = '$1^' createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) // A simple gt/lt/eq thing, or just "" to indicate "any version" createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) // An expression to strip any whitespace between the gtlt and the thing // it modifies, so that `> 1.2.3` ==> `>1.2.3` createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] }\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) exports.comparatorTrimReplace = '$1$2$3' // Something like `1.2.3 - 1.2.4` // Note that these all use the loose form, because they'll be // checked against either the strict or loose comparator form // later. createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAIN]})` + `\\s*$`) createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAINLOOSE]})` + `\\s*$`) // Star ranges basically just allow anything at all. createToken('STAR', '(<|>)?=?\\s*\\*') // >=0.0.0 is like a star createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') PK ~\E9semver/internal/debug.jsnu[const debug = ( typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ) ? (...args) => console.error('SEMVER', ...args) : () => {} module.exports = debug PK ~\©[[semver/internal/constants.jsnu[// Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. const SEMVER_SPEC_VERSION = '2.0.0' const MAX_LENGTH = 256 const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991 // Max safe segment length for coercion. const MAX_SAFE_COMPONENT_LENGTH = 16 // Max safe length for a build identifier. The max length minus 6 characters for // the shortest version with a build 0.0.0+BUILD. const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 const RELEASE_TYPES = [ 'major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease', ] module.exports = { MAX_LENGTH, MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_SAFE_INTEGER, RELEASE_TYPES, SEMVER_SPEC_VERSION, FLAG_INCLUDE_PRERELEASE: 0b001, FLAG_LOOSE: 0b010, } PK ~\aGWsemver/LICENSEnu[The ISC License Copyright (c) Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\FR  semver/ranges/to-comparators.jsnu[const Range = require('../classes/range') // Mostly just for testing and legacy API reasons const toComparators = (range, options) => new Range(range, options).set .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) module.exports = toComparators PK ~\wT&semver/ranges/outside.jsnu[const SemVer = require('../classes/semver') const Comparator = require('../classes/comparator') const { ANY } = Comparator const Range = require('../classes/range') const satisfies = require('../functions/satisfies') const gt = require('../functions/gt') const lt = require('../functions/lt') const lte = require('../functions/lte') const gte = require('../functions/gte') const outside = (version, range, hilo, options) => { version = new SemVer(version, options) range = new Range(range, options) let gtfn, ltefn, ltfn, comp, ecomp switch (hilo) { case '>': gtfn = gt ltefn = lte ltfn = lt comp = '>' ecomp = '>=' break case '<': gtfn = lt ltefn = gte ltfn = gt comp = '<' ecomp = '<=' break default: throw new TypeError('Must provide a hilo val of "<" or ">"') } // If it satisfies the range it is not outside if (satisfies(version, range, options)) { return false } // From now on, variable terms are as if we're in "gtr" mode. // but note that everything is flipped for the "ltr" function. for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let high = null let low = null comparators.forEach((comparator) => { if (comparator.semver === ANY) { comparator = new Comparator('>=0.0.0') } high = high || comparator low = low || comparator if (gtfn(comparator.semver, high.semver, options)) { high = comparator } else if (ltfn(comparator.semver, low.semver, options)) { low = comparator } }) // If the edge version comparator has a operator then our version // isn't outside it if (high.operator === comp || high.operator === ecomp) { return false } // If the lowest version comparator has an operator and our version // is less than it then it isn't higher than the range if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { return false } else if (low.operator === ecomp && ltfn(version, low.semver)) { return false } } return true } module.exports = outside PK ~\fv<semver/ranges/ltr.jsnu[const outside = require('./outside') // Determine if version is less than all the versions possible in the range const ltr = (version, range, options) => outside(version, range, '<', options) module.exports = ltr PK ~\?,DCCsemver/ranges/max-satisfying.jsnu[const SemVer = require('../classes/semver') const Range = require('../classes/range') const maxSatisfying = (versions, range, options) => { let max = null let maxSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) max = v maxSV = new SemVer(max, options) } } }) return max } module.exports = maxSatisfying PK ~\BtAAsemver/ranges/min-satisfying.jsnu[const SemVer = require('../classes/semver') const Range = require('../classes/range') const minSatisfying = (versions, range, options) => { let min = null let minSV = null let rangeObj = null try { rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach((v) => { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!min || minSV.compare(v) === 1) { // compare(min, v, true) min = v minSV = new SemVer(min, options) } } }) return min } module.exports = minSatisfying PK ~\^semver/ranges/min-version.jsnu[const SemVer = require('../classes/semver') const Range = require('../classes/range') const gt = require('../functions/gt') const minVersion = (range, loose) => { range = new Range(range, loose) let minver = new SemVer('0.0.0') if (range.test(minver)) { return minver } minver = new SemVer('0.0.0-0') if (range.test(minver)) { return minver } minver = null for (let i = 0; i < range.set.length; ++i) { const comparators = range.set[i] let setMin = null comparators.forEach((comparator) => { // Clone to avoid manipulating the comparator's semver object. const compver = new SemVer(comparator.semver.version) switch (comparator.operator) { case '>': if (compver.prerelease.length === 0) { compver.patch++ } else { compver.prerelease.push(0) } compver.raw = compver.format() /* fallthrough */ case '': case '>=': if (!setMin || gt(compver, setMin)) { setMin = compver } break case '<': case '<=': /* Ignore maximum versions */ break /* istanbul ignore next */ default: throw new Error(`Unexpected operation: ${comparator.operator}`) } }) if (setMin && (!minver || gt(minver, setMin))) { minver = setMin } } if (minver && range.test(minver)) { return minver } return null } module.exports = minVersion PK ~\nQsemver/ranges/intersects.jsnu[const Range = require('../classes/range') const intersects = (r1, r2, options) => { r1 = new Range(r1, options) r2 = new Range(r2, options) return r1.intersects(r2, options) } module.exports = intersects PK ~\==semver/ranges/simplify.jsnu[// given a set of versions and a range, create a "simplified" range // that includes the same versions that the original range does // If the original range is shorter than the simplified one, return that. const satisfies = require('../functions/satisfies.js') const compare = require('../functions/compare.js') module.exports = (versions, range, options) => { const set = [] let first = null let prev = null const v = versions.sort((a, b) => compare(a, b, options)) for (const version of v) { const included = satisfies(version, range, options) if (included) { prev = version if (!first) { first = version } } else { if (prev) { set.push([first, prev]) } prev = null first = null } } if (first) { set.push([first, null]) } const ranges = [] for (const [min, max] of set) { if (min === max) { ranges.push(min) } else if (!max && min === v[0]) { ranges.push('*') } else if (!max) { ranges.push(`>=${min}`) } else if (min === v[0]) { ranges.push(`<=${max}`) } else { ranges.push(`${min} - ${max}`) } } const simplified = ranges.join(' || ') const original = typeof range.raw === 'string' ? range.raw : String(range) return simplified.length < original.length ? simplified : range } PK ~\yc:VVsemver/ranges/subset.jsnu[const Range = require('../classes/range.js') const Comparator = require('../classes/comparator.js') const { ANY } = Comparator const satisfies = require('../functions/satisfies.js') const compare = require('../functions/compare.js') // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: // - Every simple range `r1, r2, ...` is a null set, OR // - Every simple range `r1, r2, ...` which is not a null set is a subset of // some `R1, R2, ...` // // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: // - If c is only the ANY comparator // - If C is only the ANY comparator, return true // - Else if in prerelease mode, return false // - else replace c with `[>=0.0.0]` // - If C is only the ANY comparator // - if in prerelease mode, return true // - else replace C with `[>=0.0.0]` // - Let EQ be the set of = comparators in c // - If EQ is more than one, return true (null set) // - Let GT be the highest > or >= comparator in c // - Let LT be the lowest < or <= comparator in c // - If GT and LT, and GT.semver > LT.semver, return true (null set) // - If any C is a = range, and GT or LT are set, return false // - If EQ // - If GT, and EQ does not satisfy GT, return true (null set) // - If LT, and EQ does not satisfy LT, return true (null set) // - If EQ satisfies every C, return true // - Else return false // - If GT // - If GT.semver is lower than any > or >= comp in C, return false // - If GT is >=, and GT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the GT.semver tuple, return false // - If LT // - If LT.semver is greater than any < or <= comp in C, return false // - If LT is <=, and LT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the LT.semver tuple, return false // - Else return true const subset = (sub, dom, options = {}) => { if (sub === dom) { return true } sub = new Range(sub, options) dom = new Range(dom, options) let sawNonNull = false OUTER: for (const simpleSub of sub.set) { for (const simpleDom of dom.set) { const isSub = simpleSubset(simpleSub, simpleDom, options) sawNonNull = sawNonNull || isSub !== null if (isSub) { continue OUTER } } // the null set is a subset of everything, but null simple ranges in // a complex range should be ignored. so if we saw a non-null range, // then we know this isn't a subset, but if EVERY simple range was null, // then it is a subset. if (sawNonNull) { return false } } return true } const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] const minimumVersion = [new Comparator('>=0.0.0')] const simpleSubset = (sub, dom, options) => { if (sub === dom) { return true } if (sub.length === 1 && sub[0].semver === ANY) { if (dom.length === 1 && dom[0].semver === ANY) { return true } else if (options.includePrerelease) { sub = minimumVersionWithPreRelease } else { sub = minimumVersion } } if (dom.length === 1 && dom[0].semver === ANY) { if (options.includePrerelease) { return true } else { dom = minimumVersion } } const eqSet = new Set() let gt, lt for (const c of sub) { if (c.operator === '>' || c.operator === '>=') { gt = higherGT(gt, c, options) } else if (c.operator === '<' || c.operator === '<=') { lt = lowerLT(lt, c, options) } else { eqSet.add(c.semver) } } if (eqSet.size > 1) { return null } let gtltComp if (gt && lt) { gtltComp = compare(gt.semver, lt.semver, options) if (gtltComp > 0) { return null } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { return null } } // will iterate one or zero times for (const eq of eqSet) { if (gt && !satisfies(eq, String(gt), options)) { return null } if (lt && !satisfies(eq, String(lt), options)) { return null } for (const c of dom) { if (!satisfies(eq, String(c), options)) { return false } } return true } let higher, lower let hasDomLT, hasDomGT // if the subset has a prerelease, we need a comparator in the superset // with the same tuple and a prerelease, or it's not a subset let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false // exception: <1.2.3-0 is the same as <1.2.3 if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { needDomLTPre = false } for (const c of dom) { hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' if (gt) { if (needDomGTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) { needDomGTPre = false } } if (c.operator === '>' || c.operator === '>=') { higher = higherGT(gt, c, options) if (higher === c && higher !== gt) { return false } } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { return false } } if (lt) { if (needDomLTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) { needDomLTPre = false } } if (c.operator === '<' || c.operator === '<=') { lower = lowerLT(lt, c, options) if (lower === c && lower !== lt) { return false } } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { return false } } if (!c.operator && (lt || gt) && gtltComp !== 0) { return false } } // if there was a < or >, and nothing in the dom, then must be false // UNLESS it was limited by another range in the other direction. // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 if (gt && hasDomLT && !lt && gtltComp !== 0) { return false } if (lt && hasDomGT && !gt && gtltComp !== 0) { return false } // we needed a prerelease range in a specific tuple, but didn't get one // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, // because it includes prereleases in the 1.2.3 tuple if (needDomGTPre || needDomLTPre) { return false } return true } // >=1.2.3 is lower than >1.2.3 const higherGT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp > 0 ? a : comp < 0 ? b : b.operator === '>' && a.operator === '>=' ? b : a } // <=1.2.3 is higher than <1.2.3 const lowerLT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp < 0 ? a : comp > 0 ? b : b.operator === '<' && a.operator === '<=' ? b : a } module.exports = subset PK ~\88semver/ranges/valid.jsnu[const Range = require('../classes/range') const validRange = (range, options) => { try { // Return '*' instead of '' so that truthiness works. // This will throw if it's invalid anyway return new Range(range, options).range || '*' } catch (er) { return null } } module.exports = validRange PK ~\iLsemver/ranges/gtr.jsnu[// Determine if version is greater than all the versions possible in the range. const outside = require('./outside') const gtr = (version, range, options) => outside(version, range, '>', options) module.exports = gtr PK ~\G8 8 semver/index.jsnu[// just pre-load all the stuff that index.js lazily exports const internalRe = require('./internal/re') const constants = require('./internal/constants') const SemVer = require('./classes/semver') const identifiers = require('./internal/identifiers') const parse = require('./functions/parse') const valid = require('./functions/valid') const clean = require('./functions/clean') const inc = require('./functions/inc') const diff = require('./functions/diff') const major = require('./functions/major') const minor = require('./functions/minor') const patch = require('./functions/patch') const prerelease = require('./functions/prerelease') const compare = require('./functions/compare') const rcompare = require('./functions/rcompare') const compareLoose = require('./functions/compare-loose') const compareBuild = require('./functions/compare-build') const sort = require('./functions/sort') const rsort = require('./functions/rsort') const gt = require('./functions/gt') const lt = require('./functions/lt') const eq = require('./functions/eq') const neq = require('./functions/neq') const gte = require('./functions/gte') const lte = require('./functions/lte') const cmp = require('./functions/cmp') const coerce = require('./functions/coerce') const Comparator = require('./classes/comparator') const Range = require('./classes/range') const satisfies = require('./functions/satisfies') const toComparators = require('./ranges/to-comparators') const maxSatisfying = require('./ranges/max-satisfying') const minSatisfying = require('./ranges/min-satisfying') const minVersion = require('./ranges/min-version') const validRange = require('./ranges/valid') const outside = require('./ranges/outside') const gtr = require('./ranges/gtr') const ltr = require('./ranges/ltr') const intersects = require('./ranges/intersects') const simplifyRange = require('./ranges/simplify') const subset = require('./ranges/subset') module.exports = { parse, valid, clean, inc, diff, major, minor, patch, prerelease, compare, rcompare, compareLoose, compareBuild, sort, rsort, gt, lt, eq, neq, gte, lte, cmp, coerce, Comparator, Range, satisfies, toComparators, maxSatisfying, minSatisfying, minVersion, validRange, outside, gtr, ltr, intersects, simplifyRange, subset, SemVer, re: internalRe.re, src: internalRe.src, tokens: internalRe.t, SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, RELEASE_TYPES: constants.RELEASE_TYPES, compareIdentifiers: identifiers.compareIdentifiers, rcompareIdentifiers: identifiers.rcompareIdentifiers, } PK ~\buRRsemver/bin/semver.jsnu[#!/usr/bin/env node // Standalone semver comparison program. // Exits successfully and prints matching version(s) if // any supplied version is valid and passes all tests. const argv = process.argv.slice(2) let versions = [] const range = [] let inc = null const version = require('../package.json').version let loose = false let includePrerelease = false let coerce = false let rtl = false let identifier let identifierBase const semver = require('../') const parseOptions = require('../internal/parse-options') let reverse = false let options = {} const main = () => { if (!argv.length) { return help() } while (argv.length) { let a = argv.shift() const indexOfEqualSign = a.indexOf('=') if (indexOfEqualSign !== -1) { const value = a.slice(indexOfEqualSign + 1) a = a.slice(0, indexOfEqualSign) argv.unshift(value) } switch (a) { case '-rv': case '-rev': case '--rev': case '--reverse': reverse = true break case '-l': case '--loose': loose = true break case '-p': case '--include-prerelease': includePrerelease = true break case '-v': case '--version': versions.push(argv.shift()) break case '-i': case '--inc': case '--increment': switch (argv[0]) { case 'major': case 'minor': case 'patch': case 'prerelease': case 'premajor': case 'preminor': case 'prepatch': inc = argv.shift() break default: inc = 'patch' break } break case '--preid': identifier = argv.shift() break case '-r': case '--range': range.push(argv.shift()) break case '-n': identifierBase = argv.shift() if (identifierBase === 'false') { identifierBase = false } break case '-c': case '--coerce': coerce = true break case '--rtl': rtl = true break case '--ltr': rtl = false break case '-h': case '--help': case '-?': return help() default: versions.push(a) break } } options = parseOptions({ loose, includePrerelease, rtl }) versions = versions.map((v) => { return coerce ? (semver.coerce(v, options) || { version: v }).version : v }).filter((v) => { return semver.valid(v) }) if (!versions.length) { return fail() } if (inc && (versions.length !== 1 || range.length)) { return failInc() } for (let i = 0, l = range.length; i < l; i++) { versions = versions.filter((v) => { return semver.satisfies(v, range[i], options) }) if (!versions.length) { return fail() } } versions .sort((a, b) => semver[reverse ? 'rcompare' : 'compare'](a, b, options)) .map(v => semver.clean(v, options)) .map(v => inc ? semver.inc(v, inc, options, identifier, identifierBase) : v) .forEach(v => console.log(v)) } const failInc = () => { console.error('--inc can only be used on a single version with no range') fail() } const fail = () => process.exit(1) const help = () => console.log( `SemVer ${version} A JavaScript implementation of the https://semver.org/ specification Copyright Isaac Z. Schlueter Usage: semver [options] [ [...]] Prints valid versions sorted by SemVer precedence Options: -r --range Print versions that match the specified range. -i --increment [] Increment a version by the specified level. Level can be one of: major, minor, patch, premajor, preminor, prepatch, or prerelease. Default level is 'patch'. Only one version may be specified. --preid Identifier to be used to prefix premajor, preminor, prepatch or prerelease version increments. -l --loose Interpret versions and ranges loosely -p --include-prerelease Always include prerelease versions in range matching -c --coerce Coerce a string into SemVer if possible (does not imply --loose) --rtl Coerce version strings right to left --ltr Coerce version strings left to right (default) -n Base number to be used for the prerelease identifier. Can be either 0 or 1, or false to omit the number altogether. Defaults to 0. Program exits successfully if any valid version satisfies all supplied ranges, and prints all satisfying versions. If no satisfying versions are found, then exits failure. Versions are printed in ascending order, so supplying multiple versions to the utility will just sort them.`) main() PK ~\F%j_j_semver/README.mdnu[semver(1) -- The semantic versioner for npm =========================================== ## Install ```bash npm install semver ```` ## Usage As a node module: ```js const semver = require('semver') semver.valid('1.2.3') // '1.2.3' semver.valid('a.b.c') // null semver.clean(' =v1.2.3 ') // '1.2.3' semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true semver.gt('1.2.3', '9.8.7') // false semver.lt('1.2.3', '9.8.7') // true semver.minVersion('>=1.0.0') // '1.0.0' semver.valid(semver.coerce('v2')) // '2.0.0' semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' ``` You can also just load the module for the function that you care about if you'd like to minimize your footprint. ```js // load the whole API at once in a single object const semver = require('semver') // or just load the bits you need // all of them listed here, just pick and choose what you want // classes const SemVer = require('semver/classes/semver') const Comparator = require('semver/classes/comparator') const Range = require('semver/classes/range') // functions for working with versions const semverParse = require('semver/functions/parse') const semverValid = require('semver/functions/valid') const semverClean = require('semver/functions/clean') const semverInc = require('semver/functions/inc') const semverDiff = require('semver/functions/diff') const semverMajor = require('semver/functions/major') const semverMinor = require('semver/functions/minor') const semverPatch = require('semver/functions/patch') const semverPrerelease = require('semver/functions/prerelease') const semverCompare = require('semver/functions/compare') const semverRcompare = require('semver/functions/rcompare') const semverCompareLoose = require('semver/functions/compare-loose') const semverCompareBuild = require('semver/functions/compare-build') const semverSort = require('semver/functions/sort') const semverRsort = require('semver/functions/rsort') // low-level comparators between versions const semverGt = require('semver/functions/gt') const semverLt = require('semver/functions/lt') const semverEq = require('semver/functions/eq') const semverNeq = require('semver/functions/neq') const semverGte = require('semver/functions/gte') const semverLte = require('semver/functions/lte') const semverCmp = require('semver/functions/cmp') const semverCoerce = require('semver/functions/coerce') // working with ranges const semverSatisfies = require('semver/functions/satisfies') const semverMaxSatisfying = require('semver/ranges/max-satisfying') const semverMinSatisfying = require('semver/ranges/min-satisfying') const semverToComparators = require('semver/ranges/to-comparators') const semverMinVersion = require('semver/ranges/min-version') const semverValidRange = require('semver/ranges/valid') const semverOutside = require('semver/ranges/outside') const semverGtr = require('semver/ranges/gtr') const semverLtr = require('semver/ranges/ltr') const semverIntersects = require('semver/ranges/intersects') const semverSimplifyRange = require('semver/ranges/simplify') const semverRangeSubset = require('semver/ranges/subset') ``` As a command-line utility: ``` $ semver -h A JavaScript implementation of the https://semver.org/ specification Copyright Isaac Z. Schlueter Usage: semver [options] [ [...]] Prints valid versions sorted by SemVer precedence Options: -r --range Print versions that match the specified range. -i --increment [] Increment a version by the specified level. Level can be one of: major, minor, patch, premajor, preminor, prepatch, or prerelease. Default level is 'patch'. Only one version may be specified. --preid Identifier to be used to prefix premajor, preminor, prepatch or prerelease version increments. -l --loose Interpret versions and ranges loosely -n <0|1> This is the base to be used for the prerelease identifier. -p --include-prerelease Always include prerelease versions in range matching -c --coerce Coerce a string into SemVer if possible (does not imply --loose) --rtl Coerce version strings right to left --ltr Coerce version strings left to right (default) Program exits successfully if any valid version satisfies all supplied ranges, and prints all satisfying versions. If no satisfying versions are found, then exits failure. Versions are printed in ascending order, so supplying multiple versions to the utility will just sort them. ``` ## Versions A "version" is described by the `v2.0.0` specification found at . A leading `"="` or `"v"` character is stripped off and ignored. ## Ranges A `version range` is a set of `comparators` that specify versions that satisfy the range. A `comparator` is composed of an `operator` and a `version`. The set of primitive `operators` is: * `<` Less than * `<=` Less than or equal to * `>` Greater than * `>=` Greater than or equal to * `=` Equal. If no operator is specified, then equality is assumed, so this operator is optional but MAY be included. For example, the comparator `>=1.2.7` would match the versions `1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` or `1.1.0`. The comparator `>1` is equivalent to `>=2.0.0` and would match the versions `2.0.0` and `3.1.0`, but not the versions `1.0.1` or `1.1.0`. Comparators can be joined by whitespace to form a `comparator set`, which is satisfied by the **intersection** of all of the comparators it includes. A range is composed of one or more comparator sets, joined by `||`. A version matches a range if and only if every comparator in at least one of the `||`-separated comparator sets is satisfied by the version. For example, the range `>=1.2.7 <1.3.0` would match the versions `1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, or `1.1.0`. The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, `1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. ### Prerelease Tags If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then it will only be allowed to satisfy comparator sets if at least one comparator with the same `[major, minor, patch]` tuple also has a prerelease tag. For example, the range `>1.2.3-alpha.3` would be allowed to match the version `1.2.3-alpha.7`, but it would *not* be satisfied by `3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater than" `1.2.3-alpha.3` according to the SemVer sort rules. The version range only accepts prerelease tags on the `1.2.3` version. Version `3.4.5` *would* satisfy the range because it does not have a prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. The purpose of this behavior is twofold. First, prerelease versions frequently are updated very quickly, and contain many breaking changes that are (by the author's design) not yet fit for public consumption. Therefore, by default, they are excluded from range-matching semantics. Second, a user who has opted into using a prerelease version has indicated the intent to use *that specific* set of alpha/beta/rc versions. By including a prerelease tag in the range, the user is indicating that they are aware of the risk. However, it is still not appropriate to assume that they have opted into taking a similar risk on the *next* set of prerelease versions. Note that this behavior can be suppressed (treating all prerelease versions as if they were normal versions, for range-matching) by setting the `includePrerelease` flag on the options object to any [functions](https://github.com/npm/node-semver#functions) that do range matching. #### Prerelease Identifiers The method `.inc` takes an additional `identifier` string argument that will append the value of the string as a prerelease identifier: ```javascript semver.inc('1.2.3', 'prerelease', 'beta') // '1.2.4-beta.0' ``` command-line example: ```bash $ semver 1.2.3 -i prerelease --preid beta 1.2.4-beta.0 ``` Which then can be used to increment further: ```bash $ semver 1.2.4-beta.0 -i prerelease 1.2.4-beta.1 ``` #### Prerelease Identifier Base The method `.inc` takes an optional parameter 'identifierBase' string that will let you let your prerelease number as zero-based or one-based. Set to `false` to omit the prerelease number altogether. If you do not specify this parameter, it will default to zero-based. ```javascript semver.inc('1.2.3', 'prerelease', 'beta', '1') // '1.2.4-beta.1' ``` ```javascript semver.inc('1.2.3', 'prerelease', 'beta', false) // '1.2.4-beta' ``` command-line example: ```bash $ semver 1.2.3 -i prerelease --preid beta -n 1 1.2.4-beta.1 ``` ```bash $ semver 1.2.3 -i prerelease --preid beta -n false 1.2.4-beta ``` ### Advanced Range Syntax Advanced range syntax desugars to primitive comparators in deterministic ways. Advanced ranges may be combined in the same way as primitive comparators using white space or `||`. #### Hyphen Ranges `X.Y.Z - A.B.C` Specifies an inclusive set. * `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` If a partial version is provided as the first version in the inclusive range, then the missing pieces are replaced with zeroes. * `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` If a partial version is provided as the second version in the inclusive range, then all versions that start with the supplied parts of the tuple are accepted, but nothing that would be greater than the provided tuple parts. * `1.2.3 - 2.3` := `>=1.2.3 <2.4.0-0` * `1.2.3 - 2` := `>=1.2.3 <3.0.0-0` #### X-Ranges `1.2.x` `1.X` `1.2.*` `*` Any of `X`, `x`, or `*` may be used to "stand in" for one of the numeric values in the `[major, minor, patch]` tuple. * `*` := `>=0.0.0` (Any non-prerelease version satisfies, unless `includePrerelease` is specified, in which case any version at all satisfies) * `1.x` := `>=1.0.0 <2.0.0-0` (Matching major version) * `1.2.x` := `>=1.2.0 <1.3.0-0` (Matching major and minor versions) A partial version range is treated as an X-Range, so the special character is in fact optional. * `""` (empty string) := `*` := `>=0.0.0` * `1` := `1.x.x` := `>=1.0.0 <2.0.0-0` * `1.2` := `1.2.x` := `>=1.2.0 <1.3.0-0` #### Tilde Ranges `~1.2.3` `~1.2` `~1` Allows patch-level changes if a minor version is specified on the comparator. Allows minor-level changes if not. * `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0-0` * `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0-0` (Same as `1.2.x`) * `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0-0` (Same as `1.x`) * `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0-0` * `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0-0` (Same as `0.2.x`) * `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0-0` (Same as `0.x`) * `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0-0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. #### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` Allows changes that do not modify the left-most non-zero element in the `[major, minor, patch]` tuple. In other words, this allows patch and minor updates for versions `1.0.0` and above, patch updates for versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. Many authors treat a `0.x` version as if the `x` were the major "breaking-change" indicator. Caret ranges are ideal when an author may make breaking changes between `0.2.4` and `0.3.0` releases, which is a common practice. However, it presumes that there will *not* be breaking changes between `0.2.4` and `0.2.5`. It allows for changes that are presumed to be additive (but non-breaking), according to commonly observed practices. * `^1.2.3` := `>=1.2.3 <2.0.0-0` * `^0.2.3` := `>=0.2.3 <0.3.0-0` * `^0.0.3` := `>=0.0.3 <0.0.4-0` * `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0-0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. * `^0.0.3-beta` := `>=0.0.3-beta <0.0.4-0` Note that prereleases in the `0.0.3` version *only* will be allowed, if they are greater than or equal to `beta`. So, `0.0.3-pr.2` would be allowed. When parsing caret ranges, a missing `patch` value desugars to the number `0`, but will allow flexibility within that value, even if the major and minor versions are both `0`. * `^1.2.x` := `>=1.2.0 <2.0.0-0` * `^0.0.x` := `>=0.0.0 <0.1.0-0` * `^0.0` := `>=0.0.0 <0.1.0-0` A missing `minor` and `patch` values will desugar to zero, but also allow flexibility within those values, even if the major version is zero. * `^1.x` := `>=1.0.0 <2.0.0-0` * `^0.x` := `>=0.0.0 <1.0.0-0` ### Range Grammar Putting all this together, here is a Backus-Naur grammar for ranges, for the benefit of parser authors: ```bnf range-set ::= range ( logical-or range ) * logical-or ::= ( ' ' ) * '||' ( ' ' ) * range ::= hyphen | simple ( ' ' simple ) * | '' hyphen ::= partial ' - ' partial simple ::= primitive | partial | tilde | caret primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? xr ::= 'x' | 'X' | '*' | nr nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * tilde ::= '~' partial caret ::= '^' partial qualifier ::= ( '-' pre )? ( '+' build )? pre ::= parts build ::= parts parts ::= part ( '.' part ) * part ::= nr | [-0-9A-Za-z]+ ``` ## Functions All methods and classes take a final `options` object argument. All options in this object are `false` by default. The options supported are: - `loose`: Be more forgiving about not-quite-valid semver strings. (Any resulting output will always be 100% strict compliant, of course.) For backwards compatibility reasons, if the `options` argument is a boolean value instead of an object, it is interpreted to be the `loose` param. - `includePrerelease`: Set to suppress the [default behavior](https://github.com/npm/node-semver#prerelease-tags) of excluding prerelease tagged versions from ranges unless they are explicitly opted into. Strict-mode Comparators and Ranges will be strict about the SemVer strings that they parse. * `valid(v)`: Return the parsed version, or null if it's not valid. * `inc(v, release, options, identifier, identifierBase)`: Return the version incremented by the release type (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), or null if it's not valid * `premajor` in one call will bump the version up to the next major version and down to a prerelease of that major version. `preminor`, and `prepatch` work the same way. * If called from a non-prerelease version, `prerelease` will work the same as `prepatch`. It increments the patch version and then makes a prerelease. If the input version is already a prerelease it simply increments it. * `identifier` can be used to prefix `premajor`, `preminor`, `prepatch`, or `prerelease` version increments. `identifierBase` is the base to be used for the `prerelease` identifier. * `prerelease(v)`: Returns an array of prerelease components, or null if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` * `major(v)`: Return the major version number. * `minor(v)`: Return the minor version number. * `patch(v)`: Return the patch version number. * `intersects(r1, r2, loose)`: Return true if the two supplied ranges or comparators intersect. * `parse(v)`: Attempt to parse a string as a semantic version, returning either a `SemVer` object or `null`. ### Comparison * `gt(v1, v2)`: `v1 > v2` * `gte(v1, v2)`: `v1 >= v2` * `lt(v1, v2)`: `v1 < v2` * `lte(v1, v2)`: `v1 <= v2` * `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent, even if they're not the same string. You already know how to compare strings. * `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. * `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call the corresponding function above. `"==="` and `"!=="` do simple string comparison, but are included for completeness. Throws if an invalid comparison string is provided. * `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. * `rcompare(v1, v2)`: The reverse of `compare`. Sorts an array of versions in descending order when passed to `Array.sort()`. * `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions are equal. Sorts in ascending order if passed to `Array.sort()`. * `compareLoose(v1, v2)`: Short for ``compare(v1, v2, { loose: true })`. * `diff(v1, v2)`: Returns the difference between two versions by the release type (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), or null if the versions are the same. ### Sorting * `sort(versions)`: Returns a sorted array of versions based on the `compareBuild` function. * `rsort(versions)`: The reverse of `sort`. Returns an array of versions based on the `compareBuild` function in descending order. ### Comparators * `intersects(comparator)`: Return true if the comparators intersect ### Ranges * `validRange(range)`: Return the valid range or null if it's not valid * `satisfies(version, range)`: Return true if the version satisfies the range. * `maxSatisfying(versions, range)`: Return the highest version in the list that satisfies the range, or `null` if none of them do. * `minSatisfying(versions, range)`: Return the lowest version in the list that satisfies the range, or `null` if none of them do. * `minVersion(range)`: Return the lowest version that can match the given range. * `gtr(version, range)`: Return `true` if the version is greater than all the versions possible in the range. * `ltr(version, range)`: Return `true` if the version is less than all the versions possible in the range. * `outside(version, range, hilo)`: Return true if the version is outside the bounds of the range in either the high or low direction. The `hilo` argument must be either the string `'>'` or `'<'`. (This is the function called by `gtr` and `ltr`.) * `intersects(range)`: Return true if any of the range comparators intersect. * `simplifyRange(versions, range)`: Return a "simplified" range that matches the same items in the `versions` list as the range specified. Note that it does *not* guarantee that it would match the same versions in all cases, only for the set of versions provided. This is useful when generating ranges by joining together multiple versions with `||` programmatically, to provide the user with something a bit more ergonomic. If the provided range is shorter in string-length than the generated range, then that is returned. * `subset(subRange, superRange)`: Return `true` if the `subRange` range is entirely contained by the `superRange` range. Note that, since ranges may be non-contiguous, a version might not be greater than a range, less than a range, *or* satisfy a range! For example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` until `2.0.0`, so version `1.2.10` would not be greater than the range (because `2.0.1` satisfies, which is higher), nor less than the range (since `1.2.8` satisfies, which is lower), and it also does not satisfy the range. If you want to know if a version satisfies or does not satisfy a range, use the `satisfies(version, range)` function. ### Coercion * `coerce(version, options)`: Coerces a string to semver if possible This aims to provide a very forgiving translation of a non-semver string to semver. It looks for the first digit in a string and consumes all remaining characters which satisfy at least a partial semver (e.g., `1`, `1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes `3.4.0`). Only text which lacks digits will fail coercion (`version one` is not valid). The maximum length for any semver component considered for coercion is 16 characters; longer components will be ignored (`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value components are invalid (`9999999999999999.4.7.4` is likely invalid). If the `options.rtl` flag is set, then `coerce` will return the right-most coercible tuple that does not share an ending index with a longer coercible tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not `4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of any other overlapping SemVer tuple. If the `options.includePrerelease` flag is set, then the `coerce` result will contain prerelease and build parts of a version. For example, `1.2.3.4-rc.1+rev.2` will preserve prerelease `rc.1` and build `rev.2` in the result. ### Clean * `clean(version)`: Clean a string to be a valid semver if possible This will return a cleaned and trimmed semver version. If the provided version is not valid a null will be returned. This does not work for ranges. ex. * `s.clean(' = v 2.1.5foo')`: `null` * `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'` * `s.clean(' = v 2.1.5-foo')`: `null` * `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'` * `s.clean('=v2.1.5')`: `'2.1.5'` * `s.clean(' =v2.1.5')`: `'2.1.5'` * `s.clean(' 2.1.5 ')`: `'2.1.5'` * `s.clean('~1.0.0')`: `null` ## Constants As a convenience, helper constants are exported to provide information about what `node-semver` supports: ### `RELEASE_TYPES` - major - premajor - minor - preminor - patch - prepatch - prerelease ``` const semver = require('semver'); if (semver.RELEASE_TYPES.includes(arbitraryUserInput)) { console.log('This is a valid release type!'); } else { console.warn('This is NOT a valid release type!'); } ``` ### `SEMVER_SPEC_VERSION` 2.0.0 ``` const semver = require('semver'); console.log('We are currently using the semver specification version:', semver.SEMVER_SPEC_VERSION); ``` ## Exported Modules You may pull in just the part of this semver utility that you need if you are sensitive to packing and tree-shaking concerns. The main `require('semver')` export uses getter functions to lazily load the parts of the API that are used. The following modules are available: * `require('semver')` * `require('semver/classes')` * `require('semver/classes/comparator')` * `require('semver/classes/range')` * `require('semver/classes/semver')` * `require('semver/functions/clean')` * `require('semver/functions/cmp')` * `require('semver/functions/coerce')` * `require('semver/functions/compare')` * `require('semver/functions/compare-build')` * `require('semver/functions/compare-loose')` * `require('semver/functions/diff')` * `require('semver/functions/eq')` * `require('semver/functions/gt')` * `require('semver/functions/gte')` * `require('semver/functions/inc')` * `require('semver/functions/lt')` * `require('semver/functions/lte')` * `require('semver/functions/major')` * `require('semver/functions/minor')` * `require('semver/functions/neq')` * `require('semver/functions/parse')` * `require('semver/functions/patch')` * `require('semver/functions/prerelease')` * `require('semver/functions/rcompare')` * `require('semver/functions/rsort')` * `require('semver/functions/satisfies')` * `require('semver/functions/sort')` * `require('semver/functions/valid')` * `require('semver/ranges/gtr')` * `require('semver/ranges/intersects')` * `require('semver/ranges/ltr')` * `require('semver/ranges/max-satisfying')` * `require('semver/ranges/min-satisfying')` * `require('semver/ranges/min-version')` * `require('semver/ranges/outside')` * `require('semver/ranges/simplify')` * `require('semver/ranges/subset')` * `require('semver/ranges/to-comparators')` * `require('semver/ranges/valid')` PK ~\-semver/functions/compare.jsnu[const SemVer = require('../classes/semver') const compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose)) module.exports = compare PK ~\+lsemver/functions/inc.jsnu[const SemVer = require('../classes/semver') const inc = (version, release, options, identifier, identifierBase) => { if (typeof (options) === 'string') { identifierBase = identifier identifier = options options = undefined } try { return new SemVer( version instanceof SemVer ? version.version : version, options ).inc(release, identifier, identifierBase).version } catch (er) { return null } } module.exports = inc PK ~\ Jvv!semver/functions/compare-loose.jsnu[const compare = require('./compare') const compareLoose = (a, b) => compare(a, b, true) module.exports = compareLoose PK ~\\ezzsemver/functions/minor.jsnu[const SemVer = require('../classes/semver') const minor = (a, loose) => new SemVer(a, loose).minor module.exports = minor PK ~\zzsemver/functions/patch.jsnu[const SemVer = require('../classes/semver') const patch = (a, loose) => new SemVer(a, loose).patch module.exports = patch PK ~\iO  !semver/functions/compare-build.jsnu[const SemVer = require('../classes/semver') const compareBuild = (a, b, loose) => { const versionA = new SemVer(a, loose) const versionB = new SemVer(b, loose) return versionA.compare(versionB) || versionA.compareBuild(versionB) } module.exports = compareBuild PK ~\Hxsemver/functions/prerelease.jsnu[const parse = require('./parse') const prerelease = (version, options) => { const parsed = parse(version, options) return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } module.exports = prerelease PK ~\r#Vsemver/functions/cmp.jsnu[const eq = require('./eq') const neq = require('./neq') const gt = require('./gt') const gte = require('./gte') const lt = require('./lt') const lte = require('./lte') const cmp = (a, op, b, loose) => { switch (op) { case '===': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a === b case '!==': if (typeof a === 'object') { a = a.version } if (typeof b === 'object') { b = b.version } return a !== b case '': case '=': case '==': return eq(a, b, loose) case '!=': return neq(a, b, loose) case '>': return gt(a, b, loose) case '>=': return gte(a, b, loose) case '<': return lt(a, b, loose) case '<=': return lte(a, b, loose) default: throw new TypeError(`Invalid operator: ${op}`) } } module.exports = cmp PK ~\+rrsemver/functions/neq.jsnu[const compare = require('./compare') const neq = (a, b, loose) => compare(a, b, loose) !== 0 module.exports = neq PK ~\:Unnsemver/functions/gt.jsnu[const compare = require('./compare') const gt = (a, b, loose) => compare(a, b, loose) > 0 module.exports = gt PK ~\J==semver/functions/parse.jsnu[const SemVer = require('../classes/semver') const parse = (version, options, throwErrors = false) => { if (version instanceof SemVer) { return version } try { return new SemVer(version, options) } catch (er) { if (!throwErrors) { return null } throw er } } module.exports = parse PK ~\Qgsemver/functions/sort.jsnu[const compareBuild = require('./compare-build') const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) module.exports = sort PK ~\KHvvsemver/functions/rcompare.jsnu[const compare = require('./compare') const rcompare = (a, b, loose) => compare(b, a, loose) module.exports = rcompare PK ~\DSqqsemver/functions/lte.jsnu[const compare = require('./compare') const lte = (a, b, loose) => compare(a, b, loose) <= 0 module.exports = lte PK ~\!Wsemver/functions/coerce.jsnu[const SemVer = require('../classes/semver') const parse = require('./parse') const { safeRe: re, t } = require('../internal/re') const coerce = (version, options) => { if (version instanceof SemVer) { return version } if (typeof version === 'number') { version = String(version) } if (typeof version !== 'string') { return null } options = options || {} let match = null if (!options.rtl) { match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]) } else { // Find the right-most coercible string that does not share // a terminus with a more left-ward coercible string. // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4' // // Walk through the string checking with a /g regexp // Manually set the index so as to pick up overlapping matches. // Stop when we get a match that ends at the string end, since no // coercible string can be more right-ward without the same terminus. const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL] let next while ((next = coerceRtlRegex.exec(version)) && (!match || match.index + match[0].length !== version.length) ) { if (!match || next.index + next[0].length !== match.index + match[0].length) { match = next } coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length } // leave it in a clean state coerceRtlRegex.lastIndex = -1 } if (match === null) { return null } const major = match[2] const minor = match[3] || '0' const patch = match[4] || '0' const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : '' const build = options.includePrerelease && match[6] ? `+${match[6]}` : '' return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options) } module.exports = coerce PK ~\I zzsemver/functions/major.jsnu[const SemVer = require('../classes/semver') const major = (a, loose) => new SemVer(a, loose).major module.exports = major PK ~\,ppsemver/functions/eq.jsnu[const compare = require('./compare') const eq = (a, b, loose) => compare(a, b, loose) === 0 module.exports = eq PK ~\qqsemver/functions/gte.jsnu[const compare = require('./compare') const gte = (a, b, loose) => compare(a, b, loose) >= 0 module.exports = gte PK ~\}zCsemver/functions/valid.jsnu[const parse = require('./parse') const valid = (version, options) => { const v = parse(version, options) return v ? v.version : null } module.exports = valid PK ~\semver/functions/satisfies.jsnu[const Range = require('../classes/range') const satisfies = (version, range, options) => { try { range = new Range(range, options) } catch (er) { return false } return range.test(version) } module.exports = satisfies PK ~\cƧsemver/functions/clean.jsnu[const parse = require('./parse') const clean = (version, options) => { const s = parse(version.trim().replace(/^[=v]+/, ''), options) return s ? s.version : null } module.exports = clean PK ~\ޝysemver/functions/rsort.jsnu[const compareBuild = require('./compare-build') const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) module.exports = rsort PK ~\;}nnsemver/functions/lt.jsnu[const compare = require('./compare') const lt = (a, b, loose) => compare(a, b, loose) < 0 module.exports = lt PK ~\3[LLsemver/functions/diff.jsnu[const parse = require('./parse.js') const diff = (version1, version2) => { const v1 = parse(version1, null, true) const v2 = parse(version2, null, true) const comparison = v1.compare(v2) if (comparison === 0) { return null } const v1Higher = comparison > 0 const highVersion = v1Higher ? v1 : v2 const lowVersion = v1Higher ? v2 : v1 const highHasPre = !!highVersion.prerelease.length const lowHasPre = !!lowVersion.prerelease.length if (lowHasPre && !highHasPre) { // Going from prerelease -> no prerelease requires some special casing // If the low version has only a major, then it will always be a major // Some examples: // 1.0.0-1 -> 1.0.0 // 1.0.0-1 -> 1.1.1 // 1.0.0-1 -> 2.0.0 if (!lowVersion.patch && !lowVersion.minor) { return 'major' } // Otherwise it can be determined by checking the high version if (highVersion.patch) { // anything higher than a patch bump would result in the wrong version return 'patch' } if (highVersion.minor) { // anything higher than a minor bump would result in the wrong version return 'minor' } // bumping major/minor/patch all have same result return 'major' } // add the `pre` prefix if we are going to a prerelease version const prefix = highHasPre ? 'pre' : '' if (v1.major !== v2.major) { return prefix + 'major' } if (v1.minor !== v2.minor) { return prefix + 'minor' } if (v1.patch !== v2.patch) { return prefix + 'patch' } // high and low are preleases return 'prerelease' } module.exports = diff PK ~\Vû88semver/classes/range.jsnu[// hoisted class for cyclic dependency class Range { constructor (range, options) { options = parseOptions(options) if (range instanceof Range) { if ( range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease ) { return range } else { return new Range(range.raw, options) } } if (range instanceof Comparator) { // just put it in the set and return this.raw = range.value this.set = [[range]] this.format() return this } this.options = options this.loose = !!options.loose this.includePrerelease = !!options.includePrerelease // First reduce all whitespace as much as possible so we do not have to rely // on potentially slow regexes like \s*. This is then stored and used for // future error messages as well. this.raw = range .trim() .split(/\s+/) .join(' ') // First, split on || this.set = this.raw .split('||') // map the range to a 2d array of comparators .map(r => this.parseRange(r.trim())) // throw out any comparator lists that are empty // this generally means that it was not a valid range, which is allowed // in loose mode, but will still throw if the WHOLE range is invalid. .filter(c => c.length) if (!this.set.length) { throw new TypeError(`Invalid SemVer Range: ${this.raw}`) } // if we have any that are not the null set, throw out null sets. if (this.set.length > 1) { // keep the first one, in case they're all null sets const first = this.set[0] this.set = this.set.filter(c => !isNullSet(c[0])) if (this.set.length === 0) { this.set = [first] } else if (this.set.length > 1) { // if we have any that are *, then the range is just * for (const c of this.set) { if (c.length === 1 && isAny(c[0])) { this.set = [c] break } } } } this.format() } format () { this.range = this.set .map((comps) => comps.join(' ').trim()) .join('||') .trim() return this.range } toString () { return this.range } parseRange (range) { // memoize range parsing for performance. // this is a very hot path, and fully deterministic. const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE) const memoKey = memoOpts + ':' + range const cached = cache.get(memoKey) if (cached) { return cached } const loose = this.options.loose // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) debug('hyphen replace', range) // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) debug('comparator trim', range) // `~ 1.2.3` => `~1.2.3` range = range.replace(re[t.TILDETRIM], tildeTrimReplace) debug('tilde trim', range) // `^ 1.2.3` => `^1.2.3` range = range.replace(re[t.CARETTRIM], caretTrimReplace) debug('caret trim', range) // At this point, the range is completely trimmed and // ready to be split into comparators. let rangeList = range .split(' ') .map(comp => parseComparator(comp, this.options)) .join(' ') .split(/\s+/) // >=0.0.0 is equivalent to * .map(comp => replaceGTE0(comp, this.options)) if (loose) { // in loose mode, throw out any that are not valid comparators rangeList = rangeList.filter(comp => { debug('loose invalid filter', comp, this.options) return !!comp.match(re[t.COMPARATORLOOSE]) }) } debug('range list', rangeList) // if any comparators are the null set, then replace with JUST null set // if more than one comparator, remove any * comparators // also, don't include the same comparator more than once const rangeMap = new Map() const comparators = rangeList.map(comp => new Comparator(comp, this.options)) for (const comp of comparators) { if (isNullSet(comp)) { return [comp] } rangeMap.set(comp.value, comp) } if (rangeMap.size > 1 && rangeMap.has('')) { rangeMap.delete('') } const result = [...rangeMap.values()] cache.set(memoKey, result) return result } intersects (range, options) { if (!(range instanceof Range)) { throw new TypeError('a Range is required') } return this.set.some((thisComparators) => { return ( isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => { return ( isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => { return rangeComparators.every((rangeComparator) => { return thisComparator.intersects(rangeComparator, options) }) }) ) }) ) }) } // if ANY of the sets match ALL of its comparators, then pass test (version) { if (!version) { return false } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } for (let i = 0; i < this.set.length; i++) { if (testSet(this.set[i], version, this.options)) { return true } } return false } } module.exports = Range const LRU = require('../internal/lrucache') const cache = new LRU() const parseOptions = require('../internal/parse-options') const Comparator = require('./comparator') const debug = require('../internal/debug') const SemVer = require('./semver') const { safeRe: re, t, comparatorTrimReplace, tildeTrimReplace, caretTrimReplace, } = require('../internal/re') const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require('../internal/constants') const isNullSet = c => c.value === '<0.0.0-0' const isAny = c => c.value === '' // take a set of comparators and determine whether there // exists a version which can satisfy it const isSatisfiable = (comparators, options) => { let result = true const remainingComparators = comparators.slice() let testComparator = remainingComparators.pop() while (result && remainingComparators.length) { result = remainingComparators.every((otherComparator) => { return testComparator.intersects(otherComparator, options) }) testComparator = remainingComparators.pop() } return result } // comprised of xranges, tildes, stars, and gtlt's at this point. // already replaced the hyphen ranges // turn into a set of JUST comparators. const parseComparator = (comp, options) => { debug('comp', comp, options) comp = replaceCarets(comp, options) debug('caret', comp) comp = replaceTildes(comp, options) debug('tildes', comp) comp = replaceXRanges(comp, options) debug('xrange', comp) comp = replaceStars(comp, options) debug('stars', comp) return comp } const isX = id => !id || id.toLowerCase() === 'x' || id === '*' // ~, ~> --> * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 // ~0.0.1 --> >=0.0.1 <0.1.0-0 const replaceTildes = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceTilde(c, options)) .join(' ') } const replaceTilde = (comp, options) => { const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] return comp.replace(r, (_, M, m, p, pr) => { debug('tilde', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0 <${+M + 1}.0.0-0` } else if (isX(p)) { // ~1.2 == >=1.2.0 <1.3.0-0 ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` } else if (pr) { debug('replaceTilde pr', pr) ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } else { // ~1.2.3 == >=1.2.3 <1.3.0-0 ret = `>=${M}.${m}.${p } <${M}.${+m + 1}.0-0` } debug('tilde return', ret) return ret }) } // ^ --> * (any, kinda silly) // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 // ^1.2.3 --> >=1.2.3 <2.0.0-0 // ^1.2.0 --> >=1.2.0 <2.0.0-0 // ^0.0.1 --> >=0.0.1 <0.0.2-0 // ^0.1.0 --> >=0.1.0 <0.2.0-0 const replaceCarets = (comp, options) => { return comp .trim() .split(/\s+/) .map((c) => replaceCaret(c, options)) .join(' ') } const replaceCaret = (comp, options) => { debug('caret', comp, options) const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] const z = options.includePrerelease ? '-0' : '' return comp.replace(r, (_, M, m, p, pr) => { debug('caret', comp, _, M, m, p, pr) let ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` } else if (isX(p)) { if (M === '0') { ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` } else { ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` } } else if (pr) { debug('replaceCaret pr', pr) if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p}-${pr } <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p}-${pr } <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p}-${pr } <${+M + 1}.0.0-0` } } else { debug('no pr') if (M === '0') { if (m === '0') { ret = `>=${M}.${m}.${p }${z} <${M}.${m}.${+p + 1}-0` } else { ret = `>=${M}.${m}.${p }${z} <${M}.${+m + 1}.0-0` } } else { ret = `>=${M}.${m}.${p } <${+M + 1}.0.0-0` } } debug('caret return', ret) return ret }) } const replaceXRanges = (comp, options) => { debug('replaceXRanges', comp, options) return comp .split(/\s+/) .map((c) => replaceXRange(c, options)) .join(' ') } const replaceXRange = (comp, options) => { comp = comp.trim() const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] return comp.replace(r, (ret, gtlt, M, m, p, pr) => { debug('xRange', comp, ret, gtlt, M, m, p, pr) const xM = isX(M) const xm = xM || isX(m) const xp = xm || isX(p) const anyX = xp if (gtlt === '=' && anyX) { gtlt = '' } // if we're including prereleases in the match, then we need // to fix this to -0, the lowest possible prerelease value pr = options.includePrerelease ? '-0' : '' if (xM) { if (gtlt === '>' || gtlt === '<') { // nothing is allowed ret = '<0.0.0-0' } else { // nothing is forbidden ret = '*' } } else if (gtlt && anyX) { // we know patch is an x, because we have any x at all. // replace X with 0 if (xm) { m = 0 } p = 0 if (gtlt === '>') { // >1 => >=2.0.0 // >1.2 => >=1.3.0 gtlt = '>=' if (xm) { M = +M + 1 m = 0 p = 0 } else { m = +m + 1 p = 0 } } else if (gtlt === '<=') { // <=0.7.x is actually <0.8.0, since any 0.7.x should // pass. Similarly, <=7.x is actually <8.0.0, etc. gtlt = '<' if (xm) { M = +M + 1 } else { m = +m + 1 } } if (gtlt === '<') { pr = '-0' } ret = `${gtlt + M}.${m}.${p}${pr}` } else if (xm) { ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` } else if (xp) { ret = `>=${M}.${m}.0${pr } <${M}.${+m + 1}.0-0` } debug('xRange return', ret) return ret }) } // Because * is AND-ed with everything else in the comparator, // and '' means "any version", just remove the *s entirely. const replaceStars = (comp, options) => { debug('replaceStars', comp, options) // Looseness is ignored here. star is always as loose as it gets! return comp .trim() .replace(re[t.STAR], '') } const replaceGTE0 = (comp, options) => { debug('replaceGTE0', comp, options) return comp .trim() .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') } // This function is passed to string.replace(re[t.HYPHENRANGE]) // M, m, patch, prerelease, build // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 // TODO build? const hyphenReplace = incPr => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => { if (isX(fM)) { from = '' } else if (isX(fm)) { from = `>=${fM}.0.0${incPr ? '-0' : ''}` } else if (isX(fp)) { from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` } else if (fpr) { from = `>=${from}` } else { from = `>=${from}${incPr ? '-0' : ''}` } if (isX(tM)) { to = '' } else if (isX(tm)) { to = `<${+tM + 1}.0.0-0` } else if (isX(tp)) { to = `<${tM}.${+tm + 1}.0-0` } else if (tpr) { to = `<=${tM}.${tm}.${tp}-${tpr}` } else if (incPr) { to = `<${tM}.${tm}.${+tp + 1}-0` } else { to = `<=${to}` } return `${from} ${to}`.trim() } const testSet = (set, version, options) => { for (let i = 0; i < set.length; i++) { if (!set[i].test(version)) { return false } } if (version.prerelease.length && !options.includePrerelease) { // Find the set of versions that are allowed to have prereleases // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 // That should allow `1.2.3-pr.2` to pass. // However, `1.2.4-alpha.notready` should NOT be allowed, // even though it's within the range set by the comparators. for (let i = 0; i < set.length; i++) { debug(set[i].semver) if (set[i].semver === Comparator.ANY) { continue } if (set[i].semver.prerelease.length > 0) { const allowed = set[i].semver if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { return true } } } // Version has a -pre, but it's not one of the ones we like. return false } return true } PK ~\Ḿsemver/classes/index.jsnu[module.exports = { SemVer: require('./semver.js'), Range: require('./range.js'), Comparator: require('./comparator.js'), } PK ~\QT/"/"semver/classes/semver.jsnu[const debug = require('../internal/debug') const { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants') const { safeRe: re, t } = require('../internal/re') const parseOptions = require('../internal/parse-options') const { compareIdentifiers } = require('../internal/identifiers') class SemVer { constructor (version, options) { options = parseOptions(options) if (version instanceof SemVer) { if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { return version } else { version = version.version } } else if (typeof version !== 'string') { throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) } if (version.length > MAX_LENGTH) { throw new TypeError( `version is longer than ${MAX_LENGTH} characters` ) } debug('SemVer', version, options) this.options = options this.loose = !!options.loose // this isn't actually relevant for versions, but keep it so that we // don't run into trouble passing this.options around. this.includePrerelease = !!options.includePrerelease const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) if (!m) { throw new TypeError(`Invalid Version: ${version}`) } this.raw = version // these are actually numbers this.major = +m[1] this.minor = +m[2] this.patch = +m[3] if (this.major > MAX_SAFE_INTEGER || this.major < 0) { throw new TypeError('Invalid major version') } if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { throw new TypeError('Invalid minor version') } if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { throw new TypeError('Invalid patch version') } // numberify any prerelease numeric ids if (!m[4]) { this.prerelease = [] } else { this.prerelease = m[4].split('.').map((id) => { if (/^[0-9]+$/.test(id)) { const num = +id if (num >= 0 && num < MAX_SAFE_INTEGER) { return num } } return id }) } this.build = m[5] ? m[5].split('.') : [] this.format() } format () { this.version = `${this.major}.${this.minor}.${this.patch}` if (this.prerelease.length) { this.version += `-${this.prerelease.join('.')}` } return this.version } toString () { return this.version } compare (other) { debug('SemVer.compare', this.version, this.options, other) if (!(other instanceof SemVer)) { if (typeof other === 'string' && other === this.version) { return 0 } other = new SemVer(other, this.options) } if (other.version === this.version) { return 0 } return this.compareMain(other) || this.comparePre(other) } compareMain (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return ( compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch) ) } comparePre (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } // NOT having a prerelease is > having one if (this.prerelease.length && !other.prerelease.length) { return -1 } else if (!this.prerelease.length && other.prerelease.length) { return 1 } else if (!this.prerelease.length && !other.prerelease.length) { return 0 } let i = 0 do { const a = this.prerelease[i] const b = other.prerelease[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } compareBuild (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } let i = 0 do { const a = this.build[i] const b = other.build[i] debug('build compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. inc (release, identifier, identifierBase) { switch (release) { case 'premajor': this.prerelease.length = 0 this.patch = 0 this.minor = 0 this.major++ this.inc('pre', identifier, identifierBase) break case 'preminor': this.prerelease.length = 0 this.patch = 0 this.minor++ this.inc('pre', identifier, identifierBase) break case 'prepatch': // If this is already a prerelease, it will bump to the next version // drop any prereleases that might already exist, since they are not // relevant at this point. this.prerelease.length = 0 this.inc('patch', identifier, identifierBase) this.inc('pre', identifier, identifierBase) break // If the input is a non-prerelease version, this acts the same as // prepatch. case 'prerelease': if (this.prerelease.length === 0) { this.inc('patch', identifier, identifierBase) } this.inc('pre', identifier, identifierBase) break case 'major': // If this is a pre-major version, bump up to the same major version. // Otherwise increment major. // 1.0.0-5 bumps to 1.0.0 // 1.1.0 bumps to 2.0.0 if ( this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0 ) { this.major++ } this.minor = 0 this.patch = 0 this.prerelease = [] break case 'minor': // If this is a pre-minor version, bump up to the same minor version. // Otherwise increment minor. // 1.2.0-5 bumps to 1.2.0 // 1.2.1 bumps to 1.3.0 if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++ } this.patch = 0 this.prerelease = [] break case 'patch': // If this is not a pre-release version, it will increment the patch. // If it is a pre-release it will bump up to the same patch version. // 1.2.0-5 patches to 1.2.0 // 1.2.0 patches to 1.2.1 if (this.prerelease.length === 0) { this.patch++ } this.prerelease = [] break // This probably shouldn't be used publicly. // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. case 'pre': { const base = Number(identifierBase) ? 1 : 0 if (!identifier && identifierBase === false) { throw new Error('invalid increment argument: identifier is empty') } if (this.prerelease.length === 0) { this.prerelease = [base] } else { let i = this.prerelease.length while (--i >= 0) { if (typeof this.prerelease[i] === 'number') { this.prerelease[i]++ i = -2 } } if (i === -1) { // didn't increment anything if (identifier === this.prerelease.join('.') && identifierBase === false) { throw new Error('invalid increment argument: identifier already exists') } this.prerelease.push(base) } } if (identifier) { // 1.2.0-beta.1 bumps to 1.2.0-beta.2, // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 let prerelease = [identifier, base] if (identifierBase === false) { prerelease = [identifier] } if (compareIdentifiers(this.prerelease[0], identifier) === 0) { if (isNaN(this.prerelease[1])) { this.prerelease = prerelease } } else { this.prerelease = prerelease } } break } default: throw new Error(`invalid increment argument: ${release}`) } this.raw = this.format() if (this.build.length) { this.raw += `+${this.build.join('.')}` } return this } } module.exports = SemVer PK ~\;+!!semver/classes/comparator.jsnu[const ANY = Symbol('SemVer ANY') // hoisted class for cyclic dependency class Comparator { static get ANY () { return ANY } constructor (comp, options) { options = parseOptions(options) if (comp instanceof Comparator) { if (comp.loose === !!options.loose) { return comp } else { comp = comp.value } } comp = comp.trim().split(/\s+/).join(' ') debug('comparator', comp, options) this.options = options this.loose = !!options.loose this.parse(comp) if (this.semver === ANY) { this.value = '' } else { this.value = this.operator + this.semver.version } debug('comp', this) } parse (comp) { const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] const m = comp.match(r) if (!m) { throw new TypeError(`Invalid comparator: ${comp}`) } this.operator = m[1] !== undefined ? m[1] : '' if (this.operator === '=') { this.operator = '' } // if it literally is just '>' or '' then allow anything. if (!m[2]) { this.semver = ANY } else { this.semver = new SemVer(m[2], this.options.loose) } } toString () { return this.value } test (version) { debug('Comparator.test', version, this.options.loose) if (this.semver === ANY || version === ANY) { return true } if (typeof version === 'string') { try { version = new SemVer(version, this.options) } catch (er) { return false } } return cmp(version, this.operator, this.semver, this.options) } intersects (comp, options) { if (!(comp instanceof Comparator)) { throw new TypeError('a Comparator is required') } if (this.operator === '') { if (this.value === '') { return true } return new Range(comp.value, options).test(this.value) } else if (comp.operator === '') { if (comp.value === '') { return true } return new Range(this.value, options).test(comp.semver) } options = parseOptions(options) // Special cases where nothing can possibly be lower if (options.includePrerelease && (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { return false } if (!options.includePrerelease && (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { return false } // Same direction increasing (> or >=) if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { return true } // Same direction decreasing (< or <=) if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { return true } // same SemVer and both sides are inclusive (<= or >=) if ( (this.semver.version === comp.semver.version) && this.operator.includes('=') && comp.operator.includes('=')) { return true } // opposite directions less than if (cmp(this.semver, '<', comp.semver, options) && this.operator.startsWith('>') && comp.operator.startsWith('<')) { return true } // opposite directions greater than if (cmp(this.semver, '>', comp.semver, options) && this.operator.startsWith('<') && comp.operator.startsWith('>')) { return true } return false } } module.exports = Comparator const parseOptions = require('../internal/parse-options') const { safeRe: re, t } = require('../internal/re') const cmp = require('../functions/cmp') const debug = require('../internal/debug') const SemVer = require('./semver') const Range = require('./range') PK ~\okksemver/range.bnfnu[range-set ::= range ( logical-or range ) * logical-or ::= ( ' ' ) * '||' ( ' ' ) * range ::= hyphen | simple ( ' ' simple ) * | '' hyphen ::= partial ' - ' partial simple ::= primitive | partial | tilde | caret primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? xr ::= 'x' | 'X' | '*' | nr nr ::= '0' | [1-9] ( [0-9] ) * tilde ::= '~' partial caret ::= '^' partial qualifier ::= ( '-' pre )? ( '+' build )? pre ::= parts build ::= parts parts ::= part ( '.' part ) * part ::= nr | [-0-9A-Za-z]+ PK ~\ި;;ci-info/package.jsonnu[{ "_id": "ci-info@4.0.0", "_inBundle": true, "_location": "/npm/ci-info", "_phantomChildren": {}, "_requiredBy": [ "/npm", "/npm/@npmcli/config", "/npm/libnpmexec", "/npm/libnpmpublish" ], "author": { "name": "Thomas Watson Steen", "email": "w@tson.dk", "url": "https://twitter.com/wa7son" }, "bugs": { "url": "https://github.com/watson/ci-info/issues" }, "description": "Get details about the current Continuous Integration environment", "devDependencies": { "clear-module": "^4.1.2", "husky": "^8.0.3", "standard": "^17.1.0", "tape": "^5.7.0" }, "engines": { "node": ">=8" }, "files": [ "vendors.json", "index.js", "index.d.ts", "CHANGELOG.md" ], "funding": [ { "type": "github", "url": "https://github.com/sponsors/sibiraj-s" } ], "homepage": "https://github.com/watson/ci-info", "keywords": [ "ci", "continuous", "integration", "test", "detect" ], "license": "MIT", "main": "index.js", "name": "ci-info", "repository": { "type": "git", "url": "git+https://github.com/watson/ci-info.git" }, "scripts": { "lint:fix": "standard --fix", "prepare": "husky install", "test": "standard && node test.js" }, "typings": "index.d.ts", "version": "4.0.0" } PK ~\=o=:>>ci-info/LICENSEnu[The MIT License (MIT) Copyright (c) 2016 Thomas Watson Steen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\Уm@ @ ci-info/index.jsnu['use strict' const vendors = require('./vendors.json') const env = process.env // Used for testing only Object.defineProperty(exports, '_vendors', { value: vendors.map(function (v) { return v.constant }) }) exports.name = null exports.isPR = null vendors.forEach(function (vendor) { const envs = Array.isArray(vendor.env) ? vendor.env : [vendor.env] const isCI = envs.every(function (obj) { return checkEnv(obj) }) exports[vendor.constant] = isCI if (!isCI) { return } exports.name = vendor.name switch (typeof vendor.pr) { case 'string': // "pr": "CIRRUS_PR" exports.isPR = !!env[vendor.pr] break case 'object': if ('env' in vendor.pr) { // "pr": { "env": "BUILDKITE_PULL_REQUEST", "ne": "false" } exports.isPR = vendor.pr.env in env && env[vendor.pr.env] !== vendor.pr.ne } else if ('any' in vendor.pr) { // "pr": { "any": ["ghprbPullId", "CHANGE_ID"] } exports.isPR = vendor.pr.any.some(function (key) { return !!env[key] }) } else { // "pr": { "DRONE_BUILD_EVENT": "pull_request" } exports.isPR = checkEnv(vendor.pr) } break default: // PR detection not supported for this vendor exports.isPR = null } }) exports.isCI = !!( env.CI !== 'false' && // Bypass all checks if CI env is explicitly set to 'false' (env.BUILD_ID || // Jenkins, Cloudbees env.BUILD_NUMBER || // Jenkins, TeamCity env.CI || // Travis CI, CircleCI, Cirrus CI, Gitlab CI, Appveyor, CodeShip, dsari env.CI_APP_ID || // Appflow env.CI_BUILD_ID || // Appflow env.CI_BUILD_NUMBER || // Appflow env.CI_NAME || // Codeship and others env.CONTINUOUS_INTEGRATION || // Travis CI, Cirrus CI env.RUN_ID || // TaskCluster, dsari exports.name || false) ) function checkEnv (obj) { // "env": "CIRRUS" if (typeof obj === 'string') return !!env[obj] // "env": { "env": "NODE", "includes": "/app/.heroku/node/bin/node" } if ('env' in obj) { // Currently there are no other types, uncomment when there are // if ('includes' in obj) { return env[obj.env] && env[obj.env].includes(obj.includes) // } } if ('any' in obj) { return obj.any.some(function (k) { return !!env[k] }) } return Object.keys(obj).every(function (k) { return env[k] === obj[k] }) } PK ~\YYci-info/vendors.jsonnu[[ { "name": "Agola CI", "constant": "AGOLA", "env": "AGOLA_GIT_REF", "pr": "AGOLA_PULL_REQUEST_ID" }, { "name": "Appcircle", "constant": "APPCIRCLE", "env": "AC_APPCIRCLE" }, { "name": "AppVeyor", "constant": "APPVEYOR", "env": "APPVEYOR", "pr": "APPVEYOR_PULL_REQUEST_NUMBER" }, { "name": "AWS CodeBuild", "constant": "CODEBUILD", "env": "CODEBUILD_BUILD_ARN" }, { "name": "Azure Pipelines", "constant": "AZURE_PIPELINES", "env": "TF_BUILD", "pr": { "BUILD_REASON": "PullRequest" } }, { "name": "Bamboo", "constant": "BAMBOO", "env": "bamboo_planKey" }, { "name": "Bitbucket Pipelines", "constant": "BITBUCKET", "env": "BITBUCKET_COMMIT", "pr": "BITBUCKET_PR_ID" }, { "name": "Bitrise", "constant": "BITRISE", "env": "BITRISE_IO", "pr": "BITRISE_PULL_REQUEST" }, { "name": "Buddy", "constant": "BUDDY", "env": "BUDDY_WORKSPACE_ID", "pr": "BUDDY_EXECUTION_PULL_REQUEST_ID" }, { "name": "Buildkite", "constant": "BUILDKITE", "env": "BUILDKITE", "pr": { "env": "BUILDKITE_PULL_REQUEST", "ne": "false" } }, { "name": "CircleCI", "constant": "CIRCLE", "env": "CIRCLECI", "pr": "CIRCLE_PULL_REQUEST" }, { "name": "Cirrus CI", "constant": "CIRRUS", "env": "CIRRUS_CI", "pr": "CIRRUS_PR" }, { "name": "Codefresh", "constant": "CODEFRESH", "env": "CF_BUILD_ID", "pr": { "any": [ "CF_PULL_REQUEST_NUMBER", "CF_PULL_REQUEST_ID" ] } }, { "name": "Codemagic", "constant": "CODEMAGIC", "env": "CM_BUILD_ID", "pr": "CM_PULL_REQUEST" }, { "name": "Codeship", "constant": "CODESHIP", "env": { "CI_NAME": "codeship" } }, { "name": "Drone", "constant": "DRONE", "env": "DRONE", "pr": { "DRONE_BUILD_EVENT": "pull_request" } }, { "name": "dsari", "constant": "DSARI", "env": "DSARI" }, { "name": "Earthly", "constant": "EARTHLY", "env": "EARTHLY_CI" }, { "name": "Expo Application Services", "constant": "EAS", "env": "EAS_BUILD" }, { "name": "Gerrit", "constant": "GERRIT", "env": "GERRIT_PROJECT" }, { "name": "Gitea Actions", "constant": "GITEA_ACTIONS", "env": "GITEA_ACTIONS" }, { "name": "GitHub Actions", "constant": "GITHUB_ACTIONS", "env": "GITHUB_ACTIONS", "pr": { "GITHUB_EVENT_NAME": "pull_request" } }, { "name": "GitLab CI", "constant": "GITLAB", "env": "GITLAB_CI", "pr": "CI_MERGE_REQUEST_ID" }, { "name": "GoCD", "constant": "GOCD", "env": "GO_PIPELINE_LABEL" }, { "name": "Google Cloud Build", "constant": "GOOGLE_CLOUD_BUILD", "env": "BUILDER_OUTPUT" }, { "name": "Harness CI", "constant": "HARNESS", "env": "HARNESS_BUILD_ID" }, { "name": "Heroku", "constant": "HEROKU", "env": { "env": "NODE", "includes": "/app/.heroku/node/bin/node" } }, { "name": "Hudson", "constant": "HUDSON", "env": "HUDSON_URL" }, { "name": "Jenkins", "constant": "JENKINS", "env": [ "JENKINS_URL", "BUILD_ID" ], "pr": { "any": [ "ghprbPullId", "CHANGE_ID" ] } }, { "name": "LayerCI", "constant": "LAYERCI", "env": "LAYERCI", "pr": "LAYERCI_PULL_REQUEST" }, { "name": "Magnum CI", "constant": "MAGNUM", "env": "MAGNUM" }, { "name": "Netlify CI", "constant": "NETLIFY", "env": "NETLIFY", "pr": { "env": "PULL_REQUEST", "ne": "false" } }, { "name": "Nevercode", "constant": "NEVERCODE", "env": "NEVERCODE", "pr": { "env": "NEVERCODE_PULL_REQUEST", "ne": "false" } }, { "name": "Prow", "constant": "PROW", "env": "PROW_JOB_ID" }, { "name": "ReleaseHub", "constant": "RELEASEHUB", "env": "RELEASE_BUILD_ID" }, { "name": "Render", "constant": "RENDER", "env": "RENDER", "pr": { "IS_PULL_REQUEST": "true" } }, { "name": "Sail CI", "constant": "SAIL", "env": "SAILCI", "pr": "SAIL_PULL_REQUEST_NUMBER" }, { "name": "Screwdriver", "constant": "SCREWDRIVER", "env": "SCREWDRIVER", "pr": { "env": "SD_PULL_REQUEST", "ne": "false" } }, { "name": "Semaphore", "constant": "SEMAPHORE", "env": "SEMAPHORE", "pr": "PULL_REQUEST_NUMBER" }, { "name": "Sourcehut", "constant": "SOURCEHUT", "env": { "CI_NAME": "sourcehut" } }, { "name": "Strider CD", "constant": "STRIDER", "env": "STRIDER" }, { "name": "TaskCluster", "constant": "TASKCLUSTER", "env": [ "TASK_ID", "RUN_ID" ] }, { "name": "TeamCity", "constant": "TEAMCITY", "env": "TEAMCITY_VERSION" }, { "name": "Travis CI", "constant": "TRAVIS", "env": "TRAVIS", "pr": { "env": "TRAVIS_PULL_REQUEST", "ne": "false" } }, { "name": "Vela", "constant": "VELA", "env": "VELA", "pr": { "VELA_PULL_REQUEST": "1" } }, { "name": "Vercel", "constant": "VERCEL", "env": { "any": [ "NOW_BUILDER", "VERCEL" ] }, "pr": "VERCEL_GIT_PULL_REQUEST_ID" }, { "name": "Visual Studio App Center", "constant": "APPCENTER", "env": "APPCENTER_BUILD_ID" }, { "name": "Woodpecker", "constant": "WOODPECKER", "env": { "CI": "woodpecker" }, "pr": { "CI_BUILD_EVENT": "pull_request" } }, { "name": "Xcode Cloud", "constant": "XCODE_CLOUD", "env": "CI_XCODE_PROJECT", "pr": "CI_PULL_REQUEST_NUMBER" }, { "name": "Xcode Server", "constant": "XCODE_SERVER", "env": "XCS" } ] PK ~\Iproc-log/package.jsonnu[{ "_id": "proc-log@4.2.0", "_inBundle": true, "_location": "/npm/proc-log", "_phantomChildren": {}, "_requiredBy": [ "/npm", "/npm/@npmcli/arborist", "/npm/@npmcli/config", "/npm/@npmcli/git", "/npm/@npmcli/metavuln-calculator", "/npm/@npmcli/package-json", "/npm/@npmcli/run-script", "/npm/@sigstore/sign", "/npm/libnpmexec", "/npm/libnpmpublish", "/npm/libnpmversion", "/npm/make-fetch-happen", "/npm/npm-package-arg", "/npm/npm-profile", "/npm/npm-registry-fetch", "/npm/pacote" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/proc-log/issues" }, "description": "just emit 'log' events on the process object", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.21.3", "tap": "^16.0.1" }, "engines": { "node": "^14.17.0 || ^16.13.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/proc-log#readme", "license": "ISC", "main": "lib/index.js", "name": "proc-log", "repository": { "type": "git", "url": "git+https://github.com/npm/proc-log.git" }, "scripts": { "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "postsnap": "eslint index.js test/*.js --fix", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.21.3", "publish": true }, "version": "4.2.0" } PK ~\G74 4 proc-log/lib/index.jsnu[const META = Symbol('proc-log.meta') module.exports = { META: META, output: { LEVELS: [ 'standard', 'error', 'buffer', 'flush', ], KEYS: { standard: 'standard', error: 'error', buffer: 'buffer', flush: 'flush', }, standard: function (...args) { return process.emit('output', 'standard', ...args) }, error: function (...args) { return process.emit('output', 'error', ...args) }, buffer: function (...args) { return process.emit('output', 'buffer', ...args) }, flush: function (...args) { return process.emit('output', 'flush', ...args) }, }, log: { LEVELS: [ 'notice', 'error', 'warn', 'info', 'verbose', 'http', 'silly', 'timing', 'pause', 'resume', ], KEYS: { notice: 'notice', error: 'error', warn: 'warn', info: 'info', verbose: 'verbose', http: 'http', silly: 'silly', timing: 'timing', pause: 'pause', resume: 'resume', }, error: function (...args) { return process.emit('log', 'error', ...args) }, notice: function (...args) { return process.emit('log', 'notice', ...args) }, warn: function (...args) { return process.emit('log', 'warn', ...args) }, info: function (...args) { return process.emit('log', 'info', ...args) }, verbose: function (...args) { return process.emit('log', 'verbose', ...args) }, http: function (...args) { return process.emit('log', 'http', ...args) }, silly: function (...args) { return process.emit('log', 'silly', ...args) }, timing: function (...args) { return process.emit('log', 'timing', ...args) }, pause: function () { return process.emit('log', 'pause') }, resume: function () { return process.emit('log', 'resume') }, }, time: { LEVELS: [ 'start', 'end', ], KEYS: { start: 'start', end: 'end', }, start: function (name, fn) { process.emit('time', 'start', name) function end () { return process.emit('time', 'end', name) } if (typeof fn === 'function') { const res = fn() if (res && res.finally) { return res.finally(end) } end() return res } return end }, end: function (name) { return process.emit('time', 'end', name) }, }, input: { LEVELS: [ 'start', 'end', 'read', ], KEYS: { start: 'start', end: 'end', read: 'read', }, start: function (fn) { process.emit('input', 'start') function end () { return process.emit('input', 'end') } if (typeof fn === 'function') { const res = fn() if (res && res.finally) { return res.finally(end) } end() return res } return end }, end: function () { return process.emit('input', 'end') }, read: function (...args) { let resolve, reject const promise = new Promise((_resolve, _reject) => { resolve = _resolve reject = _reject }) process.emit('input', 'read', resolve, reject, ...args) return promise }, }, } PK ~\<proc-log/LICENSEnu[The ISC License Copyright (c) GitHub, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\ function-bind/package.jsonnu[{ "_id": "function-bind@1.1.2", "_inBundle": true, "_location": "/npm/function-bind", "_phantomChildren": {}, "_requiredBy": [ "/npm/hasown" ], "author": { "name": "Raynos", "email": "raynos2@gmail.com" }, "auto-changelog": { "output": "CHANGELOG.md", "template": "keepachangelog", "unreleased": false, "commitLimit": false, "backfillLimit": false, "hideCredit": true }, "bugs": { "url": "https://github.com/Raynos/function-bind/issues", "email": "raynos2@gmail.com" }, "contributors": [ { "name": "Raynos" }, { "name": "Jordan Harband", "url": "https://github.com/ljharb" } ], "description": "Implementation of Function.prototype.bind", "devDependencies": { "@ljharb/eslint-config": "^21.1.0", "aud": "^2.0.3", "auto-changelog": "^2.4.0", "eslint": "=8.8.0", "in-publish": "^2.0.1", "npmignore": "^0.3.0", "nyc": "^10.3.2", "safe-publish-latest": "^2.0.0", "tape": "^5.7.1" }, "funding": { "url": "https://github.com/sponsors/ljharb" }, "homepage": "https://github.com/Raynos/function-bind", "keywords": [ "function", "bind", "shim", "es5" ], "license": "MIT", "main": "index", "name": "function-bind", "publishConfig": { "ignore": [ ".github/workflows" ] }, "repository": { "type": "git", "url": "git+https://github.com/Raynos/function-bind.git" }, "scripts": { "lint": "eslint --ext=js,mjs .", "posttest": "aud --production", "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"", "prepack": "npmignore --auto --commentLines=autogenerated", "prepublish": "not-in-publish || npm run prepublishOnly", "prepublishOnly": "safe-publish-latest", "pretest": "npm run lint", "test": "npm run tests-only", "tests-only": "nyc tape 'test/**/*.js'", "version": "auto-changelog && git add CHANGELOG.md" }, "testling": { "files": "test/index.js", "browsers": [ "ie/8..latest", "firefox/16..latest", "firefox/nightly", "chrome/22..latest", "chrome/canary", "opera/12..latest", "opera/next", "safari/5.1..latest", "ipad/6.0..latest", "iphone/6.0..latest", "android-browser/4.2..latest" ] }, "version": "1.1.2" } PK ~\BG##function-bind/test/index.jsnu[// jscs:disable requireUseStrict var test = require('tape'); var functionBind = require('../implementation'); var getCurrentContext = function () { return this; }; test('functionBind is a function', function (t) { t.equal(typeof functionBind, 'function'); t.end(); }); test('non-functions', function (t) { var nonFunctions = [true, false, [], {}, 42, 'foo', NaN, /a/g]; t.plan(nonFunctions.length); for (var i = 0; i < nonFunctions.length; ++i) { try { functionBind.call(nonFunctions[i]); } catch (ex) { t.ok(ex instanceof TypeError, 'throws when given ' + String(nonFunctions[i])); } } t.end(); }); test('without a context', function (t) { t.test('binds properly', function (st) { var args, context; var namespace = { func: functionBind.call(function () { args = Array.prototype.slice.call(arguments); context = this; }) }; namespace.func(1, 2, 3); st.deepEqual(args, [1, 2, 3]); st.equal(context, getCurrentContext.call()); st.end(); }); t.test('binds properly, and still supplies bound arguments', function (st) { var args, context; var namespace = { func: functionBind.call(function () { args = Array.prototype.slice.call(arguments); context = this; }, undefined, 1, 2, 3) }; namespace.func(4, 5, 6); st.deepEqual(args, [1, 2, 3, 4, 5, 6]); st.equal(context, getCurrentContext.call()); st.end(); }); t.test('returns properly', function (st) { var args; var namespace = { func: functionBind.call(function () { args = Array.prototype.slice.call(arguments); return this; }, null) }; var context = namespace.func(1, 2, 3); st.equal(context, getCurrentContext.call(), 'returned context is namespaced context'); st.deepEqual(args, [1, 2, 3], 'passed arguments are correct'); st.end(); }); t.test('returns properly with bound arguments', function (st) { var args; var namespace = { func: functionBind.call(function () { args = Array.prototype.slice.call(arguments); return this; }, null, 1, 2, 3) }; var context = namespace.func(4, 5, 6); st.equal(context, getCurrentContext.call(), 'returned context is namespaced context'); st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'passed arguments are correct'); st.end(); }); t.test('called as a constructor', function (st) { var thunkify = function (value) { return function () { return value; }; }; st.test('returns object value', function (sst) { var expectedReturnValue = [1, 2, 3]; var Constructor = functionBind.call(thunkify(expectedReturnValue), null); var result = new Constructor(); sst.equal(result, expectedReturnValue); sst.end(); }); st.test('does not return primitive value', function (sst) { var Constructor = functionBind.call(thunkify(42), null); var result = new Constructor(); sst.notEqual(result, 42); sst.end(); }); st.test('object from bound constructor is instance of original and bound constructor', function (sst) { var A = function (x) { this.name = x || 'A'; }; var B = functionBind.call(A, null, 'B'); var result = new B(); sst.ok(result instanceof B, 'result is instance of bound constructor'); sst.ok(result instanceof A, 'result is instance of original constructor'); sst.end(); }); st.end(); }); t.end(); }); test('with a context', function (t) { t.test('with no bound arguments', function (st) { var args, context; var boundContext = {}; var namespace = { func: functionBind.call(function () { args = Array.prototype.slice.call(arguments); context = this; }, boundContext) }; namespace.func(1, 2, 3); st.equal(context, boundContext, 'binds a context properly'); st.deepEqual(args, [1, 2, 3], 'supplies passed arguments'); st.end(); }); t.test('with bound arguments', function (st) { var args, context; var boundContext = {}; var namespace = { func: functionBind.call(function () { args = Array.prototype.slice.call(arguments); context = this; }, boundContext, 1, 2, 3) }; namespace.func(4, 5, 6); st.equal(context, boundContext, 'binds a context properly'); st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'supplies bound and passed arguments'); st.end(); }); t.test('returns properly', function (st) { var boundContext = {}; var args; var namespace = { func: functionBind.call(function () { args = Array.prototype.slice.call(arguments); return this; }, boundContext) }; var context = namespace.func(1, 2, 3); st.equal(context, boundContext, 'returned context is bound context'); st.notEqual(context, getCurrentContext.call(), 'returned context is not lexical context'); st.deepEqual(args, [1, 2, 3], 'passed arguments are correct'); st.end(); }); t.test('returns properly with bound arguments', function (st) { var boundContext = {}; var args; var namespace = { func: functionBind.call(function () { args = Array.prototype.slice.call(arguments); return this; }, boundContext, 1, 2, 3) }; var context = namespace.func(4, 5, 6); st.equal(context, boundContext, 'returned context is bound context'); st.notEqual(context, getCurrentContext.call(), 'returned context is not lexical context'); st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'passed arguments are correct'); st.end(); }); t.test('passes the correct arguments when called as a constructor', function (st) { var expected = { name: 'Correct' }; var namespace = { Func: functionBind.call(function (arg) { return arg; }, { name: 'Incorrect' }) }; var returned = new namespace.Func(expected); st.equal(returned, expected, 'returns the right arg when called as a constructor'); st.end(); }); t.test('has the new instance\'s context when called as a constructor', function (st) { var actualContext; var expectedContext = { foo: 'bar' }; var namespace = { Func: functionBind.call(function () { actualContext = this; }, expectedContext) }; var result = new namespace.Func(); st.equal(result instanceof namespace.Func, true); st.notEqual(actualContext, expectedContext); st.end(); }); t.end(); }); test('bound function length', function (t) { t.test('sets a correct length without thisArg', function (st) { var subject = functionBind.call(function (a, b, c) { return a + b + c; }); st.equal(subject.length, 3); st.equal(subject(1, 2, 3), 6); st.end(); }); t.test('sets a correct length with thisArg', function (st) { var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}); st.equal(subject.length, 3); st.equal(subject(1, 2, 3), 6); st.end(); }); t.test('sets a correct length without thisArg and first argument', function (st) { var subject = functionBind.call(function (a, b, c) { return a + b + c; }, undefined, 1); st.equal(subject.length, 2); st.equal(subject(2, 3), 6); st.end(); }); t.test('sets a correct length with thisArg and first argument', function (st) { var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}, 1); st.equal(subject.length, 2); st.equal(subject(2, 3), 6); st.end(); }); t.test('sets a correct length without thisArg and too many arguments', function (st) { var subject = functionBind.call(function (a, b, c) { return a + b + c; }, undefined, 1, 2, 3, 4); st.equal(subject.length, 0); st.equal(subject(), 6); st.end(); }); t.test('sets a correct length with thisArg and too many arguments', function (st) { var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}, 1, 2, 3, 4); st.equal(subject.length, 0); st.equal(subject(), 6); st.end(); }); }); PK ~\Ofunction-bind/LICENSEnu[Copyright (c) 2013 Raynos. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\A- ~~function-bind/index.jsnu['use strict'; var implementation = require('./implementation'); module.exports = Function.prototype.bind || implementation; PK ~\Ufunction-bind/implementation.jsnu['use strict'; /* eslint no-invalid-this: 1 */ var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; var toStr = Object.prototype.toString; var max = Math.max; var funcType = '[object Function]'; var concatty = function concatty(a, b) { var arr = []; for (var i = 0; i < a.length; i += 1) { arr[i] = a[i]; } for (var j = 0; j < b.length; j += 1) { arr[j + a.length] = b[j]; } return arr; }; var slicy = function slicy(arrLike, offset) { var arr = []; for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) { arr[j] = arrLike[i]; } return arr; }; var joiny = function (arr, joiner) { var str = ''; for (var i = 0; i < arr.length; i += 1) { str += arr[i]; if (i + 1 < arr.length) { str += joiner; } } return str; }; module.exports = function bind(that) { var target = this; if (typeof target !== 'function' || toStr.apply(target) !== funcType) { throw new TypeError(ERROR_MESSAGE + target); } var args = slicy(arguments, 1); var bound; var binder = function () { if (this instanceof bound) { var result = target.apply( this, concatty(args, arguments) ); if (Object(result) === result) { return result; } return this; } return target.apply( that, concatty(args, arguments) ); }; var boundLength = max(0, target.length - args.length); var boundArgs = []; for (var i = 0; i < boundLength; i++) { boundArgs[i] = '$' + i; } bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder); if (target.prototype) { var Empty = function Empty() {}; Empty.prototype = target.prototype; bound.prototype = new Empty(); Empty.prototype = null; } return bound; }; PK ~\FGnnaggregate-error/package.jsonnu[{ "_id": "aggregate-error@3.1.0", "_inBundle": true, "_location": "/npm/aggregate-error", "_phantomChildren": {}, "_requiredBy": [ "/npm/p-map" ], "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "bugs": { "url": "https://github.com/sindresorhus/aggregate-error/issues" }, "dependencies": { "clean-stack": "^2.0.0", "indent-string": "^4.0.0" }, "description": "Create an error from multiple errors", "devDependencies": { "ava": "^2.4.0", "tsd": "^0.7.1", "xo": "^0.25.3" }, "engines": { "node": ">=8" }, "files": [ "index.js", "index.d.ts" ], "homepage": "https://github.com/sindresorhus/aggregate-error#readme", "keywords": [ "aggregate", "error", "combine", "multiple", "many", "collection", "iterable", "iterator" ], "license": "MIT", "name": "aggregate-error", "repository": { "type": "git", "url": "git+https://github.com/sindresorhus/aggregate-error.git" }, "scripts": { "test": "xo && ava && tsd" }, "version": "3.1.0" } PK ~\>aggregate-error/index.jsnu['use strict'; const indentString = require('indent-string'); const cleanStack = require('clean-stack'); const cleanInternalStack = stack => stack.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g, ''); class AggregateError extends Error { constructor(errors) { if (!Array.isArray(errors)) { throw new TypeError(`Expected input to be an Array, got ${typeof errors}`); } errors = [...errors].map(error => { if (error instanceof Error) { return error; } if (error !== null && typeof error === 'object') { // Handle plain error objects with message property and/or possibly other metadata return Object.assign(new Error(error.message), error); } return new Error(error); }); let message = errors .map(error => { // The `stack` property is not standardized, so we can't assume it exists return typeof error.stack === 'string' ? cleanInternalStack(cleanStack(error.stack)) : String(error); }) .join('\n'); message = '\n' + indentString(message, 4); super(message); this.name = 'AggregateError'; Object.defineProperty(this, '_errors', {value: errors}); } * [Symbol.iterator]() { for (const error of this._errors) { yield error; } } } module.exports = AggregateError; PK ~\E}UUaggregate-error/licensenu[MIT License Copyright (c) Sindre Sorhus (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\hT^^!@npmcli/package-json/package.jsonnu[{ "_id": "@npmcli/package-json@5.1.1", "_inBundle": true, "_location": "/npm/@npmcli/package-json", "_phantomChildren": {}, "_requiredBy": [ "/npm", "/npm/@npmcli/arborist", "/npm/@npmcli/run-script", "/npm/init-package-json", "/npm/pacote" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/package-json/issues" }, "dependencies": { "@npmcli/git": "^5.0.0", "glob": "^10.2.2", "hosted-git-info": "^7.0.0", "json-parse-even-better-errors": "^3.0.0", "normalize-package-data": "^6.0.0", "proc-log": "^4.0.0", "semver": "^7.5.3" }, "description": "Programmatic API to update package.json", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.22.0", "read-package-json": "^7.0.0", "read-package-json-fast": "^3.0.2", "tap": "^16.0.1" }, "engines": { "node": "^16.14.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/package-json#readme", "keywords": [ "npm", "oss" ], "license": "ISC", "main": "lib/index.js", "name": "@npmcli/package-json", "repository": { "type": "git", "url": "git+https://github.com/npm/package-json.git" }, "scripts": { "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "postsnap": "npm run lintfix --", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.22.0", "publish": "true" }, "version": "5.1.1" } PK ~\,"a̘*@npmcli/package-json/lib/update-scripts.jsnu[const updateScripts = ({ content, originalContent = {} }) => { const newScripts = content.scripts if (!newScripts) { return originalContent } // validate scripts content being appended const hasInvalidScripts = () => Object.entries(newScripts) .some(([key, value]) => typeof key !== 'string' || typeof value !== 'string') if (hasInvalidScripts()) { throw Object.assign( new TypeError( 'package.json scripts should be a key-value pair of strings.'), { code: 'ESCRIPTSINVALID' } ) } return { ...originalContent, scripts: { ...newScripts, }, } } module.exports = updateScripts PK ~\j!rr-@npmcli/package-json/lib/update-workspaces.jsnu[const updateWorkspaces = ({ content, originalContent = {} }) => { const newWorkspaces = content.workspaces if (!newWorkspaces) { return originalContent } // validate workspaces content being appended const hasInvalidWorkspaces = () => newWorkspaces.some(w => !(typeof w === 'string')) if (!newWorkspaces.length || hasInvalidWorkspaces()) { throw Object.assign( new TypeError('workspaces should be an array of strings.'), { code: 'EWORKSPACESINVALID' } ) } return { ...originalContent, workspaces: [ ...newWorkspaces, ], } } module.exports = updateWorkspaces PK ~\#Ͷ/@npmcli/package-json/lib/update-dependencies.jsnu[const depTypes = new Set([ 'dependencies', 'optionalDependencies', 'devDependencies', 'peerDependencies', ]) // sort alphabetically all types of deps for a given package const orderDeps = (content) => { for (const type of depTypes) { if (content && content[type]) { content[type] = Object.keys(content[type]) .sort((a, b) => a.localeCompare(b, 'en')) .reduce((res, key) => { res[key] = content[type][key] return res }, {}) } } return content } const updateDependencies = ({ content, originalContent }) => { const pkg = orderDeps({ ...content, }) // optionalDependencies don't need to be repeated in two places if (pkg.dependencies) { if (pkg.optionalDependencies) { for (const name of Object.keys(pkg.optionalDependencies)) { delete pkg.dependencies[name] } } } const result = { ...originalContent } // loop through all types of dependencies and update package json pkg for (const type of depTypes) { if (pkg[type]) { result[type] = pkg[type] } // prune empty type props from resulting object const emptyDepType = pkg[type] && typeof pkg === 'object' && Object.keys(pkg[type]).length === 0 if (emptyDepType) { delete result[type] } } // if original package.json had dep in peerDeps AND deps, preserve that. const { dependencies: origProd, peerDependencies: origPeer } = originalContent || {} const { peerDependencies: newPeer } = result if (origProd && origPeer && newPeer) { // we have original prod/peer deps, and new peer deps // copy over any that were in both in the original for (const name of Object.keys(origPeer)) { if (origProd[name] !== undefined && newPeer[name] !== undefined) { result.dependencies = result.dependencies || {} result.dependencies[name] = newPeer[name] } } } return result } updateDependencies.knownKeys = depTypes module.exports = updateDependencies PK ~\V_0!@npmcli/package-json/lib/index.jsnu[const { readFile, writeFile } = require('fs/promises') const { resolve } = require('path') const updateDeps = require('./update-dependencies.js') const updateScripts = require('./update-scripts.js') const updateWorkspaces = require('./update-workspaces.js') const normalize = require('./normalize.js') const parseJSON = require('json-parse-even-better-errors') // a list of handy specialized helper functions that take // care of special cases that are handled by the npm cli const knownSteps = new Set([ updateDeps, updateScripts, updateWorkspaces, ]) // list of all keys that are handled by "knownSteps" helpers const knownKeys = new Set([ ...updateDeps.knownKeys, 'scripts', 'workspaces', ]) class PackageJson { static normalizeSteps = Object.freeze([ '_id', '_attributes', 'bundledDependencies', 'bundleDependencies', 'optionalDedupe', 'scripts', 'funding', 'bin', ]) // npm pkg fix static fixSteps = Object.freeze([ 'binRefs', 'bundleDependencies', 'bundleDependenciesFalse', 'fixNameField', 'fixVersionField', 'fixRepositoryField', 'fixDependencies', 'devDependencies', 'scriptpath', ]) static prepareSteps = Object.freeze([ '_id', '_attributes', 'bundledDependencies', 'bundleDependencies', 'bundleDependenciesDeleteFalse', 'gypfile', 'serverjs', 'scriptpath', 'authors', 'readme', 'mans', 'binDir', 'gitHead', 'fillTypes', 'normalizeData', 'binRefs', ]) // create a new empty package.json, so we can save at the given path even // though we didn't start from a parsed file static async create (path, opts = {}) { const p = new PackageJson() await p.create(path) if (opts.data) { return p.update(opts.data) } return p } // Loads a package.json at given path and JSON parses static async load (path, opts = {}) { const p = new PackageJson() // Avoid try/catch if we aren't going to create if (!opts.create) { return p.load(path) } try { return await p.load(path) } catch (err) { if (!err.message.startsWith('Could not read package.json')) { throw err } return await p.create(path) } } // npm pkg fix static async fix (path, opts) { const p = new PackageJson() await p.load(path, true) return p.fix(opts) } // read-package-json compatible behavior static async prepare (path, opts) { const p = new PackageJson() await p.load(path, true) return p.prepare(opts) } // read-package-json-fast compatible behavior static async normalize (path, opts) { const p = new PackageJson() await p.load(path) return p.normalize(opts) } #path #manifest #readFileContent = '' #canSave = true // Load content from given path async load (path, parseIndex) { this.#path = path let parseErr try { this.#readFileContent = await readFile(this.filename, 'utf8') } catch (err) { err.message = `Could not read package.json: ${err}` if (!parseIndex) { throw err } parseErr = err } if (parseErr) { const indexFile = resolve(this.path, 'index.js') let indexFileContent try { indexFileContent = await readFile(indexFile, 'utf8') } catch (err) { throw parseErr } try { this.fromComment(indexFileContent) } catch (err) { throw parseErr } // This wasn't a package.json so prevent saving this.#canSave = false return this } return this.fromJSON(this.#readFileContent) } // Load data from a JSON string/buffer fromJSON (data) { try { this.#manifest = parseJSON(data) } catch (err) { err.message = `Invalid package.json: ${err}` throw err } return this } fromContent (data) { this.#manifest = data this.#canSave = false return this } // Load data from a comment // /**package { "name": "foo", "version": "1.2.3", ... } **/ fromComment (data) { data = data.split(/^\/\*\*package(?:\s|$)/m) if (data.length < 2) { throw new Error('File has no package in comments') } data = data[1] data = data.split(/\*\*\/$/m) if (data.length < 2) { throw new Error('File has no package in comments') } data = data[0] data = data.replace(/^\s*\*/mg, '') this.#manifest = parseJSON(data) return this } get content () { return this.#manifest } get path () { return this.#path } get filename () { if (this.path) { return resolve(this.path, 'package.json') } return undefined } create (path) { this.#path = path this.#manifest = {} return this } // This should be the ONLY way to set content in the manifest update (content) { if (!this.content) { throw new Error('Can not update without content. Please `load` or `create`') } for (const step of knownSteps) { this.#manifest = step({ content, originalContent: this.content }) } // unknown properties will just be overwitten for (const [key, value] of Object.entries(content)) { if (!knownKeys.has(key)) { this.content[key] = value } } return this } async save () { if (!this.#canSave) { throw new Error('No package.json to save to') } const { [Symbol.for('indent')]: indent, [Symbol.for('newline')]: newline, } = this.content const format = indent === undefined ? ' ' : indent const eol = newline === undefined ? '\n' : newline const fileContent = `${ JSON.stringify(this.content, null, format) }\n` .replace(/\n/g, eol) if (fileContent.trim() !== this.#readFileContent.trim()) { return await writeFile(this.filename, fileContent) } } async normalize (opts = {}) { if (!opts.steps) { opts.steps = this.constructor.normalizeSteps } await normalize(this, opts) return this } async prepare (opts = {}) { if (!opts.steps) { opts.steps = this.constructor.prepareSteps } await normalize(this, opts) return this } async fix (opts = {}) { // This one is not overridable opts.steps = this.constructor.fixSteps await normalize(this, opts) return this } } module.exports = PackageJson PK ~\MM%@npmcli/package-json/lib/normalize.jsnu[const valid = require('semver/functions/valid') const clean = require('semver/functions/clean') const fs = require('fs/promises') const path = require('path') const { log } = require('proc-log') /** * @type {import('hosted-git-info')} */ let _hostedGitInfo function lazyHostedGitInfo () { if (!_hostedGitInfo) { _hostedGitInfo = require('hosted-git-info') } return _hostedGitInfo } /** * @type {import('glob').glob} */ let _glob function lazyLoadGlob () { if (!_glob) { _glob = require('glob').glob } return _glob } // used to be npm-normalize-package-bin function normalizePackageBin (pkg, changes) { if (pkg.bin) { if (typeof pkg.bin === 'string' && pkg.name) { changes?.push('"bin" was converted to an object') pkg.bin = { [pkg.name]: pkg.bin } } else if (Array.isArray(pkg.bin)) { changes?.push('"bin" was converted to an object') pkg.bin = pkg.bin.reduce((acc, k) => { acc[path.basename(k)] = k return acc }, {}) } if (typeof pkg.bin === 'object') { for (const binKey in pkg.bin) { if (typeof pkg.bin[binKey] !== 'string') { delete pkg.bin[binKey] changes?.push(`removed invalid "bin[${binKey}]"`) continue } const base = path.basename(secureAndUnixifyPath(binKey)) if (!base) { delete pkg.bin[binKey] changes?.push(`removed invalid "bin[${binKey}]"`) continue } const binTarget = secureAndUnixifyPath(pkg.bin[binKey]) if (!binTarget) { delete pkg.bin[binKey] changes?.push(`removed invalid "bin[${binKey}]"`) continue } if (base !== binKey) { delete pkg.bin[binKey] changes?.push(`"bin[${binKey}]" was renamed to "bin[${base}]"`) } if (binTarget !== pkg.bin[binKey]) { changes?.push(`"bin[${base}]" script name was cleaned`) } pkg.bin[base] = binTarget } if (Object.keys(pkg.bin).length === 0) { changes?.push('empty "bin" was removed') delete pkg.bin } return pkg } } delete pkg.bin } function normalizePackageMan (pkg, changes) { if (pkg.man) { const mans = [] for (const man of (Array.isArray(pkg.man) ? pkg.man : [pkg.man])) { if (typeof man !== 'string') { changes?.push(`removed invalid "man [${man}]"`) } else { mans.push(secureAndUnixifyPath(man)) } } if (!mans.length) { changes?.push('empty "man" was removed') } else { pkg.man = mans return pkg } } delete pkg.man } function isCorrectlyEncodedName (spec) { return !spec.match(/[/@\s+%:]/) && spec === encodeURIComponent(spec) } function isValidScopedPackageName (spec) { if (spec.charAt(0) !== '@') { return false } const rest = spec.slice(1).split('/') if (rest.length !== 2) { return false } return rest[0] && rest[1] && rest[0] === encodeURIComponent(rest[0]) && rest[1] === encodeURIComponent(rest[1]) } function unixifyPath (ref) { return ref.replace(/\\|:/g, '/') } function securePath (ref) { const secured = path.join('.', path.join('/', unixifyPath(ref))) return secured.startsWith('.') ? '' : secured } function secureAndUnixifyPath (ref) { return unixifyPath(securePath(ref)) } // We don't want the `changes` array in here by default because this is a hot // path for parsing packuments during install. So the calling method passes it // in if it wants to track changes. const normalize = async (pkg, { strict, steps, root, changes, allowLegacyCase }) => { if (!pkg.content) { throw new Error('Can not normalize without content') } const data = pkg.content const scripts = data.scripts || {} const pkgId = `${data.name ?? ''}@${data.version ?? ''}` // name and version are load bearing so we have to clean them up first if (steps.includes('fixNameField') || steps.includes('normalizeData')) { if (!data.name && !strict) { changes?.push('Missing "name" field was set to an empty string') data.name = '' } else { if (typeof data.name !== 'string') { throw new Error('name field must be a string.') } if (!strict) { const name = data.name.trim() if (data.name !== name) { changes?.push(`Whitespace was trimmed from "name"`) data.name = name } } if (data.name.startsWith('.') || !(isValidScopedPackageName(data.name) || isCorrectlyEncodedName(data.name)) || (strict && (!allowLegacyCase) && data.name !== data.name.toLowerCase()) || data.name.toLowerCase() === 'node_modules' || data.name.toLowerCase() === 'favicon.ico') { throw new Error('Invalid name: ' + JSON.stringify(data.name)) } } } if (steps.includes('fixVersionField') || steps.includes('normalizeData')) { // allow "loose" semver 1.0 versions in non-strict mode // enforce strict semver 2.0 compliance in strict mode const loose = !strict if (!data.version) { data.version = '' } else { if (!valid(data.version, loose)) { throw new Error(`Invalid version: "${data.version}"`) } const version = clean(data.version, loose) if (version !== data.version) { changes?.push(`"version" was cleaned and set to "${version}"`) data.version = version } } } // remove attributes that start with "_" if (steps.includes('_attributes')) { for (const key in data) { if (key.startsWith('_')) { changes?.push(`"${key}" was removed`) delete pkg.content[key] } } } // build the "_id" attribute if (steps.includes('_id')) { if (data.name && data.version) { changes?.push(`"_id" was set to ${pkgId}`) data._id = pkgId } } // fix bundledDependencies typo // normalize bundleDependencies if (steps.includes('bundledDependencies')) { if (data.bundleDependencies === undefined && data.bundledDependencies !== undefined) { data.bundleDependencies = data.bundledDependencies } changes?.push(`Deleted incorrect "bundledDependencies"`) delete data.bundledDependencies } // expand "bundleDependencies: true or translate from object" if (steps.includes('bundleDependencies')) { const bd = data.bundleDependencies if (bd === false && !steps.includes('bundleDependenciesDeleteFalse')) { changes?.push(`"bundleDependencies" was changed from "false" to "[]"`) data.bundleDependencies = [] } else if (bd === true) { changes?.push(`"bundleDependencies" was auto-populated from "dependencies"`) data.bundleDependencies = Object.keys(data.dependencies || {}) } else if (bd && typeof bd === 'object') { if (!Array.isArray(bd)) { changes?.push(`"bundleDependencies" was changed from an object to an array`) data.bundleDependencies = Object.keys(bd) } } else if ('bundleDependencies' in data) { changes?.push(`"bundleDependencies" was removed`) delete data.bundleDependencies } } // it was once common practice to list deps both in optionalDependencies and // in dependencies, to support npm versions that did not know about // optionalDependencies. This is no longer a relevant need, so duplicating // the deps in two places is unnecessary and excessive. if (steps.includes('optionalDedupe')) { if (data.dependencies && data.optionalDependencies && typeof data.optionalDependencies === 'object') { for (const name in data.optionalDependencies) { changes?.push(`optionalDependencies."${name}" was removed`) delete data.dependencies[name] } if (!Object.keys(data.dependencies).length) { changes?.push(`Empty "optionalDependencies" was removed`) delete data.dependencies } } } // add "install" attribute if any "*.gyp" files exist if (steps.includes('gypfile')) { if (!scripts.install && !scripts.preinstall && data.gypfile !== false) { const files = await lazyLoadGlob()('*.gyp', { cwd: pkg.path }) if (files.length) { scripts.install = 'node-gyp rebuild' data.scripts = scripts data.gypfile = true changes?.push(`"scripts.install" was set to "node-gyp rebuild"`) changes?.push(`"gypfile" was set to "true"`) } } } // add "start" attribute if "server.js" exists if (steps.includes('serverjs') && !scripts.start) { try { await fs.access(path.join(pkg.path, 'server.js')) scripts.start = 'node server.js' data.scripts = scripts changes?.push('"scripts.start" was set to "node server.js"') } catch { // do nothing } } // strip "node_modules/.bin" from scripts entries // remove invalid scripts entries (non-strings) if ((steps.includes('scripts') || steps.includes('scriptpath')) && data.scripts !== undefined) { const spre = /^(\.[/\\])?node_modules[/\\].bin[\\/]/ if (typeof data.scripts === 'object') { for (const name in data.scripts) { if (typeof data.scripts[name] !== 'string') { delete data.scripts[name] changes?.push(`Invalid scripts."${name}" was removed`) } else if (steps.includes('scriptpath') && spre.test(data.scripts[name])) { data.scripts[name] = data.scripts[name].replace(spre, '') changes?.push(`scripts entry "${name}" was fixed to remove node_modules/.bin reference`) } } } else { changes?.push(`Removed invalid "scripts"`) delete data.scripts } } if (steps.includes('funding')) { if (data.funding && typeof data.funding === 'string') { data.funding = { url: data.funding } changes?.push(`"funding" was changed to an object with a url attribute`) } } // populate "authors" attribute if (steps.includes('authors') && !data.contributors) { try { const authorData = await fs.readFile(path.join(pkg.path, 'AUTHORS'), 'utf8') const authors = authorData.split(/\r?\n/g) .map(line => line.replace(/^\s*#.*$/, '').trim()) .filter(line => line) data.contributors = authors changes?.push('"contributors" was auto-populated with the contents of the "AUTHORS" file') } catch { // do nothing } } // populate "readme" attribute if (steps.includes('readme') && !data.readme) { const mdre = /\.m?a?r?k?d?o?w?n?$/i const files = await lazyLoadGlob()('{README,README.*}', { cwd: pkg.path, nocase: true, mark: true, }) let readmeFile for (const file of files) { // don't accept directories. if (!file.endsWith(path.sep)) { if (file.match(mdre)) { readmeFile = file break } if (file.endsWith('README')) { readmeFile = file } } } if (readmeFile) { const readmeData = await fs.readFile(path.join(pkg.path, readmeFile), 'utf8') data.readme = readmeData data.readmeFilename = readmeFile changes?.push(`"readme" was set to the contents of ${readmeFile}`) changes?.push(`"readmeFilename" was set to ${readmeFile}`) } if (!data.readme) { // this.warn('missingReadme') data.readme = 'ERROR: No README data found!' } } // expand directories.man if (steps.includes('mans')) { if (data.directories?.man && !data.man) { const manDir = secureAndUnixifyPath(data.directories.man) const cwd = path.resolve(pkg.path, manDir) const files = await lazyLoadGlob()('**/*.[0-9]', { cwd }) data.man = files.map(man => path.relative(pkg.path, path.join(cwd, man)).split(path.sep).join('/') ) } normalizePackageMan(data, changes) } if (steps.includes('bin') || steps.includes('binDir') || steps.includes('binRefs')) { normalizePackageBin(data, changes) } // expand "directories.bin" if (steps.includes('binDir') && data.directories?.bin && !data.bin) { const binsDir = path.resolve(pkg.path, securePath(data.directories.bin)) const bins = await lazyLoadGlob()('**', { cwd: binsDir }) data.bin = bins.reduce((acc, binFile) => { if (binFile && !binFile.startsWith('.')) { const binName = path.basename(binFile) acc[binName] = path.join(data.directories.bin, binFile) } return acc }, {}) // *sigh* normalizePackageBin(data, changes) } // populate "gitHead" attribute if (steps.includes('gitHead') && !data.gitHead) { const git = require('@npmcli/git') const gitRoot = await git.find({ cwd: pkg.path, root }) let head if (gitRoot) { try { head = await fs.readFile(path.resolve(gitRoot, '.git/HEAD'), 'utf8') } catch (err) { // do nothing } } let headData if (head) { if (head.startsWith('ref: ')) { const headRef = head.replace(/^ref: /, '').trim() const headFile = path.resolve(gitRoot, '.git', headRef) try { headData = await fs.readFile(headFile, 'utf8') headData = headData.replace(/^ref: /, '').trim() } catch (err) { // do nothing } if (!headData) { const packFile = path.resolve(gitRoot, '.git/packed-refs') try { let refs = await fs.readFile(packFile, 'utf8') if (refs) { refs = refs.split('\n') for (let i = 0; i < refs.length; i++) { const match = refs[i].match(/^([0-9a-f]{40}) (.+)$/) if (match && match[2].trim() === headRef) { headData = match[1] break } } } } catch { // do nothing } } } else { headData = head.trim() } } if (headData) { data.gitHead = headData } } // populate "types" attribute if (steps.includes('fillTypes')) { const index = data.main || 'index.js' if (typeof index !== 'string') { throw new TypeError('The "main" attribute must be of type string.') } // TODO exports is much more complicated than this in verbose format // We need to support for instance // "exports": { // ".": [ // { // "default": "./lib/npm.js" // }, // "./lib/npm.js" // ], // "./package.json": "./package.json" // }, // as well as conditional exports // if (data.exports && typeof data.exports === 'string') { // index = data.exports // } // if (data.exports && data.exports['.']) { // index = data.exports['.'] // if (typeof index !== 'string') { // } // } const extless = path.join(path.dirname(index), path.basename(index, path.extname(index))) const dts = `./${extless}.d.ts` const hasDTSFields = 'types' in data || 'typings' in data if (!hasDTSFields) { try { await fs.access(path.join(pkg.path, dts)) data.types = dts.split(path.sep).join('/') } catch { // do nothing } } } // "normalizeData" from "read-package-json", which was just a call through to // "normalize-package-data". We only call the "fixer" functions because // outside of that it was also clobbering _id (which we already conditionally // do) and also adding the gypfile script (which we also already // conditionally do) // Some steps are isolated so we can do a limited subset of these in `fix` if (steps.includes('fixRepositoryField') || steps.includes('normalizeData')) { if (data.repositories) { /* eslint-disable-next-line max-len */ changes?.push(`"repository" was set to the first entry in "repositories" (${data.repository})`) data.repository = data.repositories[0] } if (data.repository) { if (typeof data.repository === 'string') { changes?.push('"repository" was changed from a string to an object') data.repository = { type: 'git', url: data.repository, } } if (data.repository.url) { const hosted = lazyHostedGitInfo().fromUrl(data.repository.url) let r if (hosted) { if (hosted.getDefaultRepresentation() === 'shortcut') { r = hosted.https() } else { r = hosted.toString() } if (r !== data.repository.url) { changes?.push(`"repository.url" was normalized to "${r}"`) data.repository.url = r } } } } } if (steps.includes('fixDependencies') || steps.includes('normalizeData')) { // peerDependencies? // devDependencies is meaningless here, it's ignored on an installed package for (const type of ['dependencies', 'devDependencies', 'optionalDependencies']) { if (data[type]) { let secondWarning = true if (typeof data[type] === 'string') { changes?.push(`"${type}" was converted from a string into an object`) data[type] = data[type].trim().split(/[\n\r\s\t ,]+/) secondWarning = false } if (Array.isArray(data[type])) { if (secondWarning) { changes?.push(`"${type}" was converted from an array into an object`) } const o = {} for (const d of data[type]) { if (typeof d === 'string') { const dep = d.trim().split(/(:?[@\s><=])/) const dn = dep.shift() const dv = dep.join('').replace(/^@/, '').trim() o[dn] = dv } } data[type] = o } } } // normalize-package-data used to put optional dependencies BACK into // dependencies here, we no longer do this for (const deps of ['dependencies', 'devDependencies']) { if (deps in data) { if (!data[deps] || typeof data[deps] !== 'object') { changes?.push(`Removed invalid "${deps}"`) delete data[deps] } else { for (const d in data[deps]) { const r = data[deps][d] if (typeof r !== 'string') { changes?.push(`Removed invalid "${deps}.${d}"`) delete data[deps][d] } const hosted = lazyHostedGitInfo().fromUrl(data[deps][d])?.toString() if (hosted && hosted !== data[deps][d]) { changes?.push(`Normalized git reference to "${deps}.${d}"`) data[deps][d] = hosted.toString() } } } } } } if (steps.includes('normalizeData')) { const legacyFixer = require('normalize-package-data/lib/fixer.js') const legacyMakeWarning = require('normalize-package-data/lib/make_warning.js') legacyFixer.warn = function () { changes?.push(legacyMakeWarning.apply(null, arguments)) } const legacySteps = [ 'fixDescriptionField', 'fixModulesField', 'fixFilesField', 'fixManField', 'fixBugsField', 'fixKeywordsField', 'fixBundleDependenciesField', 'fixHomepageField', 'fixReadmeField', 'fixLicenseField', 'fixPeople', 'fixTypos', ] for (const legacyStep of legacySteps) { legacyFixer[legacyStep](data) } } // Warn if the bin references don't point to anything. This might be better // in normalize-package-data if it had access to the file path. if (steps.includes('binRefs') && data.bin instanceof Object) { for (const key in data.bin) { try { await fs.access(path.resolve(pkg.path, data.bin[key])) } catch { log.warn('package-json', pkgId, `No bin file found at ${data.bin[key]}`) // XXX: should a future breaking change delete bin entries that cannot be accessed? } } } } module.exports = normalize PK ~\)xU1@npmcli/package-json/LICENSEnu[ISC License Copyright GitHub Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND NPM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NPM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\ewHH(@npmcli/metavuln-calculator/package.jsonnu[{ "_id": "@npmcli/metavuln-calculator@7.1.1", "_inBundle": true, "_location": "/npm/@npmcli/metavuln-calculator", "_phantomChildren": {}, "_requiredBy": [ "/npm/@npmcli/arborist" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/metavuln-calculator/issues" }, "dependencies": { "cacache": "^18.0.0", "json-parse-even-better-errors": "^3.0.0", "pacote": "^18.0.0", "proc-log": "^4.1.0", "semver": "^7.3.5" }, "description": "Calculate meta-vulnerabilities from package security advisories", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.22.0", "require-inject": "^1.4.4", "tap": "^16.0.1" }, "engines": { "node": "^16.14.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/metavuln-calculator#readme", "license": "ISC", "main": "lib/index.js", "name": "@npmcli/metavuln-calculator", "repository": { "type": "git", "url": "git+https://github.com/npm/metavuln-calculator.git" }, "scripts": { "eslint": "eslint", "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "postsnap": "npm run lint", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "check-coverage": true, "coverage-map": "map.js", "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.22.0", "publish": "true", "ciVersions": [ "16.14.0", "16.x", "18.0.0", "18.x" ] }, "version": "7.1.1" } PK ~\N'@npmcli/metavuln-calculator/lib/hash.jsnu[const { createHash } = require('crypto') module.exports = ({ name, source }) => createHash('sha512') .update(JSON.stringify([name, source])) .digest('base64') PK ~\~4t4t4+@npmcli/metavuln-calculator/lib/advisory.jsnu[const hash = require('./hash.js') const semver = require('semver') const semverOpt = { includePrerelease: true, loose: true } const getDepSpec = require('./get-dep-spec.js') // any fields that we don't want in the cache need to be hidden const _source = Symbol('source') const _packument = Symbol('packument') const _versionVulnMemo = Symbol('versionVulnMemo') const _updated = Symbol('updated') const _options = Symbol('options') const _specVulnMemo = Symbol('specVulnMemo') const _testVersion = Symbol('testVersion') const _testVersions = Symbol('testVersions') const _calculateRange = Symbol('calculateRange') const _markVulnerable = Symbol('markVulnerable') const _testSpec = Symbol('testSpec') class Advisory { constructor (name, source, options = {}) { this.source = source.id this[_source] = source this[_options] = options this.name = name if (!source.name) { source.name = name } this.dependency = source.name if (this.type === 'advisory') { this.title = source.title this.url = source.url } else { this.title = `Depends on vulnerable versions of ${source.name}` this.url = null } this.severity = source.severity || 'high' this.versions = [] this.vulnerableVersions = [] this.cwe = source.cwe this.cvss = source.cvss // advisories have the range, metavulns do not // if an advisory doesn't specify range, assume all are vulnerable this.range = this.type === 'advisory' ? source.vulnerable_versions || '*' : null this.id = hash(this) this[_packument] = null // memoized list of which versions are vulnerable this[_versionVulnMemo] = new Map() // memoized list of which dependency specs are vulnerable this[_specVulnMemo] = new Map() this[_updated] = false } // true if we updated from what we had in cache get updated () { return this[_updated] } get type () { return this.dependency === this.name ? 'advisory' : 'metavuln' } get packument () { return this[_packument] } // load up the data from a cache entry and a fetched packument load (cached, packument) { // basic data integrity gutcheck if (!cached || typeof cached !== 'object') { throw new TypeError('invalid cached data, expected object') } if (!packument || typeof packument !== 'object') { throw new TypeError('invalid packument data, expected object') } if (cached.id && cached.id !== this.id) { throw Object.assign(new Error('loading from incorrect cache entry'), { expected: this.id, actual: cached.id, }) } if (packument.name !== this.name) { throw Object.assign(new Error('loading from incorrect packument'), { expected: this.name, actual: packument.name, }) } if (this[_packument]) { throw new Error('advisory object already loaded') } // if we have a range from the initialization, and the cached // data has a *different* range, then we know we have to recalc. // just don't use the cached data, so we will definitely not match later if (!this.range || cached.range && cached.range === this.range) { Object.assign(this, cached) } this[_packument] = packument const pakuVersions = Object.keys(packument.versions || {}) const allVersions = new Set([...pakuVersions, ...this.versions]) const versionsAdded = [] const versionsRemoved = [] for (const v of allVersions) { if (!this.versions.includes(v)) { versionsAdded.push(v) this.versions.push(v) } else if (!pakuVersions.includes(v)) { versionsRemoved.push(v) } } // strip out any removed versions from our lists, and sort by semver this.versions = semver.sort(this.versions.filter(v => !versionsRemoved.includes(v)), semverOpt) // if no changes, then just return what we got from cache // versions added or removed always means we changed // otherwise, advisories change if the range changes, and // metavulns change if the source was updated const unchanged = this.type === 'advisory' ? this.range && this.range === cached.range : !this[_source].updated // if the underlying source changed, by an advisory updating the // range, or a source advisory being updated, then we have to re-check // otherwise, only recheck the new ones. this.vulnerableVersions = !unchanged ? [] : semver.sort(this.vulnerableVersions.filter(v => !versionsRemoved.includes(v)), semverOpt) if (unchanged && !versionsAdded.length && !versionsRemoved.length) { // nothing added or removed, nothing to do here. use the cached copy. return this } this[_updated] = true // test any versions newly added if (!unchanged || versionsAdded.length) { this[_testVersions](unchanged ? versionsAdded : this.versions) } this.vulnerableVersions = semver.sort(this.vulnerableVersions, semverOpt) // metavulns have to calculate their range, since cache is invalidated // advisories just get their range from the advisory above if (this.type === 'metavuln') { this[_calculateRange]() } return this } [_calculateRange] () { // calling semver.simplifyRange with a massive list of versions, and those // versions all concatenated with `||` is a geometric CPU explosion! // we can try to be a *little* smarter up front by doing x-y for all // contiguous version sets in the list const ranges = [] this.versions = semver.sort(this.versions, semverOpt) this.vulnerableVersions = semver.sort(this.vulnerableVersions, semverOpt) for (let v = 0, vulnVer = 0; v < this.versions.length; v++) { // figure out the vulnerable subrange const vr = [this.versions[v]] while (v < this.versions.length) { if (this.versions[v] !== this.vulnerableVersions[vulnVer]) { // we don't test prerelease versions, so just skip past it if (/-/.test(this.versions[v])) { v++ continue } break } if (vr.length > 1) { vr[1] = this.versions[v] } else { vr.push(this.versions[v]) } v++ vulnVer++ } // it'll either be just the first version, which means no overlap, // or the start and end versions, which might be the same version if (vr.length > 1) { const tail = this.versions[this.versions.length - 1] ranges.push(vr[1] === tail ? `>=${vr[0]}` : vr[0] === vr[1] ? vr[0] : vr.join(' - ')) } } const metavuln = ranges.join(' || ').trim() this.range = !metavuln ? '<0.0.0-0' : semver.simplifyRange(this.versions, metavuln, semverOpt) } // returns true if marked as vulnerable, false if ok // spec is a dependency specifier, for metavuln cases // where the version might not be in the packument. if // we have the packument and spec is not provided, then // we use the dependency version from the manifest. testVersion (version, spec = null) { const sv = String(version) if (this[_versionVulnMemo].has(sv)) { return this[_versionVulnMemo].get(sv) } const result = this[_testVersion](version, spec) if (result) { this[_markVulnerable](version) } this[_versionVulnMemo].set(sv, !!result) return result } [_markVulnerable] (version) { const sv = String(version) if (!this.vulnerableVersions.includes(sv)) { this.vulnerableVersions.push(sv) } } [_testVersion] (version, spec) { const sv = String(version) if (this.vulnerableVersions.includes(sv)) { return true } if (this.type === 'advisory') { // advisory, just test range return semver.satisfies(version, this.range, semverOpt) } // check the dependency of this version on the vulnerable dep // if we got a version that's not in the packument, fall back on // the spec provided, if possible. const mani = this[_packument]?.versions?.[version] || { dependencies: { [this.dependency]: spec, }, } if (!spec) { spec = getDepSpec(mani, this.dependency) } // no dep, no vuln if (spec === null) { return false } if (!semver.validRange(spec, semverOpt)) { // not a semver range, nothing we can hope to do about it return true } const bd = mani.bundleDependencies const bundled = bd && bd.includes(this[_source].name) // XXX if bundled, then semver.intersects() means vulnerable // else, pick a manifest and see if it can't be avoided // try to pick a version of the dep that isn't vulnerable const avoid = this[_source].range if (bundled) { return semver.intersects(spec, avoid, semverOpt) } return this[_source].testSpec(spec) } testSpec (spec) { // testing all the versions is a bit costly, and the spec tends to stay // consistent across multiple versions, so memoize this as well, in case // we're testing lots of versions. const memo = this[_specVulnMemo] if (memo.has(spec)) { return memo.get(spec) } const res = this[_testSpec](spec) memo.set(spec, res) return res } [_testSpec] (spec) { for (const v of this.versions) { const satisfies = semver.satisfies(v, spec) if (!satisfies) { continue } if (!this.testVersion(v)) { return false } } // either vulnerable, or not installable because nothing satisfied // either way, best avoided. return true } [_testVersions] (versions) { if (!versions.length) { return } // set of lists of versions const versionSets = new Set() versions = semver.sort(versions.map(v => semver.parse(v, semverOpt))) // start out with the versions grouped by major and minor let last = versions[0].major + '.' + versions[0].minor let list = [] versionSets.add(list) for (const v of versions) { const k = v.major + '.' + v.minor if (k !== last) { last = k list = [] versionSets.add(list) } list.push(v) } for (const set of versionSets) { // it's common to have version lists like: // 1.0.0 // 1.0.1-alpha.0 // 1.0.1-alpha.1 // ... // 1.0.1-alpha.999 // 1.0.1 // 1.0.2-alpha.0 // ... // 1.0.2-alpha.99 // 1.0.2 // with a huge number of prerelease versions that are not installable // anyway. // If mid has a prerelease tag, and set[0] does not, then walk it // back until we hit a non-prerelease version // If mid has a prerelease tag, and set[set.length-1] does not, // then walk it forward until we hit a version without a prerelease tag // Similarly, if the head/tail is a prerelease, but there is a non-pr // version in the set, then start there instead. let h = 0 const origHeadVuln = this.testVersion(set[h]) while (h < set.length && /-/.test(String(set[h]))) { h++ } // don't filter out the whole list! they might all be pr's if (h === set.length) { h = 0 } else if (origHeadVuln) { // if the original was vulnerable, assume so are all of these for (let hh = 0; hh < h; hh++) { this[_markVulnerable](set[hh]) } } let t = set.length - 1 const origTailVuln = this.testVersion(set[t]) while (t > h && /-/.test(String(set[t]))) { t-- } // don't filter out the whole list! might all be pr's if (t === h) { t = set.length - 1 } else if (origTailVuln) { // if original tail was vulnerable, assume these are as well for (let tt = set.length - 1; tt > t; tt--) { this[_markVulnerable](set[tt]) } } const headVuln = h === 0 ? origHeadVuln : this.testVersion(set[h]) const tailVuln = t === set.length - 1 ? origTailVuln : this.testVersion(set[t]) // if head and tail both vulnerable, whole list is thrown out if (headVuln && tailVuln) { for (let v = h; v < t; v++) { this[_markVulnerable](set[v]) } continue } // if length is 2 or 1, then we marked them all already if (t < h + 2) { continue } const mid = Math.floor(set.length / 2) const pre = set.slice(0, mid) const post = set.slice(mid) // if the parent list wasn't prereleases, then drop pr tags // from end of the pre list, and beginning of the post list, // marking as vulnerable if the midpoint item we picked is. if (!/-/.test(String(pre[0]))) { const midVuln = this.testVersion(pre[pre.length - 1]) while (/-/.test(String(pre[pre.length - 1]))) { const v = pre.pop() if (midVuln) { this[_markVulnerable](v) } } } if (!/-/.test(String(post[post.length - 1]))) { const midVuln = this.testVersion(post[0]) while (/-/.test(String(post[0]))) { const v = post.shift() if (midVuln) { this[_markVulnerable](v) } } } versionSets.add(pre) versionSets.add(post) } } } module.exports = Advisory PK ~\Kts(@npmcli/metavuln-calculator/lib/index.jsnu[// this is the public class that is used by consumers. // the Advisory class handles all the calculation, and this // class handles all the IO with the registry and cache. const pacote = require('pacote') const cacache = require('cacache') const { time } = require('proc-log') const Advisory = require('./advisory.js') const { homedir } = require('os') const jsonParse = require('json-parse-even-better-errors') const _packument = Symbol('packument') const _cachePut = Symbol('cachePut') const _cacheGet = Symbol('cacheGet') const _cacheData = Symbol('cacheData') const _packuments = Symbol('packuments') const _cache = Symbol('cache') const _options = Symbol('options') const _advisories = Symbol('advisories') const _calculate = Symbol('calculate') class Calculator { constructor (options = {}) { this[_options] = { ...options } this[_cache] = this[_options].cache || (homedir() + '/.npm/_cacache') this[_options].cache = this[_cache] this[_packuments] = new Map() this[_cacheData] = new Map() this[_advisories] = new Map() } get cache () { return this[_cache] } get options () { return { ...this[_options] } } async calculate (name, source) { const k = `security-advisory:${name}:${source.id}` if (this[_advisories].has(k)) { return this[_advisories].get(k) } const p = this[_calculate](name, source) this[_advisories].set(k, p) return p } async [_calculate] (name, source) { const k = `security-advisory:${name}:${source.id}` const timeEnd = time.start(`metavuln:calculate:${k}`) const advisory = new Advisory(name, source, this[_options]) // load packument and cached advisory const [cached, packument] = await Promise.all([ this[_cacheGet](advisory), this[_packument](name), ]) const timeEndLoad = time.start(`metavuln:load:${k}`) advisory.load(cached, packument) timeEndLoad() if (advisory.updated) { await this[_cachePut](advisory) } this[_advisories].set(k, advisory) timeEnd() return advisory } async [_cachePut] (advisory) { const { name, id } = advisory const key = `security-advisory:${name}:${id}` const timeEnd = time.start(`metavuln:cache:put:${key}`) const data = JSON.stringify(advisory) const options = { ...this[_options] } this[_cacheData].set(key, jsonParse(data)) await cacache.put(this[_cache], key, data, options).catch(() => {}) timeEnd() } async [_cacheGet] (advisory) { const { name, id } = advisory const key = `security-advisory:${name}:${id}` /* istanbul ignore if - should be impossible, since we memoize the * advisory object itself using the same key, just being cautious */ if (this[_cacheData].has(key)) { return this[_cacheData].get(key) } const timeEnd = time.start(`metavuln:cache:get:${key}`) const p = cacache.get(this[_cache], key, { ...this[_options] }) .catch(() => ({ data: '{}' })) .then(({ data }) => { data = jsonParse(data) timeEnd() this[_cacheData].set(key, data) return data }) this[_cacheData].set(key, p) return p } async [_packument] (name) { if (this[_packuments].has(name)) { return this[_packuments].get(name) } const timeEnd = time.start(`metavuln:packument:${name}`) const p = pacote.packument(name, { ...this[_options] }) .catch(() => { // presumably not something from the registry. // an empty packument will have an effective range of * return { name, versions: {}, } }) .then(paku => { timeEnd() this[_packuments].set(name, paku) return paku }) this[_packuments].set(name, p) return p } } module.exports = Calculator PK ~\  /@npmcli/metavuln-calculator/lib/get-dep-spec.jsnu[module.exports = (mani, name) => { // skip dev because that only matters at the root, // where we aren't fetching a manifest from the registry // with multiple versions anyway. const { dependencies: deps = {}, optionalDependencies: optDeps = {}, peerDependencies: peerDeps = {}, } = mani return deps && typeof deps[name] === 'string' ? deps[name] : optDeps && typeof optDeps[name] === 'string' ? optDeps[name] : peerDeps && typeof peerDeps[name] === 'string' ? peerDeps[name] : null } PK ~\.9#@npmcli/metavuln-calculator/LICENSEnu[The ISC License Copyright (c) npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\2qK K @npmcli/arborist/package.jsonnu[{ "_id": "@npmcli/arborist@7.5.3", "_inBundle": true, "_location": "/npm/@npmcli/arborist", "_phantomChildren": {}, "_requiredBy": [ "/npm", "/npm/libnpmdiff", "/npm/libnpmexec", "/npm/libnpmfund", "/npm/libnpmpack" ], "author": { "name": "GitHub Inc." }, "bin": { "arborist": "bin/index.js" }, "bugs": { "url": "https://github.com/npm/cli/issues" }, "dependencies": { "@isaacs/string-locale-compare": "^1.1.0", "@npmcli/fs": "^3.1.1", "@npmcli/installed-package-contents": "^2.1.0", "@npmcli/map-workspaces": "^3.0.2", "@npmcli/metavuln-calculator": "^7.1.1", "@npmcli/name-from-folder": "^2.0.0", "@npmcli/node-gyp": "^3.0.0", "@npmcli/package-json": "^5.1.0", "@npmcli/query": "^3.1.0", "@npmcli/redact": "^2.0.0", "@npmcli/run-script": "^8.1.0", "bin-links": "^4.0.4", "cacache": "^18.0.3", "common-ancestor-path": "^1.0.1", "hosted-git-info": "^7.0.2", "json-parse-even-better-errors": "^3.0.2", "json-stringify-nice": "^1.1.4", "lru-cache": "^10.2.2", "minimatch": "^9.0.4", "nopt": "^7.2.1", "npm-install-checks": "^6.2.0", "npm-package-arg": "^11.0.2", "npm-pick-manifest": "^9.0.1", "npm-registry-fetch": "^17.0.1", "pacote": "^18.0.6", "parse-conflict-json": "^3.0.0", "proc-log": "^4.2.0", "proggy": "^2.0.0", "promise-all-reject-late": "^1.0.0", "promise-call-limit": "^3.0.1", "read-package-json-fast": "^3.0.2", "semver": "^7.3.7", "ssri": "^10.0.6", "treeverse": "^3.0.0", "walk-up-path": "^3.0.1" }, "description": "Manage node_modules trees", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.22.0", "benchmark": "^2.1.4", "minify-registry-metadata": "^3.0.0", "nock": "^13.3.3", "tap": "^16.3.8", "tar-stream": "^3.0.0", "tcompare": "^5.0.6" }, "engines": { "node": "^16.14.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/cli#readme", "license": "ISC", "main": "lib/index.js", "name": "@npmcli/arborist", "repository": { "type": "git", "url": "git+https://github.com/npm/cli.git", "directory": "workspaces/arborist" }, "scripts": { "benchclean": "rm -rf scripts/benchmark/*/", "benchmark": "node scripts/benchmark.js", "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap", "test-proxy": "ARBORIST_TEST_PROXY=1 tap --snapshot" }, "tap": { "after": "test/fixtures/cleanup.js", "test-env": [ "LC_ALL=sk" ], "timeout": "360", "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.22.0", "content": "../../scripts/template-oss/index.js" }, "version": "7.5.3" } PK ~\ .rff!@npmcli/arborist/lib/printable.jsnu[// helper function to output a clearer visualization // of the current node and its descendents const localeCompare = require('@isaacs/string-locale-compare')('en') const util = require('node:util') const relpath = require('./relpath.js') class ArboristNode { constructor (tree, path) { this.name = tree.name if (tree.packageName && tree.packageName !== this.name) { this.packageName = tree.packageName } if (tree.version) { this.version = tree.version } this.location = tree.location this.path = tree.path if (tree.realpath !== this.path) { this.realpath = tree.realpath } if (tree.resolved !== null) { this.resolved = tree.resolved } if (tree.extraneous) { this.extraneous = true } if (tree.dev) { this.dev = true } if (tree.optional) { this.optional = true } if (tree.devOptional && !tree.dev && !tree.optional) { this.devOptional = true } if (tree.peer) { this.peer = true } if (tree.inBundle) { this.bundled = true } if (tree.inDepBundle) { this.bundler = tree.getBundler().location } if (tree.isProjectRoot) { this.isProjectRoot = true } if (tree.isWorkspace) { this.isWorkspace = true } const bd = tree.package && tree.package.bundleDependencies if (bd && bd.length) { this.bundleDependencies = bd } if (tree.inShrinkwrap) { this.inShrinkwrap = true } else if (tree.hasShrinkwrap) { this.hasShrinkwrap = true } if (tree.error) { this.error = treeError(tree.error) } if (tree.errors && tree.errors.length) { this.errors = tree.errors.map(treeError) } if (tree.overrides) { this.overrides = new Map([...tree.overrides.ruleset.values()] .map((override) => [override.key, override.value])) } // edgesOut sorted by name if (tree.edgesOut.size) { this.edgesOut = new Map([...tree.edgesOut.entries()] .sort(([a], [b]) => localeCompare(a, b)) .map(([name, edge]) => [name, new EdgeOut(edge)])) } // edgesIn sorted by location if (tree.edgesIn.size) { this.edgesIn = new Set([...tree.edgesIn] .sort((a, b) => localeCompare(a.from.location, b.from.location)) .map(edge => new EdgeIn(edge))) } if (tree.workspaces && tree.workspaces.size) { this.workspaces = new Map([...tree.workspaces.entries()] .map(([name, path]) => [name, relpath(tree.root.realpath, path)])) } // fsChildren sorted by path if (tree.fsChildren.size) { this.fsChildren = new Set([...tree.fsChildren] .sort(({ path: a }, { path: b }) => localeCompare(a, b)) .map(tree => printableTree(tree, path))) } // children sorted by name if (tree.children.size) { this.children = new Map([...tree.children.entries()] .sort(([a], [b]) => localeCompare(a, b)) .map(([name, tree]) => [name, printableTree(tree, path)])) } } } class ArboristVirtualNode extends ArboristNode { constructor (tree, path) { super(tree, path) this.sourceReference = printableTree(tree.sourceReference, path) } } class ArboristLink extends ArboristNode { constructor (tree, path) { super(tree, path) this.target = printableTree(tree.target, path) } } const treeError = ({ code, path }) => ({ code, ...(path ? { path } : {}), }) // print out edges without dumping the full node all over again // this base class will toJSON as a plain old object, but the // util.inspect() output will be a bit cleaner class Edge { constructor (edge) { this.type = edge.type this.name = edge.name this.spec = edge.rawSpec || '*' if (edge.rawSpec !== edge.spec) { this.override = edge.spec } if (edge.error) { this.error = edge.error } if (edge.peerConflicted) { this.peerConflicted = edge.peerConflicted } } } // don't care about 'from' for edges out class EdgeOut extends Edge { constructor (edge) { super(edge) this.to = edge.to && edge.to.location } [util.inspect.custom] () { return `{ ${this.type} ${this.name}@${this.spec}${ this.override ? ` overridden:${this.override}` : '' }${ this.to ? ' -> ' + this.to : '' }${ this.error ? ' ' + this.error : '' }${ this.peerConflicted ? ' peerConflicted' : '' } }` } } // don't care about 'to' for edges in class EdgeIn extends Edge { constructor (edge) { super(edge) this.from = edge.from && edge.from.location } [util.inspect.custom] () { return `{ ${this.from || '""'} ${this.type} ${this.name}@${this.spec}${ this.error ? ' ' + this.error : '' }${ this.peerConflicted ? ' peerConflicted' : '' } }` } } const printableTree = (tree, path = []) => { if (!tree) { return tree } const Cls = tree.isLink ? ArboristLink : tree.sourceReference ? ArboristVirtualNode : ArboristNode if (path.includes(tree)) { const obj = Object.create(Cls.prototype) return Object.assign(obj, { location: tree.location }) } path.push(tree) return new Cls(tree, path) } module.exports = printableTree PK ~\)@npmcli/arborist/lib/override-resolves.jsnu[function overrideResolves (resolved, opts) { const { omitLockfileRegistryResolved = false } = opts if (omitLockfileRegistryResolved) { return undefined } return resolved } module.exports = { overrideResolves } PK ~\>}jj&@npmcli/arborist/lib/spec-from-lock.jsnu[const npa = require('npm-package-arg') // extracted from npm v6 lib/install/realize-shrinkwrap-specifier.js const specFromLock = (name, lock, where) => { try { if (lock.version) { const spec = npa.resolve(name, lock.version, where) if (lock.integrity || spec.type === 'git') { return spec } } if (lock.from) { // legacy metadata includes "from", but not integrity const spec = npa.resolve(name, lock.from, where) if (spec.registry && lock.version) { return npa.resolve(name, lock.version, where) } else if (!lock.resolved) { return spec } } if (lock.resolved) { return npa.resolve(name, lock.resolved, where) } } catch { // ignore errors } try { return npa.resolve(name, lock.version, where) } catch { return {} } } module.exports = specFromLock PK ~\!@npmcli/arborist/lib/dep-valid.jsnu[// Do not rely on package._fields, so that we don't throw // false failures if a tree is generated by other clients. // Only relies on child.resolved, which MAY come from // client-specific package.json meta _fields, but most of // the time will be pulled out of a lockfile const semver = require('semver') const npa = require('npm-package-arg') const { relative } = require('node:path') const fromPath = require('./from-path.js') const depValid = (child, requested, requestor) => { // NB: we don't do much to verify 'tag' type requests. // Just verify that we got a remote resolution. Presumably, it // came from a registry and was tagged at some point. if (typeof requested === 'string') { try { // tarball/dir must have resolved to the same tgz on disk, but for // file: deps that depend on other files/dirs, we must resolve the // location based on the *requestor* file/dir, not where it ends up. // '' is equivalent to '*' requested = npa.resolve(child.name, requested || '*', fromPath(requestor, requestor.edgesOut.get(child.name))) } catch (er) { // Not invalid because the child doesn't match, but because // the spec itself is not supported. Nothing would match, // so the edge is definitely not valid and never can be. er.dependency = child.name er.requested = requested requestor.errors.push(er) return false } } // if the lockfile is super old, or hand-modified, // then it's possible to hit this state. if (!requested) { const er = new Error('Invalid dependency specifier') er.dependency = child.name er.requested = requested requestor.errors.push(er) return false } switch (requested.type) { case 'range': if (requested.fetchSpec === '*') { return true } // fallthrough case 'version': // if it's a version or a range other than '*', semver it return semver.satisfies(child.version, requested.fetchSpec, true) case 'directory': return linkValid(child, requested, requestor) case 'file': return tarballValid(child, requested, requestor) case 'alias': // check that the alias target is valid return depValid(child, requested.subSpec, requestor) case 'tag': // if it's a tag, we just verify that it has a tarball resolution // presumably, it came from the registry and was tagged at some point return child.resolved && npa(child.resolved).type === 'remote' case 'remote': // verify that we got it from the desired location return child.resolved === requested.fetchSpec case 'git': { // if it's a git type, verify that they're the same repo // // if it specifies a definite commit, then it must have the // same commit to be considered the same repo // // if it has a #semver: specifier, verify that the // version in the package is in the semver range const resRepo = npa(child.resolved || '') const resHost = resRepo.hosted const reqHost = requested.hosted const reqCommit = /^[a-fA-F0-9]{40}$/.test(requested.gitCommittish || '') const nc = { noCommittish: !reqCommit } if (!resHost) { if (resRepo.fetchSpec !== requested.fetchSpec) { return false } } else { if (reqHost?.ssh(nc) !== resHost.ssh(nc)) { return false } } if (!requested.gitRange) { return true } return semver.satisfies(child.package.version, requested.gitRange, { loose: true, }) } default: // unpossible, just being cautious break } const er = new Error('Unsupported dependency type') er.dependency = child.name er.requested = requested requestor.errors.push(er) return false } const linkValid = (child, requested, requestor) => { const isLink = !!child.isLink // if we're installing links and the node is a link, then it's invalid because we want // a real node to be there. Except for workspaces. They are always links. if (requestor.installLinks && !child.isWorkspace) { return !isLink } // directory must be a link to the specified folder return isLink && relative(child.realpath, requested.fetchSpec) === '' } const tarballValid = (child, requested) => { if (child.isLink) { return false } if (child.resolved) { return child.resolved.replace(/\\/g, '/') === `file:${requested.fetchSpec.replace(/\\/g, '/')}` } // if we have a legacy mutated package.json file. we can't be 100% // sure that it resolved to the same file, but if it was the same // request, that's a pretty good indicator of sameness. if (child.package._requested) { return child.package._requested.saveSpec === requested.saveSpec } // ok, we're probably dealing with some legacy cruft here, not much // we can do at this point unfortunately. return false } module.exports = (child, requested, accept, requestor) => depValid(child, requested, requestor) || (typeof accept === 'string' ? depValid(child, accept, requestor) : false) PK ~\"XOO!@npmcli/arborist/lib/place-dep.jsnu[// Given a dep, a node that depends on it, and the edge representing that // dependency, place the dep somewhere in the node's tree, and all of its // peer dependencies. // // Handles all of the tree updating needed to place the dep, including // removing replaced nodes, pruning now-extraneous or invalidated nodes, // and saves a set of what was placed and what needs re-evaluation as // a result. const localeCompare = require('@isaacs/string-locale-compare')('en') const { log } = require('proc-log') const { redact } = require('@npmcli/redact') const deepestNestingTarget = require('./deepest-nesting-target.js') const CanPlaceDep = require('./can-place-dep.js') const { KEEP, CONFLICT, } = CanPlaceDep const debug = require('./debug.js') const Link = require('./link.js') const gatherDepSet = require('./gather-dep-set.js') const peerEntrySets = require('./peer-entry-sets.js') class PlaceDep { constructor (options) { this.auditReport = options.auditReport this.dep = options.dep this.edge = options.edge this.explicitRequest = options.explicitRequest this.force = options.force this.installLinks = options.installLinks this.installStrategy = options.installStrategy this.legacyPeerDeps = options.legacyPeerDeps this.parent = options.parent || null this.preferDedupe = options.preferDedupe this.strictPeerDeps = options.strictPeerDeps this.updateNames = options.updateNames this.canPlace = null this.canPlaceSelf = null // XXX this only appears to be used by tests this.checks = new Map() this.children = [] this.needEvaluation = new Set() this.peerConflict = null this.placed = null this.target = null this.current = this.edge.to this.name = this.edge.name this.top = this.parent?.top || this // nothing to do if the edge is fine as it is if (this.edge.to && !this.edge.error && !this.explicitRequest && !this.updateNames.includes(this.edge.name) && !this.auditReport?.isVulnerable(this.edge.to)) { return } // walk up the tree until we hit either a top/root node, or a place // where the dep is not a peer dep. const start = this.getStartNode() for (const target of start.ancestry()) { // if the current location has a peerDep on it, then we can't place here // this is pretty rare to hit, since we always prefer deduping peers, // and the getStartNode will start us out above any peers from the // thing that depends on it. but we could hit it with something like: // // a -> (b@1, c@1) // +-- c@1 // +-- b -> PEEROPTIONAL(v) (c@2) // +-- c@2 -> (v) // // So we check if we can place v under c@2, that's fine. // Then we check under b, and can't, because of the optional peer dep. // but we CAN place it under a, so the correct thing to do is keep // walking up the tree. const targetEdge = target.edgesOut.get(this.edge.name) if (!target.isTop && targetEdge && targetEdge.peer) { continue } const cpd = new CanPlaceDep({ dep: this.dep, edge: this.edge, // note: this sets the parent's canPlace as the parent of this // canPlace, but it does NOT add this canPlace to the parent's // children. This way, we can know that it's a peer dep, and // get the top edge easily, while still maintaining the // tree of checks that factored into the original decision. parent: this.parent && this.parent.canPlace, target, preferDedupe: this.preferDedupe, explicitRequest: this.explicitRequest, }) this.checks.set(target, cpd) // It's possible that a "conflict" is a conflict among the *peers* of // a given node we're trying to place, but there actually is no current // node. Eg, // root -> (a, b) // a -> PEER(c) // b -> PEER(d) // d -> PEER(c@2) // We place (a), and get a peer of (c) along with it. // then we try to place (b), and get CONFLICT in the check, because // of the conflicting peer from (b)->(d)->(c@2). In that case, we // should treat (b) and (d) as OK, and place them in the last place // where they did not themselves conflict, and skip c@2 if conflict // is ok by virtue of being forced or not ours and not strict. if (cpd.canPlaceSelf !== CONFLICT) { this.canPlaceSelf = cpd } // we found a place this can go, along with all its peer friends. // we break when we get the first conflict if (cpd.canPlace !== CONFLICT) { this.canPlace = cpd } else { break } // if it's a load failure, just plop it in the first place attempted, // since we're going to crash the build or prune it out anyway. // but, this will frequently NOT be a successful canPlace, because // it'll have no version or other information. if (this.dep.errors.length) { break } // nest packages like npm v1 and v2 // very disk-inefficient if (this.installStrategy === 'nested') { break } // when installing globally, or just in global style, we never place // deps above the first level. if (this.installStrategy === 'shallow') { const rp = target.resolveParent if (rp && rp.isProjectRoot) { break } } } // if we can't find a target, that means that the last place checked, // and all the places before it, had a conflict. if (!this.canPlace) { // if not forced, and it's our dep, or strictPeerDeps is set, then // this is an ERESOLVE error. if (!this.force && (this.isMine || this.strictPeerDeps)) { return this.failPeerConflict() } // ok! we're gonna allow the conflict, but we should still warn // if we have a current, then we treat CONFLICT as a KEEP. // otherwise, we just skip it. Only warn on the one that actually // could not be placed somewhere. if (!this.canPlaceSelf) { this.warnPeerConflict() return } this.canPlace = this.canPlaceSelf } // now we have a target, a tree of CanPlaceDep results for the peer group, // and we are ready to go /* istanbul ignore next */ if (!this.canPlace) { debug(() => { throw new Error('canPlace not set, but trying to place in tree') }) return } const { target } = this.canPlace log.silly( 'placeDep', target.location || 'ROOT', `${this.dep.name}@${this.dep.version}`, this.canPlace.description, `for: ${this.edge.from.package._id || this.edge.from.location}`, `want: ${redact(this.edge.spec || '*')}` ) const placementType = this.canPlace.canPlace === CONFLICT ? this.canPlace.canPlaceSelf : this.canPlace.canPlace // if we're placing in the tree with --force, we can get here even though // it's a conflict. Treat it as a KEEP, but warn and move on. if (placementType === KEEP) { // this was a peerConflicted peer dep if (this.edge.peer && !this.edge.valid) { this.warnPeerConflict() } // if we get a KEEP in a update scenario, then we MAY have something // already duplicating this unnecessarily! For example: // ``` // root (dep: y@1) // +-- x (dep: y@1.1) // | +-- y@1.1.0 (replacing with 1.1.2, got KEEP at the root) // +-- y@1.1.2 (updated already from 1.0.0) // ``` // Now say we do `reify({update:['y']})`, and the latest version is // 1.1.2, which we now have in the root. We'll try to place y@1.1.2 // first in x, then in the root, ending with KEEP, because we already // have it. In that case, we ought to REMOVE the nm/x/nm/y node, because // it is an unnecessary duplicate. this.pruneDedupable(target) return } // we were told to place it here in the target, so either it does not // already exist in the tree, OR it's shadowed. // handle otherwise unresolvable dependency nesting loops by // creating a symbolic link // a1 -> b1 -> a2 -> b2 -> a1 -> ... // instead of nesting forever, when the loop occurs, create // a symbolic link to the earlier instance for (let p = target; p; p = p.resolveParent) { if (p.matches(this.dep) && !p.isTop) { this.placed = new Link({ parent: target, target: p }) return } } // XXX if we are replacing SOME of a peer entry group, we will need to // remove any that are not being replaced and will now be invalid, and // re-evaluate them deeper into the tree. const virtualRoot = this.dep.parent this.placed = new this.dep.constructor({ name: this.dep.name, pkg: this.dep.package, resolved: this.dep.resolved, integrity: this.dep.integrity, installLinks: this.installLinks, legacyPeerDeps: this.legacyPeerDeps, error: this.dep.errors[0], ...(this.dep.overrides ? { overrides: this.dep.overrides } : {}), ...(this.dep.isLink ? { target: this.dep.target, realpath: this.dep.realpath } : {}), }) this.oldDep = target.children.get(this.name) if (this.oldDep) { this.replaceOldDep() } else { this.placed.parent = target } // if it's a peerConflicted peer dep, warn about it if (this.edge.peer && !this.placed.satisfies(this.edge)) { this.warnPeerConflict() } // If the edge is not an error, then we're updating something, and // MAY end up putting a better/identical node further up the tree in // a way that causes an unnecessary duplication. If so, remove the // now-unnecessary node. if (this.edge.valid && this.edge.to && this.edge.to !== this.placed) { this.pruneDedupable(this.edge.to, false) } // in case we just made some duplicates that can be removed, // prune anything deeper in the tree that can be replaced by this for (const node of target.root.inventory.query('name', this.name)) { if (node.isDescendantOf(target) && !node.isTop) { this.pruneDedupable(node, false) // only walk the direct children of the ones we kept if (node.root === target.root) { for (const kid of node.children.values()) { this.pruneDedupable(kid, false) } } } } // also place its unmet or invalid peer deps at this location // loop through any peer deps from the thing we just placed, and place // those ones as well. it's safe to do this with the virtual nodes, // because we're copying rather than moving them out of the virtual root, // otherwise they'd be gone and the peer set would change throughout // this loop. for (const peerEdge of this.placed.edgesOut.values()) { if (peerEdge.valid || !peerEdge.peer || peerEdge.peerConflicted) { continue } const peer = virtualRoot.children.get(peerEdge.name) // Note: if the virtualRoot *doesn't* have the peer, then that means // it's an optional peer dep. If it's not being properly met (ie, // peerEdge.valid is false), then this is likely heading for an // ERESOLVE error, unless it can walk further up the tree. if (!peer) { continue } // peerConflicted peerEdge, just accept what's there already if (!peer.satisfies(peerEdge)) { continue } this.children.push(new PlaceDep({ auditReport: this.auditReport, explicitRequest: this.explicitRequest, force: this.force, installLinks: this.installLinks, installStrategy: this.installStrategy, legacyPeerDeps: this.legaycPeerDeps, preferDedupe: this.preferDedupe, strictPeerDeps: this.strictPeerDeps, updateNames: this.updateName, parent: this, dep: peer, node: this.placed, edge: peerEdge, })) } } replaceOldDep () { const target = this.oldDep.parent // XXX handle replacing an entire peer group? // what about cases where we need to push some other peer groups deeper // into the tree? all the tree updating should be done here, and track // all the things that we add and remove, so that we can know what // to re-evaluate. // if we're replacing, we should also remove any nodes for edges that // are now invalid, and where this (or its deps) is the only dependent, // and also recurse on that pruning. Otherwise leaving that dep node // around can result in spurious conflicts pushing nodes deeper into // the tree than needed in the case of cycles that will be removed // later anyway. const oldDeps = [] for (const [name, edge] of this.oldDep.edgesOut.entries()) { if (!this.placed.edgesOut.has(name) && edge.to) { oldDeps.push(...gatherDepSet([edge.to], e => e.to !== edge.to)) } } // gather all peer edgesIn which are at this level, and will not be // satisfied by the new dependency. Those are the peer sets that need // to be either warned about (if they cannot go deeper), or removed and // re-placed (if they can). const prunePeerSets = [] for (const edge of this.oldDep.edgesIn) { if (this.placed.satisfies(edge) || !edge.peer || edge.from.parent !== target || edge.peerConflicted) { // not a peer dep, not invalid, or not from this level, so it's fine // to just let it re-evaluate as a problemEdge later, or let it be // satisfied by the new dep being placed. continue } for (const entryEdge of peerEntrySets(edge.from).keys()) { // either this one needs to be pruned and re-evaluated, or marked // as peerConflicted and warned about. If the entryEdge comes in from // the root or a workspace, then we have to leave it alone, and in that // case, it will have already warned or crashed by getting to this point const entryNode = entryEdge.to const deepestTarget = deepestNestingTarget(entryNode) if (deepestTarget !== target && !(entryEdge.from.isProjectRoot || entryEdge.from.isWorkspace)) { prunePeerSets.push(...gatherDepSet([entryNode], e => { return e.to !== entryNode && !e.peerConflicted })) } else { this.warnPeerConflict(edge, this.dep) } } } this.placed.replace(this.oldDep) this.pruneForReplacement(this.placed, oldDeps) for (const dep of prunePeerSets) { for (const edge of dep.edgesIn) { this.needEvaluation.add(edge.from) } dep.root = null } } pruneForReplacement (node, oldDeps) { // gather up all the now-invalid/extraneous edgesOut, as long as they are // only depended upon by the old node/deps const invalidDeps = new Set([...node.edgesOut.values()] .filter(e => e.to && !e.valid).map(e => e.to)) for (const dep of oldDeps) { const set = gatherDepSet([dep], e => e.to !== dep && e.valid) for (const dep of set) { invalidDeps.add(dep) } } // ignore dependency edges from the node being replaced, but // otherwise filter the set down to just the set with no // dependencies from outside the set, except the node in question. const deps = gatherDepSet(invalidDeps, edge => edge.from !== node && edge.to !== node && edge.valid) // now just delete whatever's left, because it's junk for (const dep of deps) { dep.root = null } } // prune all the nodes in a branch of the tree that can be safely removed // This is only the most basic duplication detection; it finds if there // is another satisfying node further up the tree, and if so, dedupes. // Even in installStategy is nested, we do this amount of deduplication. pruneDedupable (node, descend = true) { if (node.canDedupe(this.preferDedupe)) { // gather up all deps that have no valid edges in from outside // the dep set, except for this node we're deduping, so that we // also prune deps that would be made extraneous. const deps = gatherDepSet([node], e => e.to !== node && e.valid) for (const node of deps) { node.root = null } return } if (descend) { // sort these so that they're deterministically ordered // otherwise, resulting tree shape is dependent on the order // in which they happened to be resolved. const nodeSort = (a, b) => localeCompare(a.location, b.location) const children = [...node.children.values()].sort(nodeSort) for (const child of children) { this.pruneDedupable(child) } const fsChildren = [...node.fsChildren].sort(nodeSort) for (const topNode of fsChildren) { const children = [...topNode.children.values()].sort(nodeSort) for (const child of children) { this.pruneDedupable(child) } } } } get isMine () { const { edge } = this.top const { from: node } = edge if (node.isWorkspace || node.isProjectRoot) { return true } if (!edge.peer) { return false } // re-entry case. check if any non-peer edges come from the project, // or any entryEdges on peer groups are from the root. let hasPeerEdges = false for (const edge of node.edgesIn) { if (edge.peer) { hasPeerEdges = true continue } if (edge.from.isWorkspace || edge.from.isProjectRoot) { return true } } if (hasPeerEdges) { for (const edge of peerEntrySets(node).keys()) { if (edge.from.isWorkspace || edge.from.isProjectRoot) { return true } } } return false } warnPeerConflict (edge, dep) { edge = edge || this.edge dep = dep || this.dep edge.peerConflicted = true const expl = this.explainPeerConflict(edge, dep) log.warn('ERESOLVE', 'overriding peer dependency', expl) } failPeerConflict (edge, dep) { edge = edge || this.top.edge dep = dep || this.top.dep const expl = this.explainPeerConflict(edge, dep) throw Object.assign(new Error('could not resolve'), expl) } explainPeerConflict (edge, dep) { const { from: node } = edge const curNode = node.resolve(edge.name) // XXX decorate more with this.canPlace and this.canPlaceSelf, // this.checks, this.children, walk over conflicted peers, etc. const expl = { code: 'ERESOLVE', edge: edge.explain(), dep: dep.explain(edge), force: this.force, isMine: this.isMine, strictPeerDeps: this.strictPeerDeps, } if (this.parent) { // this is the conflicted peer expl.current = curNode && curNode.explain(edge) expl.peerConflict = this.current && this.current.explain(this.edge) } else { expl.current = curNode && curNode.explain() if (this.canPlaceSelf && this.canPlaceSelf.canPlaceSelf !== CONFLICT) { // failed while checking for a child dep const cps = this.canPlaceSelf for (const peer of cps.conflictChildren) { if (peer.current) { expl.peerConflict = { current: peer.current.explain(), peer: peer.dep.explain(peer.edge), } break } } } else { expl.peerConflict = { current: this.current && this.current.explain(), peer: this.dep.explain(this.edge), } } } return expl } getStartNode () { // if we are a peer, then we MUST be at least as shallow as the peer // dependent const from = this.parent?.getStartNode() || this.edge.from return deepestNestingTarget(from, this.name) } // XXX this only appears to be used by tests get allChildren () { const set = new Set(this.children) for (const child of set) { for (const grandchild of child.children) { set.add(grandchild) } } return [...set] } } module.exports = PlaceDep PK ~\N @npmcli/arborist/lib/tracker.jsnu[const proggy = require('proggy') module.exports = cls => class Tracker extends cls { #progress = new Map() #createTracker (key, name) { const tracker = new proggy.Tracker(name ?? key) tracker.on('done', () => this.#progress.delete(key)) this.#progress.set(key, tracker) } addTracker (section, subsection = null, key = null) { if (section === null || section === undefined) { this.#onError(`Tracker can't be null or undefined`) } if (key === null) { key = subsection } const hasTracker = this.#progress.has(section) const hasSubtracker = this.#progress.has(`${section}:${key}`) if (hasTracker && subsection === null) { // 0. existing tracker, no subsection this.#onError(`Tracker "${section}" already exists`) } else if (!hasTracker && subsection === null) { // 1. no existing tracker, no subsection // Create a new progress tracker this.#createTracker(section) } else if (!hasTracker && subsection !== null) { // 2. no parent tracker and subsection this.#onError(`Parent tracker "${section}" does not exist`) } else if (!hasTracker || !hasSubtracker) { // 3. existing parent tracker, no subsection tracker // Create a new subtracker and update parents const parentTracker = this.#progress.get(section) parentTracker.update(parentTracker.value, parentTracker.total + 1) this.#createTracker(`${section}:${key}`, `${section}:${subsection}`) } // 4. existing parent tracker, existing subsection tracker // skip it } finishTracker (section, subsection = null, key = null) { if (section === null || section === undefined) { this.#onError(`Tracker can't be null or undefined`) } if (key === null) { key = subsection } const hasTracker = this.#progress.has(section) const hasSubtracker = this.#progress.has(`${section}:${key}`) // 0. parent tracker exists, no subsection // Finish parent tracker and remove from this.#progress if (hasTracker && subsection === null) { // check if parent tracker does // not have any remaining children const keys = this.#progress.keys() for (const key of keys) { if (key.match(new RegExp(section + ':'))) { this.finishTracker(section, key) } } // remove parent tracker this.#progress.get(section).finish() } else if (!hasTracker && subsection === null) { // 1. no existing parent tracker, no subsection this.#onError(`Tracker "${section}" does not exist`) } else if (!hasTracker || hasSubtracker) { // 2. subtracker exists // Finish subtracker and remove from this.#progress const parentTracker = this.#progress.get(section) parentTracker.update(parentTracker.value + 1) this.#progress.get(`${section}:${key}`).finish() } // 3. existing parent tracker, no subsection } #onError (msg) { throw new Error(msg) } } PK ~\ւy'@npmcli/arborist/lib/add-rm-pkg-deps.jsnu[// add and remove dependency specs to/from pkg manifest const { log } = require('proc-log') const localeCompare = require('@isaacs/string-locale-compare')('en') const add = ({ pkg, add, saveBundle, saveType }) => { for (const { name, rawSpec } of add) { let addSaveType = saveType // if the user does not give us a type, we infer which type(s) // to keep based on the same order of priority we do when // building the tree as defined in the _loadDeps method of // the node class. if (!addSaveType) { addSaveType = inferSaveType(pkg, name) } if (addSaveType === 'prod') { // a production dependency can only exist as production (rpj ensures it // doesn't coexist w/ optional) deleteSubKey(pkg, 'devDependencies', name, 'dependencies') deleteSubKey(pkg, 'peerDependencies', name, 'dependencies') } else if (addSaveType === 'dev') { // a dev dependency may co-exist as peer, or optional, but not production deleteSubKey(pkg, 'dependencies', name, 'devDependencies') } else if (addSaveType === 'optional') { // an optional dependency may co-exist as dev (rpj ensures it doesn't // coexist w/ prod) deleteSubKey(pkg, 'peerDependencies', name, 'optionalDependencies') } else { // peer or peerOptional is all that's left // a peer dependency may coexist as dev deleteSubKey(pkg, 'dependencies', name, 'peerDependencies') deleteSubKey(pkg, 'optionalDependencies', name, 'peerDependencies') } const depType = saveTypeMap.get(addSaveType) pkg[depType] = pkg[depType] || {} if (rawSpec !== '*' || pkg[depType][name] === undefined) { pkg[depType][name] = rawSpec } if (addSaveType === 'optional') { // Affordance for previous npm versions that require this behaviour pkg.dependencies = pkg.dependencies || {} pkg.dependencies[name] = pkg.optionalDependencies[name] } if (addSaveType === 'peer' || addSaveType === 'peerOptional') { const pdm = pkg.peerDependenciesMeta || {} if (addSaveType === 'peer' && pdm[name] && pdm[name].optional) { pdm[name].optional = false } else if (addSaveType === 'peerOptional') { pdm[name] = pdm[name] || {} pdm[name].optional = true pkg.peerDependenciesMeta = pdm } // peerDeps are often also a devDep, so that they can be tested when // using package managers that don't auto-install peer deps if (pkg.devDependencies && pkg.devDependencies[name] !== undefined) { pkg.devDependencies[name] = pkg.peerDependencies[name] } } if (saveBundle && addSaveType !== 'peer' && addSaveType !== 'peerOptional') { // keep it sorted, keep it unique const bd = new Set(pkg.bundleDependencies || []) bd.add(name) pkg.bundleDependencies = [...bd].sort(localeCompare) } } return pkg } // Canonical source of both the map between saveType and where it correlates to // in the package, and the names of all our dependencies attributes const saveTypeMap = new Map([ ['dev', 'devDependencies'], ['optional', 'optionalDependencies'], ['prod', 'dependencies'], ['peerOptional', 'peerDependencies'], ['peer', 'peerDependencies'], ]) // Finds where the package is already in the spec and infers saveType from that const inferSaveType = (pkg, name) => { for (const saveType of saveTypeMap.keys()) { if (hasSubKey(pkg, saveTypeMap.get(saveType), name)) { if ( saveType === 'peerOptional' && (!hasSubKey(pkg, 'peerDependenciesMeta', name) || !pkg.peerDependenciesMeta[name].optional) ) { return 'peer' } return saveType } } return 'prod' } const hasSubKey = (pkg, depType, name) => { return pkg[depType] && Object.prototype.hasOwnProperty.call(pkg[depType], name) } // Removes a subkey and warns about it if it's being replaced const deleteSubKey = (pkg, depType, name, replacedBy) => { if (hasSubKey(pkg, depType, name)) { if (replacedBy) { log.warn('idealTree', `Removing ${depType}.${name} in favor of ${replacedBy}.${name}`) } delete pkg[depType][name] // clean up peerDepsMeta if we are removing something from peerDependencies if (depType === 'peerDependencies' && pkg.peerDependenciesMeta) { delete pkg.peerDependenciesMeta[name] if (!Object.keys(pkg.peerDependenciesMeta).length) { delete pkg.peerDependenciesMeta } } if (!Object.keys(pkg[depType]).length) { delete pkg[depType] } } } const rm = (pkg, rm) => { for (const depType of new Set(saveTypeMap.values())) { for (const name of rm) { deleteSubKey(pkg, depType, name) } } if (pkg.bundleDependencies) { pkg.bundleDependencies = pkg.bundleDependencies .filter(name => !rm.includes(name)) if (!pkg.bundleDependencies.length) { delete pkg.bundleDependencies } } return pkg } module.exports = { add, rm, saveTypeMap, hasSubKey } PK ~\ź %%*@npmcli/arborist/lib/consistent-resolve.jsnu[// take a path and a resolved value, and turn it into a resolution from // the given new path. This is used with converting a package.json's // relative file: path into one suitable for a lockfile, or between // lockfiles, and for converting hosted git repos to a consistent url type. const npa = require('npm-package-arg') const relpath = require('./relpath.js') const consistentResolve = (resolved, fromPath, toPath, relPaths = false) => { if (!resolved) { return null } try { const hostedOpt = { noCommittish: false } const { fetchSpec, saveSpec, type, hosted, rawSpec, raw, } = npa(resolved, fromPath) if (type === 'file' || type === 'directory') { const cleanFetchSpec = fetchSpec.replace(/#/g, '%23') if (relPaths && toPath) { return `file:${relpath(toPath, cleanFetchSpec)}` } return `file:${cleanFetchSpec}` } if (hosted) { return `git+${hosted.auth ? hosted.https(hostedOpt) : hosted.sshurl(hostedOpt)}` } if (type === 'git') { return saveSpec } if (rawSpec === '*') { return raw } return rawSpec } catch (_) { // whatever we passed in was not acceptable to npa. // leave it 100% untouched. return resolved } } module.exports = consistentResolve PK ~\bQ.@npmcli/arborist/lib/deepest-nesting-target.jsnu[// given a starting node, what is the *deepest* target where name could go? // This is not on the Node class for the simple reason that we sometimes // need to check the deepest *potential* target for a Node that is not yet // added to the tree where we are checking. const deepestNestingTarget = (start, name) => { for (const target of start.ancestry()) { // note: this will skip past the first target if edge is peer if (target.isProjectRoot || !target.resolveParent || target.globalTop) { return target } const targetEdge = target.edgesOut.get(name) if (!targetEdge || !targetEdge.peer) { return target } } } module.exports = deepestNestingTarget PK ~\:\? ? @npmcli/arborist/lib/link.jsnu[const relpath = require('./relpath.js') const Node = require('./node.js') const _loadDeps = Symbol.for('Arborist.Node._loadDeps') const _target = Symbol.for('_target') const { dirname } = require('node:path') // defined by Node class const _delistFromMeta = Symbol.for('_delistFromMeta') const _refreshLocation = Symbol.for('_refreshLocation') class Link extends Node { constructor (options) { const { root, realpath, target, parent, fsParent, isStoreLink } = options if (!realpath && !(target && target.path)) { throw new TypeError('must provide realpath for Link node') } super({ ...options, realpath: realpath || target.path, root: root || (parent ? parent.root : fsParent ? fsParent.root : target ? target.root : null), }) this.isStoreLink = isStoreLink || false if (target) { this.target = target } else if (this.realpath === this.root.path) { this.target = this.root } else { this.target = new Node({ ...options, path: realpath, parent: null, fsParent: null, root: this.root, }) } } get version () { return this.target ? this.target.version : this.package.version || '' } get target () { return this[_target] } set target (target) { const current = this[_target] if (target === current) { return } if (!target) { if (current && current.linksIn) { current.linksIn.delete(this) } if (this.path) { this[_delistFromMeta]() this[_target] = null this.package = {} this[_refreshLocation]() } else { this[_target] = null } return } if (!this.path) { // temp node pending assignment to a tree // we know it's not in the inventory yet, because no path. if (target.path) { this.realpath = target.path } else { target.path = target.realpath = this.realpath } target.root = this.root this[_target] = target target.linksIn.add(this) this.package = target.package return } // have to refresh metadata, because either realpath or package // is very likely changing. this[_delistFromMeta]() this.package = target.package this.realpath = target.path this[_refreshLocation]() target.root = this.root } // a link always resolves to the relative path to its target get resolved () { // the path/realpath guard is there for the benefit of setting // these things in the "wrong" order return this.path && this.realpath ? `file:${relpath(dirname(this.path), this.realpath).replace(/#/g, '%23')}` : null } set resolved (r) {} // deps are resolved on the target, not the Link // so this is a no-op [_loadDeps] () {} // links can't have children, only their targets can // fix it to an empty list so that we can still call // things that iterate over them, just as a no-op get children () { return new Map() } set children (c) {} get isLink () { return true } } module.exports = Link PK ~\]}L_ _ @npmcli/arborist/lib/realpath.jsnu[// look up the realpath, but cache stats to minimize overhead // If the parent folder is in the realpath cache, then we just // lstat the child, since there's no need to do a full realpath // This is not a separate module, and is much simpler than Node's // built-in fs.realpath, because we only care about symbolic links, // so we can handle many fewer edge cases. const { lstat, readlink } = require('node:fs/promises') const { resolve, basename, dirname } = require('node:path') const realpathCached = (path, rpcache, stcache, depth) => { // just a safety against extremely deep eloops /* istanbul ignore next */ if (depth > 2000) { throw eloop(path) } path = resolve(path) if (rpcache.has(path)) { return Promise.resolve(rpcache.get(path)) } const dir = dirname(path) const base = basename(path) if (base && rpcache.has(dir)) { return realpathChild(dir, base, rpcache, stcache, depth) } // if it's the root, then we know it's real if (!base) { rpcache.set(dir, dir) return Promise.resolve(dir) } // the parent, what is that? // find out, and then come back. return realpathCached(dir, rpcache, stcache, depth + 1).then(() => realpathCached(path, rpcache, stcache, depth + 1)) } const lstatCached = (path, stcache) => { if (stcache.has(path)) { return Promise.resolve(stcache.get(path)) } const p = lstat(path).then(st => { stcache.set(path, st) return st }) stcache.set(path, p) return p } // This is a slight fib, as it doesn't actually occur during a stat syscall. // But file systems are giant piles of lies, so whatever. const eloop = path => Object.assign(new Error( `ELOOP: too many symbolic links encountered, stat '${path}'`), { errno: -62, syscall: 'stat', code: 'ELOOP', path: path, }) const realpathChild = (dir, base, rpcache, stcache, depth) => { const realdir = rpcache.get(dir) // that unpossible /* istanbul ignore next */ if (typeof realdir === 'undefined') { throw new Error('in realpathChild without parent being in realpath cache') } const realish = resolve(realdir, base) return lstatCached(realish, stcache).then(st => { if (!st.isSymbolicLink()) { rpcache.set(resolve(dir, base), realish) return realish } return readlink(realish).then(target => { const resolved = resolve(realdir, target) if (realish === resolved) { throw eloop(realish) } return realpathCached(resolved, rpcache, stcache, depth + 1) }).then(real => { rpcache.set(resolve(dir, base), real) return real }) }) } module.exports = realpathCached PK ~\2//$@npmcli/arborist/lib/audit-report.jsnu[// an object representing the set of vulnerabilities in a tree /* eslint camelcase: "off" */ const localeCompare = require('@isaacs/string-locale-compare')('en') const npa = require('npm-package-arg') const pickManifest = require('npm-pick-manifest') const Vuln = require('./vuln.js') const Calculator = require('@npmcli/metavuln-calculator') const _getReport = Symbol('getReport') const _fixAvailable = Symbol('fixAvailable') const _checkTopNode = Symbol('checkTopNode') const _init = Symbol('init') const _omit = Symbol('omit') const { log, time } = require('proc-log') const fetch = require('npm-registry-fetch') class AuditReport extends Map { static load (tree, opts) { return new AuditReport(tree, opts).run() } get auditReportVersion () { return 2 } toJSON () { const obj = { auditReportVersion: this.auditReportVersion, vulnerabilities: {}, metadata: { vulnerabilities: { info: 0, low: 0, moderate: 0, high: 0, critical: 0, total: this.size, }, dependencies: { prod: 0, dev: 0, optional: 0, peer: 0, peerOptional: 0, total: this.tree.inventory.size - 1, }, }, } for (const node of this.tree.inventory.values()) { const { dependencies } = obj.metadata let prod = true for (const type of [ 'dev', 'optional', 'peer', 'peerOptional', ]) { if (node[type]) { dependencies[type]++ prod = false } } if (prod) { dependencies.prod++ } } // if it doesn't have any topVulns, then it's fixable with audit fix // for each topVuln, figure out if it's fixable with audit fix --force, // or if we have to just delete the thing, and if the fix --force will // require a semver major update. const vulnerabilities = [] for (const [name, vuln] of this.entries()) { vulnerabilities.push([name, vuln.toJSON()]) obj.metadata.vulnerabilities[vuln.severity]++ } obj.vulnerabilities = vulnerabilities .sort(([a], [b]) => localeCompare(a, b)) .reduce((set, [name, vuln]) => { set[name] = vuln return set }, {}) return obj } constructor (tree, opts = {}) { super() const { omit } = opts this[_omit] = new Set(omit || []) this.topVulns = new Map() this.calculator = new Calculator(opts) this.error = null this.options = opts this.tree = tree this.filterSet = opts.filterSet } async run () { this.report = await this[_getReport]() log.silly('audit report', this.report) if (this.report) { await this[_init]() } return this } isVulnerable (node) { const vuln = this.get(node.packageName) return !!(vuln && vuln.isVulnerable(node)) } async [_init] () { const timeEnd = time.start('auditReport:init') const promises = [] for (const [name, advisories] of Object.entries(this.report)) { for (const advisory of advisories) { promises.push(this.calculator.calculate(name, advisory)) } } // now the advisories are calculated with a set of versions // and the packument. turn them into our style of vuln objects // which also have the affected nodes, and also create entries // for all the metavulns that we find from dependents. const advisories = new Set(await Promise.all(promises)) const seen = new Set() for (const advisory of advisories) { const { name, range } = advisory const k = `${name}@${range}` const vuln = this.get(name) || new Vuln({ name, advisory }) if (this.has(name)) { vuln.addAdvisory(advisory) } super.set(name, vuln) // don't flag the exact same name/range more than once // adding multiple advisories with the same range is fine, but no // need to search for nodes we already would have added. if (!seen.has(k)) { const p = [] for (const node of this.tree.inventory.query('packageName', name)) { if (!shouldAudit(node, this[_omit], this.filterSet)) { continue } // if not vulnerable by this advisory, keep searching if (!advisory.testVersion(node.version)) { continue } // we will have loaded the source already if this is a metavuln if (advisory.type === 'metavuln') { vuln.addVia(this.get(advisory.dependency)) } // already marked this one, no need to do it again if (vuln.nodes.has(node)) { continue } // haven't marked this one yet. get its dependents. vuln.nodes.add(node) for (const { from: dep, spec } of node.edgesIn) { if (dep.isTop && !vuln.topNodes.has(dep)) { this[_checkTopNode](dep, vuln, spec) } else { // calculate a metavuln, if necessary const calc = this.calculator.calculate(dep.packageName, advisory) // eslint-disable-next-line promise/always-return p.push(calc.then(meta => { // eslint-disable-next-line promise/always-return if (meta.testVersion(dep.version, spec)) { advisories.add(meta) } })) } } } await Promise.all(p) seen.add(k) } // make sure we actually got something. if not, remove it // this can happen if you are loading from a lockfile created by // npm v5, since it lists the current version of all deps, // rather than the range that is actually depended upon, // or if using --omit with the older audit endpoint. if (this.get(name).nodes.size === 0) { this.delete(name) continue } // if the vuln is valid, but THIS advisory doesn't apply to any of // the nodes it references, then remove it from the advisory list. // happens when using omit with old audit endpoint. for (const advisory of vuln.advisories) { const relevant = [...vuln.nodes] .some(n => advisory.testVersion(n.version)) if (!relevant) { vuln.deleteAdvisory(advisory) } } } timeEnd() } [_checkTopNode] (topNode, vuln, spec) { vuln.fixAvailable = this[_fixAvailable](topNode, vuln, spec) if (vuln.fixAvailable !== true) { // now we know the top node is vulnerable, and cannot be // upgraded out of the bad place without --force. But, there's // no need to add it to the actual vulns list, because nothing // depends on root. this.topVulns.set(vuln.name, vuln) vuln.topNodes.add(topNode) } } // check whether the top node is vulnerable. // check whether we can get out of the bad place with --force, and if // so, whether that update is SemVer Major [_fixAvailable] (topNode, vuln, spec) { // this will always be set to at least {name, versions:{}} const paku = vuln.packument if (!vuln.testSpec(spec)) { return true } // similarly, even if we HAVE a packument, but we're looking for it // somewhere other than the registry, and we got something vulnerable, // then we're stuck with it. const specObj = npa(spec) if (!specObj.registry) { return false } if (specObj.subSpec) { spec = specObj.subSpec.rawSpec } // We don't provide fixes for top nodes other than root, but we // still check to see if the node is fixable with a different version, // and if that is a semver major bump. try { const { _isSemVerMajor: isSemVerMajor, version, name, } = pickManifest(paku, spec, { ...this.options, before: null, avoid: vuln.range, avoidStrict: true, }) return { name, version, isSemVerMajor } } catch (er) { return false } } set () { throw new Error('do not call AuditReport.set() directly') } // convert a quick-audit into a bulk advisory listing static auditToBulk (report) { if (!report.advisories) { // tack on the report json where the response body would go throw Object.assign(new Error('Invalid advisory report'), { body: JSON.stringify(report), }) } const bulk = {} const { advisories } = report for (const advisory of Object.values(advisories)) { const { id, url, title, severity = 'high', vulnerable_versions = '*', module_name: name, } = advisory bulk[name] = bulk[name] || [] bulk[name].push({ id, url, title, severity, vulnerable_versions }) } return bulk } async [_getReport] () { // if we're not auditing, just return false if (this.options.audit === false || this.options.offline === true || this.tree.inventory.size === 1) { return null } const timeEnd = time.start('auditReport:getReport') try { try { // first try the super fast bulk advisory listing const body = prepareBulkData(this.tree, this[_omit], this.filterSet) log.silly('audit', 'bulk request', body) // no sense asking if we don't have anything to audit, // we know it'll be empty if (!Object.keys(body).length) { return null } const res = await fetch('/-/npm/v1/security/advisories/bulk', { ...this.options, registry: this.options.auditRegistry || this.options.registry, method: 'POST', gzip: true, body, }) return await res.json() } catch (er) { log.silly('audit', 'bulk request failed', String(er.body)) // that failed, try the quick audit endpoint const body = prepareData(this.tree, this.options) const res = await fetch('/-/npm/v1/security/audits/quick', { ...this.options, registry: this.options.auditRegistry || this.options.registry, method: 'POST', gzip: true, body, }) return AuditReport.auditToBulk(await res.json()) } } catch (er) { log.verbose('audit error', er) log.silly('audit error', String(er.body)) this.error = er return null } finally { timeEnd() } } } // return true if we should audit this one const shouldAudit = (node, omit, filterSet) => !node.version ? false : node.isRoot ? false : filterSet && filterSet.size !== 0 && !filterSet.has(node) ? false : omit.size === 0 ? true : !( // otherwise, just ensure we're not omitting this one node.dev && omit.has('dev') || node.optional && omit.has('optional') || node.devOptional && omit.has('dev') && omit.has('optional') || node.peer && omit.has('peer') ) const prepareBulkData = (tree, omit, filterSet) => { const payload = {} for (const name of tree.inventory.query('packageName')) { const set = new Set() for (const node of tree.inventory.query('packageName', name)) { if (!shouldAudit(node, omit, filterSet)) { continue } set.add(node.version) } if (set.size) { payload[name] = [...set] } } return payload } const prepareData = (tree, opts) => { const { npmVersion: npm_version } = opts const node_version = process.version const { platform, arch } = process const { NODE_ENV: node_env } = process.env const data = tree.meta.commit() // the legacy audit endpoint doesn't support any kind of pre-filtering // we just have to get the advisories and skip over them in the report return { name: data.name, version: data.version, requires: { ...(tree.package.devDependencies || {}), ...(tree.package.peerDependencies || {}), ...(tree.package.optionalDependencies || {}), ...(tree.package.dependencies || {}), }, dependencies: data.dependencies, metadata: { node_version, npm_version, platform, arch, node_env, }, } } module.exports = AuditReport PK ~\).:.:,@npmcli/arborist/lib/arborist/load-actual.jsnu[// mix-in implementing the loadActual method const { relative, dirname, resolve, join, normalize } = require('node:path') const rpj = require('read-package-json-fast') const { readdirScoped } = require('@npmcli/fs') const { walkUp } = require('walk-up-path') const ancestorPath = require('common-ancestor-path') const treeCheck = require('../tree-check.js') const Shrinkwrap = require('../shrinkwrap.js') const calcDepFlags = require('../calc-dep-flags.js') const Node = require('../node.js') const Link = require('../link.js') const realpath = require('../realpath.js') // public symbols const _changePath = Symbol.for('_changePath') const _setWorkspaces = Symbol.for('setWorkspaces') const _rpcache = Symbol.for('realpathCache') const _stcache = Symbol.for('statCache') module.exports = cls => class ActualLoader extends cls { #actualTree // ensure when walking the tree that we don't call loadTree on the same // actual node more than one time. #actualTreeLoaded = new Set() #actualTreePromise // cache of nodes when loading the actualTree, so that we avoid loaded the // same node multiple times when symlinks attack. #cache = new Map() #filter // cache of link targets for setting fsParent links // We don't do fsParent as a magic getter/setter, because it'd be too costly // to keep up to date along the walk. // And, we know that it can ONLY be relevant when the node is a target of a // link, otherwise it'd be in a node_modules folder, so take advantage of // that to limit the scans later. #topNodes = new Set() #transplantFilter constructor (options) { super(options) // the tree of nodes on disk this.actualTree = options.actualTree // caches for cached realpath calls const cwd = process.cwd() // assume that the cwd is real enough for our purposes this[_rpcache] = new Map([[cwd, cwd]]) this[_stcache] = new Map() } // public method // TODO remove options param in next semver major async loadActual (options = {}) { // In the past this.actualTree was set as a promise that eventually // resolved, and overwrite this.actualTree with the resolved value. This // was a problem because virtually no other code expects this.actualTree to // be a promise. Instead we only set it once resolved, and also return it // from the promise so that it is what's returned from this function when // awaited. if (this.actualTree) { return this.actualTree } if (!this.#actualTreePromise) { // allow the user to set options on the ctor as well. // XXX: deprecate separate method options objects. options = { ...this.options, ...options } this.#actualTreePromise = this.#loadActual(options) .then(tree => { // reset all deps to extraneous prior to recalc if (!options.root) { for (const node of tree.inventory.values()) { node.extraneous = true } } // only reset root flags if we're not re-rooting, // otherwise leave as-is calcDepFlags(tree, !options.root) this.actualTree = treeCheck(tree) return this.actualTree }) } return this.#actualTreePromise } // return the promise so that we don't ever have more than one going at the // same time. This is so that buildIdealTree can default to the actualTree // if no shrinkwrap present, but reify() can still call buildIdealTree and // loadActual in parallel safely. async #loadActual (options) { // mostly realpath to throw if the root doesn't exist const { global, filter = () => true, root = null, transplantFilter = () => true, ignoreMissing = false, forceActual = false, } = options this.#filter = filter this.#transplantFilter = transplantFilter if (global) { const real = await realpath(this.path, this[_rpcache], this[_stcache]) const params = { path: this.path, realpath: real, pkg: {}, global, loadOverrides: true, } if (this.path === real) { this.#actualTree = this.#newNode(params) } else { this.#actualTree = await this.#newLink(params) } } else { // not in global mode, hidden lockfile is allowed, load root pkg too this.#actualTree = await this.#loadFSNode({ path: this.path, real: await realpath(this.path, this[_rpcache], this[_stcache]), loadOverrides: true, }) this.#actualTree.assertRootOverrides() // if forceActual is set, don't even try the hidden lockfile if (!forceActual) { // Note: hidden lockfile will be rejected if it's not the latest thing // in the folder, or if any of the entries in the hidden lockfile are // missing. const meta = await Shrinkwrap.load({ path: this.#actualTree.path, hiddenLockfile: true, resolveOptions: this.options, }) if (meta.loadedFromDisk) { this.#actualTree.meta = meta // have to load on a new Arborist object, so we don't assign // the virtualTree on this one! Also, the weird reference is because // we can't easily get a ref to Arborist in this module, without // creating a circular reference, since this class is a mixin used // to build up the Arborist class itself. await new this.constructor({ ...this.options }).loadVirtual({ root: this.#actualTree, }) await this[_setWorkspaces](this.#actualTree) this.#transplant(root) return this.#actualTree } } const meta = await Shrinkwrap.load({ path: this.#actualTree.path, lockfileVersion: this.options.lockfileVersion, resolveOptions: this.options, }) this.#actualTree.meta = meta } await this.#loadFSTree(this.#actualTree) await this[_setWorkspaces](this.#actualTree) // if there are workspace targets without Link nodes created, load // the targets, so that we know what they are. if (this.#actualTree.workspaces && this.#actualTree.workspaces.size) { const promises = [] for (const path of this.#actualTree.workspaces.values()) { if (!this.#cache.has(path)) { // workspace overrides use the root overrides const p = this.#loadFSNode({ path, root: this.#actualTree, useRootOverrides: true }) .then(node => this.#loadFSTree(node)) promises.push(p) } } await Promise.all(promises) } if (!ignoreMissing) { await this.#findMissingEdges() } // try to find a node that is the parent in a fs tree sense, but not a // node_modules tree sense, of any link targets. this allows us to // resolve deps that node will find, but a legacy npm view of the // world would not have noticed. for (const path of this.#topNodes) { const node = this.#cache.get(path) if (node && !node.parent && !node.fsParent) { for (const p of walkUp(dirname(path))) { if (this.#cache.has(p)) { node.fsParent = this.#cache.get(p) break } } } } this.#transplant(root) if (global) { // need to depend on the children, or else all of them // will end up being flagged as extraneous, since the // global root isn't a "real" project const tree = this.#actualTree const actualRoot = tree.isLink ? tree.target : tree const { dependencies = {} } = actualRoot.package for (const [name, kid] of actualRoot.children.entries()) { const def = kid.isLink ? `file:${kid.realpath.replace(/#/g, '%23')}` : '*' dependencies[name] = dependencies[name] || def } actualRoot.package = { ...actualRoot.package, dependencies } } return this.#actualTree } #transplant (root) { if (!root || root === this.#actualTree) { return } this.#actualTree[_changePath](root.path) for (const node of this.#actualTree.children.values()) { if (!this.#transplantFilter(node)) { node.root = null } } root.replace(this.#actualTree) for (const node of this.#actualTree.fsChildren) { node.root = this.#transplantFilter(node) ? root : null } this.#actualTree = root } async #loadFSNode ({ path, parent, real, root, loadOverrides, useRootOverrides }) { if (!real) { try { real = await realpath(path, this[_rpcache], this[_stcache]) } catch (error) { // if realpath fails, just provide a dummy error node return new Node({ error, path, realpath: path, parent, root, loadOverrides, }) } } const cached = this.#cache.get(path) let node // missing edges get a dummy node, assign the parent and return it if (cached && !cached.dummy) { cached.parent = parent return cached } else { const params = { installLinks: this.installLinks, legacyPeerDeps: this.legacyPeerDeps, path, realpath: real, parent, root, loadOverrides, } try { const pkg = await rpj(join(real, 'package.json')) params.pkg = pkg if (useRootOverrides && root.overrides) { params.overrides = root.overrides.getNodeRule({ name: pkg.name, version: pkg.version }) } } catch (err) { params.error = err } // soldier on if read-package-json raises an error, passing it to the // Node which will attach it to its errors array (Link passes it along to // its target node) if (normalize(path) === real) { node = this.#newNode(params) } else { node = await this.#newLink(params) } } this.#cache.set(path, node) return node } #newNode (options) { // check it for an fsParent if it's a tree top. there's a decent chance // it'll get parented later, making the fsParent scan a no-op, but better // safe than sorry, since it's cheap. const { parent, realpath } = options if (!parent) { this.#topNodes.add(realpath) } return new Node(options) } async #newLink (options) { const { realpath } = options this.#topNodes.add(realpath) const target = this.#cache.get(realpath) const link = new Link({ ...options, target }) if (!target) { // Link set its target itself in this case this.#cache.set(realpath, link.target) // if a link target points at a node outside of the root tree's // node_modules hierarchy, then load that node as well. await this.#loadFSTree(link.target) } return link } async #loadFSTree (node) { const did = this.#actualTreeLoaded if (!node.isLink && !did.has(node.target.realpath)) { did.add(node.target.realpath) await this.#loadFSChildren(node.target) return Promise.all( [...node.target.children.entries()] .filter(([, kid]) => !did.has(kid.realpath)) .map(([, kid]) => this.#loadFSTree(kid)) ) } } // create child nodes for all the entries in node_modules // and attach them to the node as a parent async #loadFSChildren (node) { const nm = resolve(node.realpath, 'node_modules') try { const kids = await readdirScoped(nm).then(paths => paths.map(p => p.replace(/\\/g, '/'))) return Promise.all( // ignore . dirs and retired scoped package folders kids.filter(kid => !/^(@[^/]+\/)?\./.test(kid)) .filter(kid => this.#filter(node, kid)) .map(kid => this.#loadFSNode({ parent: node, path: resolve(nm, kid), }))) } catch { // error in the readdir is not fatal, just means no kids } } async #findMissingEdges () { // try to resolve any missing edges by walking up the directory tree, // checking for the package in each node_modules folder. stop at the // root directory. // The tricky move here is that we load a "dummy" node for the folder // containing the node_modules folder, so that it can be assigned as // the fsParent. It's a bad idea to *actually* load that full node, // because people sometimes develop in ~/projects/node_modules/... // so we'd end up loading a massive tree with lots of unrelated junk. const nmContents = new Map() const tree = this.#actualTree for (const node of tree.inventory.values()) { const ancestor = ancestorPath(node.realpath, this.path) const depPromises = [] for (const [name, edge] of node.edgesOut.entries()) { const notMissing = !edge.missing && !(edge.to && (edge.to.dummy || edge.to.parent !== node)) if (notMissing) { continue } // start the walk from the dirname, because we would have found // the dep in the loadFSTree step already if it was local. for (const p of walkUp(dirname(node.realpath))) { // only walk as far as the nearest ancestor // this keeps us from going into completely unrelated // places when a project is just missing something, but // allows for finding the transitive deps of link targets. // ie, if it has to go up and back out to get to the path // from the nearest common ancestor, we've gone too far. if (ancestor && /^\.\.(?:[\\/]|$)/.test(relative(ancestor, p))) { break } let entries if (!nmContents.has(p)) { entries = await readdirScoped(p + '/node_modules') .catch(() => []).then(paths => paths.map(p => p.replace(/\\/g, '/'))) nmContents.set(p, entries) } else { entries = nmContents.get(p) } if (!entries.includes(name)) { continue } let d if (!this.#cache.has(p)) { d = new Node({ path: p, root: node.root, dummy: true }) this.#cache.set(p, d) } else { d = this.#cache.get(p) } if (d.dummy) { // it's a placeholder, so likely would not have loaded this dep, // unless another dep in the tree also needs it. const depPath = normalize(`${p}/node_modules/${name}`) const cached = this.#cache.get(depPath) if (!cached || cached.dummy) { depPromises.push(this.#loadFSNode({ path: depPath, root: node.root, parent: d, }).then(node => this.#loadFSTree(node))) } } break } } await Promise.all(depPromises) } } } PK ~\=?^<<1@npmcli/arborist/lib/arborist/isolated-reifier.jsnu[const _makeIdealGraph = Symbol('makeIdealGraph') const _createIsolatedTree = Symbol.for('createIsolatedTree') const _createBundledTree = Symbol('createBundledTree') const { mkdirSync } = require('node:fs') const pacote = require('pacote') const { join } = require('node:path') const { depth } = require('treeverse') const crypto = require('node:crypto') // cache complicated function results const memoize = (fn) => { const memo = new Map() return async function (arg) { const key = arg if (memo.has(key)) { return memo.get(key) } const result = {} memo.set(key, result) await fn(result, arg) return result } } module.exports = cls => class IsolatedReifier extends cls { /** * Create an ideal graph. * * An implementation of npm RFC-0042 * https://github.com/npm/rfcs/blob/main/accepted/0042-isolated-mode.md * * This entire file should be considered technical debt that will be resolved * with an Arborist refactor or rewrite. Embedded logic in Nodes and Links, * and the incremental state of building trees and reifying contains too many * assumptions to do a linked mode properly. * * Instead, this approach takes a tree built from build-ideal-tree, and * returns a new tree-like structure without the embedded logic of Node and * Link classes. * * Since the RFC requires leaving the package-lock in place, this approach * temporarily replaces the tree state for a couple of steps of reifying. * **/ async [_makeIdealGraph] (options) { /* Make sure that the ideal tree is build as the rest of * the algorithm depends on it. */ const bitOpt = { ...options, complete: false, } await this.buildIdealTree(bitOpt) const idealTree = this.idealTree this.rootNode = {} const root = this.rootNode this.counter = 0 // memoize to cache generating proxy Nodes this.externalProxyMemo = memoize(this.externalProxy.bind(this)) this.workspaceProxyMemo = memoize(this.workspaceProxy.bind(this)) root.external = [] root.isProjectRoot = true root.localLocation = idealTree.location root.localPath = idealTree.path root.workspaces = await Promise.all( Array.from(idealTree.fsChildren.values(), this.workspaceProxyMemo)) const processed = new Set() const queue = [idealTree, ...idealTree.fsChildren] while (queue.length !== 0) { const next = queue.pop() if (processed.has(next.location)) { continue } processed.add(next.location) next.edgesOut.forEach(e => { if (!e.to || (next.package.bundleDependencies || next.package.bundledDependencies || []).includes(e.to.name)) { return } queue.push(e.to) }) if (!next.isProjectRoot && !next.isWorkspace) { root.external.push(await this.externalProxyMemo(next)) } } await this.assignCommonProperties(idealTree, root) this.idealGraph = root } async workspaceProxy (result, node) { result.localLocation = node.location result.localPath = node.path result.isWorkspace = true result.resolved = node.resolved await this.assignCommonProperties(node, result) } async externalProxy (result, node) { await this.assignCommonProperties(node, result) if (node.hasShrinkwrap) { const dir = join( node.root.path, 'node_modules', '.store', `${node.name}@${node.version}` ) mkdirSync(dir, { recursive: true }) // TODO this approach feels wrong // and shouldn't be necessary for shrinkwraps await pacote.extract(node.resolved, dir, { ...this.options, resolved: node.resolved, integrity: node.integrity, }) const Arborist = this.constructor const arb = new Arborist({ ...this.options, path: dir }) await arb[_makeIdealGraph]({ dev: false }) this.rootNode.external.push(...arb.idealGraph.external) arb.idealGraph.external.forEach(e => { e.root = this.rootNode e.id = `${node.id}=>${e.id}` }) result.localDependencies = [] result.externalDependencies = arb.idealGraph.externalDependencies result.externalOptionalDependencies = arb.idealGraph.externalOptionalDependencies result.dependencies = [ ...result.externalDependencies, ...result.localDependencies, ...result.externalOptionalDependencies, ] } result.optional = node.optional result.resolved = node.resolved result.version = node.version } async assignCommonProperties (node, result) { function validEdgesOut (node) { return [...node.edgesOut.values()].filter(e => e.to && e.to.target && !(node.package.bundledDepenedencies || node.package.bundleDependencies || []).includes(e.to.name)) } const edges = validEdgesOut(node) const optionalDeps = edges.filter(e => e.optional).map(e => e.to.target) const nonOptionalDeps = edges.filter(e => !e.optional).map(e => e.to.target) result.localDependencies = await Promise.all(nonOptionalDeps.filter(n => n.isWorkspace).map(this.workspaceProxyMemo)) result.externalDependencies = await Promise.all(nonOptionalDeps.filter(n => !n.isWorkspace).map(this.externalProxyMemo)) result.externalOptionalDependencies = await Promise.all(optionalDeps.map(this.externalProxyMemo)) result.dependencies = [ ...result.externalDependencies, ...result.localDependencies, ...result.externalOptionalDependencies, ] result.root = this.rootNode result.id = this.counter++ result.name = node.name result.package = { ...node.package } result.package.bundleDependencies = undefined result.hasInstallScript = node.hasInstallScript } async [_createBundledTree] () { // TODO: make sure that idealTree object exists const idealTree = this.idealTree // TODO: test workspaces having bundled deps const queue = [] for (const [, edge] of idealTree.edgesOut) { if (edge.to && (idealTree.package.bundleDependencies || idealTree.package.bundledDependencies || []).includes(edge.to.name)) { queue.push({ from: idealTree, to: edge.to }) } } for (const child of idealTree.fsChildren) { for (const [, edge] of child.edgesOut) { if (edge.to && (child.package.bundleDependencies || child.package.bundledDependencies || []).includes(edge.to.name)) { queue.push({ from: child, to: edge.to }) } } } const processed = new Set() const nodes = new Map() const edges = [] while (queue.length !== 0) { const nextEdge = queue.pop() const key = `${nextEdge.from.location}=>${nextEdge.to.location}` // should be impossible, unless bundled is duped /* istanbul ignore next */ if (processed.has(key)) { continue } processed.add(key) const from = nextEdge.from if (!from.isRoot && !from.isWorkspace) { nodes.set(from.location, { location: from.location, resolved: from.resolved, name: from.name, optional: from.optional, pkg: { ...from.package, bundleDependencies: undefined } }) } const to = nextEdge.to nodes.set(to.location, { location: to.location, resolved: to.resolved, name: to.name, optional: to.optional, pkg: { ...to.package, bundleDependencies: undefined } }) edges.push({ from: from.isRoot ? 'root' : from.location, to: to.location }) to.edgesOut.forEach(e => { // an edge out should always have a to /* istanbul ignore else */ if (e.to) { queue.push({ from: e.from, to: e.to }) } }) } return { edges, nodes } } async [_createIsolatedTree] () { await this[_makeIdealGraph](this.options) const proxiedIdealTree = this.idealGraph const bundledTree = await this[_createBundledTree]() const treeHash = (startNode) => { // generate short hash based on the dependency tree // starting at this node const deps = [] const branch = [] depth({ tree: startNode, getChildren: node => node.dependencies, filter: node => node, visit: node => { branch.push(`${node.name}@${node.version}`) deps.push(`${branch.join('->')}::${node.resolved}`) }, leave: () => { branch.pop() }, }) deps.sort() return crypto.createHash('shake256', { outputLength: 16 }) .update(deps.join(',')) .digest('base64') // Node v14 doesn't support base64url .replace(/\+/g, '-') .replace(/\//g, '_') .replace(/=+$/m, '') } const getKey = (idealTreeNode) => { return `${idealTreeNode.name}@${idealTreeNode.version}-${treeHash(idealTreeNode)}` } const root = { fsChildren: [], integrity: null, inventory: new Map(), isLink: false, isRoot: true, binPaths: [], edgesIn: new Set(), edgesOut: new Map(), hasShrinkwrap: false, parent: null, // TODO: we should probably not reference this.idealTree resolved: this.idealTree.resolved, isTop: true, path: proxiedIdealTree.root.localPath, realpath: proxiedIdealTree.root.localPath, package: proxiedIdealTree.root.package, meta: { loadedFromDisk: false }, global: false, isProjectRoot: true, children: [], } // root.inventory.set('', t) // root.meta = this.idealTree.meta // TODO We should mock better the inventory object because it is used by audit-report.js ... maybe root.inventory.query = () => { return [] } const processed = new Set() proxiedIdealTree.workspaces.forEach(c => { const workspace = { edgesIn: new Set(), edgesOut: new Map(), children: [], hasInstallScript: c.hasInstallScript, binPaths: [], package: c.package, location: c.localLocation, path: c.localPath, realpath: c.localPath, resolved: c.resolved, } root.fsChildren.push(workspace) root.inventory.set(workspace.location, workspace) }) const generateChild = (node, location, pkg, inStore) => { const newChild = { global: false, globalTop: false, isProjectRoot: false, isTop: false, location, name: node.name, optional: node.optional, top: { path: proxiedIdealTree.root.localPath }, children: [], edgesIn: new Set(), edgesOut: new Map(), binPaths: [], fsChildren: [], /* istanbul ignore next -- emulate Node */ getBundler () { return null }, hasShrinkwrap: false, inDepBundle: false, integrity: null, isLink: false, isRoot: false, isInStore: inStore, path: join(proxiedIdealTree.root.localPath, location), realpath: join(proxiedIdealTree.root.localPath, location), resolved: node.resolved, version: pkg.version, package: pkg, } newChild.target = newChild root.children.push(newChild) root.inventory.set(newChild.location, newChild) } proxiedIdealTree.external.forEach(c => { const key = getKey(c) if (processed.has(key)) { return } processed.add(key) const location = join('node_modules', '.store', key, 'node_modules', c.name) generateChild(c, location, c.package, true) }) bundledTree.nodes.forEach(node => { generateChild(node, node.location, node.pkg, false) }) bundledTree.edges.forEach(e => { const from = e.from === 'root' ? root : root.inventory.get(e.from) const to = root.inventory.get(e.to) // Maybe optional should be propagated from the original edge const edge = { optional: false, from, to } from.edgesOut.set(to.name, edge) to.edgesIn.add(edge) }) const memo = new Set() function processEdges (node, externalEdge) { externalEdge = !!externalEdge const key = getKey(node) if (memo.has(key)) { return } memo.add(key) let from, nmFolder if (externalEdge) { const fromLocation = join('node_modules', '.store', key, 'node_modules', node.name) from = root.children.find(c => c.location === fromLocation) nmFolder = join('node_modules', '.store', key, 'node_modules') } else { from = node.isProjectRoot ? root : root.fsChildren.find(c => c.location === node.localLocation) nmFolder = join(node.localLocation, 'node_modules') } const processDeps = (dep, optional, external) => { optional = !!optional external = !!external const location = join(nmFolder, dep.name) const binNames = dep.package.bin && Object.keys(dep.package.bin) || [] const toKey = getKey(dep) let target if (external) { const toLocation = join('node_modules', '.store', toKey, 'node_modules', dep.name) target = root.children.find(c => c.location === toLocation) } else { target = root.fsChildren.find(c => c.location === dep.localLocation) } // TODO: we should no-op is an edge has already been created with the same fromKey and toKey binNames.forEach(bn => { target.binPaths.push(join(from.realpath, 'node_modules', '.bin', bn)) }) const link = { global: false, globalTop: false, isProjectRoot: false, edgesIn: new Set(), edgesOut: new Map(), binPaths: [], isTop: false, optional, location: location, path: join(dep.root.localPath, nmFolder, dep.name), realpath: target.path, name: toKey, resolved: dep.resolved, top: { path: dep.root.localPath }, children: [], fsChildren: [], isLink: true, isStoreLink: true, isRoot: false, package: { _id: 'abc', bundleDependencies: undefined, deprecated: undefined, bin: target.package.bin, scripts: dep.package.scripts }, target, } const newEdge1 = { optional, from, to: link } from.edgesOut.set(dep.name, newEdge1) link.edgesIn.add(newEdge1) const newEdge2 = { optional: false, from: link, to: target } link.edgesOut.set(dep.name, newEdge2) target.edgesIn.add(newEdge2) root.children.push(link) } for (const dep of node.localDependencies) { processEdges(dep, false) // nonOptional, local processDeps(dep, false, false) } for (const dep of node.externalDependencies) { processEdges(dep, true) // nonOptional, external processDeps(dep, false, true) } for (const dep of node.externalOptionalDependencies) { processEdges(dep, true) // optional, external processDeps(dep, true, true) } } processEdges(proxiedIdealTree, false) for (const node of proxiedIdealTree.workspaces) { processEdges(node, false) } root.children.forEach(c => c.parent = root) root.children.forEach(c => c.root = root) root.root = root root.target = root return root } } PK ~\[Z.Z.(@npmcli/arborist/lib/arborist/rebuild.jsnu[// Arborist.rebuild({path = this.path}) will do all the binlinks and // bundle building needed. Called by reify, and by `npm rebuild`. const localeCompare = require('@isaacs/string-locale-compare')('en') const { depth: dfwalk } = require('treeverse') const promiseAllRejectLate = require('promise-all-reject-late') const rpj = require('read-package-json-fast') const binLinks = require('bin-links') const runScript = require('@npmcli/run-script') const { callLimit: promiseCallLimit } = require('promise-call-limit') const { resolve } = require('node:path') const { isNodeGypPackage, defaultGypInstallScript } = require('@npmcli/node-gyp') const { log, time } = require('proc-log') const boolEnv = b => b ? '1' : '' const sortNodes = (a, b) => (a.depth - b.depth) || localeCompare(a.path, b.path) const _checkBins = Symbol.for('checkBins') // defined by reify mixin const _handleOptionalFailure = Symbol.for('handleOptionalFailure') const _trashList = Symbol.for('trashList') module.exports = cls => class Builder extends cls { #doHandleOptionalFailure #oldMeta = null #queues constructor (options) { super(options) this.scriptsRun = new Set() this.#resetQueues() } async rebuild ({ nodes, handleOptionalFailure = false } = {}) { // nothing to do if we're not building anything! if (this.options.ignoreScripts && !this.options.binLinks) { return } // when building for the first time, as part of reify, we ignore // failures in optional nodes, and just delete them. however, when // running JUST a rebuild, we treat optional failures as real fails this.#doHandleOptionalFailure = handleOptionalFailure if (!nodes) { nodes = await this.#loadDefaultNodes() } // separates links nodes so that it can run // prepare scripts and link bins in the expected order const timeEnd = time.start('build') const { depNodes, linkNodes, } = this.#retrieveNodesByType(nodes) // build regular deps await this.#build(depNodes, {}) // build link deps if (linkNodes.size) { this.#resetQueues() await this.#build(linkNodes, { type: 'links' }) } timeEnd() } // if we don't have a set of nodes, then just rebuild // the actual tree on disk. async #loadDefaultNodes () { let nodes const tree = await this.loadActual() let filterSet if (!this.options.workspacesEnabled) { filterSet = this.excludeWorkspacesDependencySet(tree) nodes = tree.inventory.filter(node => filterSet.has(node) || node.isProjectRoot ) } else if (this.options.workspaces.length) { filterSet = this.workspaceDependencySet( tree, this.options.workspaces, this.options.includeWorkspaceRoot ) nodes = tree.inventory.filter(node => filterSet.has(node)) } else { nodes = tree.inventory.values() } return nodes } #retrieveNodesByType (nodes) { const depNodes = new Set() const linkNodes = new Set() const storeNodes = new Set() for (const node of nodes) { if (node.isStoreLink) { storeNodes.add(node) } else if (node.isLink) { linkNodes.add(node) } else { depNodes.add(node) } } // Make sure that store linked nodes are processed last. // We can't process store links separately or else lifecycle scripts on // standard nodes might not have bin links yet. for (const node of storeNodes) { depNodes.add(node) } // deduplicates link nodes and their targets, avoids // calling lifecycle scripts twice when running `npm rebuild` // ref: https://github.com/npm/cli/issues/2905 // // we avoid doing so if global=true since `bin-links` relies // on having the target nodes available in global mode. if (!this.options.global) { for (const node of linkNodes) { depNodes.delete(node.target) } } return { depNodes, linkNodes, } } #resetQueues () { this.#queues = { preinstall: [], install: [], postinstall: [], prepare: [], bin: [], } } async #build (nodes, { type = 'deps' }) { const timeEnd = time.start(`build:${type}`) await this.#buildQueues(nodes) if (!this.options.ignoreScripts) { await this.#runScripts('preinstall') } // links should run prepare scripts and only link bins after that if (type === 'links') { await this.#runScripts('prepare') } if (this.options.binLinks) { await this.#linkAllBins() } if (!this.options.ignoreScripts) { await this.#runScripts('install') await this.#runScripts('postinstall') } timeEnd() } async #buildQueues (nodes) { const timeEnd = time.start('build:queue') const set = new Set() const promises = [] for (const node of nodes) { promises.push(this.#addToBuildSet(node, set)) // if it has bundle deps, add those too, if rebuildBundle if (this.options.rebuildBundle !== false) { const bd = node.package.bundleDependencies if (bd && bd.length) { dfwalk({ tree: node, leave: node => promises.push(this.#addToBuildSet(node, set)), getChildren: node => [...node.children.values()], filter: node => node.inBundle, }) } } } await promiseAllRejectLate(promises) // now sort into the queues for the 4 things we have to do // run in the same predictable order that buildIdealTree uses // there's no particular reason for doing it in this order rather // than another, but sorting *somehow* makes it consistent. const queue = [...set].sort(sortNodes) for (const node of queue) { const { package: { bin, scripts = {} } } = node.target const { preinstall, install, postinstall, prepare } = scripts const tests = { bin, preinstall, install, postinstall, prepare } for (const [key, has] of Object.entries(tests)) { if (has) { this.#queues[key].push(node) } } } timeEnd() } async [_checkBins] (node) { // if the node is a global top, and we're not in force mode, then // any existing bins need to either be missing, or a symlink into // the node path. Otherwise a package can have a preinstall script // that unlinks something, to allow them to silently overwrite system // binaries, which is unsafe and insecure. if (!node.globalTop || this.options.force) { return } const { path, package: pkg } = node await binLinks.checkBins({ pkg, path, top: true, global: true }) } async #addToBuildSet (node, set, refreshed = false) { if (set.has(node)) { return } if (this.#oldMeta === null) { const { root: { meta } } = node this.#oldMeta = meta && meta.loadedFromDisk && !(meta.originalLockfileVersion >= 2) } const { package: pkg, hasInstallScript } = node.target const { gypfile, bin, scripts = {} } = pkg const { preinstall, install, postinstall, prepare } = scripts const anyScript = preinstall || install || postinstall || prepare if (!refreshed && !anyScript && (hasInstallScript || this.#oldMeta)) { // we either have an old metadata (and thus might have scripts) // or we have an indication that there's install scripts (but // don't yet know what they are) so we have to load the package.json // from disk to see what the deal is. Failure here just means // no scripts to add, probably borked package.json. // add to the set then remove while we're reading the pj, so we // don't accidentally hit it multiple times. set.add(node) const pkg = await rpj(node.path + '/package.json').catch(() => ({})) set.delete(node) const { scripts = {} } = pkg node.package.scripts = scripts return this.#addToBuildSet(node, set, true) } // Rebuild node-gyp dependencies lacking an install or preinstall script // note that 'scripts' might be missing entirely, and the package may // set gypfile:false to avoid this automatic detection. const isGyp = gypfile !== false && !install && !preinstall && await isNodeGypPackage(node.path) if (bin || preinstall || install || postinstall || prepare || isGyp) { if (bin) { await this[_checkBins](node) } if (isGyp) { scripts.install = defaultGypInstallScript node.package.scripts = scripts } set.add(node) } } async #runScripts (event) { const queue = this.#queues[event] if (!queue.length) { return } const timeEnd = time.start(`build:run:${event}`) const stdio = this.options.foregroundScripts ? 'inherit' : 'pipe' const limit = this.options.foregroundScripts ? 1 : undefined await promiseCallLimit(queue.map(node => async () => { const { path, integrity, resolved, optional, peer, dev, devOptional, package: pkg, location, isStoreLink, } = node.target // skip any that we know we'll be deleting // or storeLinks if (this[_trashList].has(path) || isStoreLink) { return } const timeEndLocation = time.start(`build:run:${event}:${location}`) log.info('run', pkg._id, event, location, pkg.scripts[event]) const env = { npm_package_resolved: resolved, npm_package_integrity: integrity, npm_package_json: resolve(path, 'package.json'), npm_package_optional: boolEnv(optional), npm_package_dev: boolEnv(dev), npm_package_peer: boolEnv(peer), npm_package_dev_optional: boolEnv(devOptional && !dev && !optional), } const runOpts = { event, path, pkg, stdio, env, scriptShell: this.options.scriptShell, } const p = runScript(runOpts).catch(er => { const { code, signal } = er log.info('run', pkg._id, event, { code, signal }) throw er }).then(({ args, code, signal, stdout, stderr }) => { this.scriptsRun.add({ pkg, path, event, // I do not know why this needs to be on THIS line but refactoring // this function would be quite a process // eslint-disable-next-line promise/always-return cmd: args && args[args.length - 1], env, code, signal, stdout, stderr, }) log.info('run', pkg._id, event, { code, signal }) }) await (this.#doHandleOptionalFailure ? this[_handleOptionalFailure](node, p) : p) timeEndLocation() }), { limit }) timeEnd() } async #linkAllBins () { const queue = this.#queues.bin if (!queue.length) { return } const timeEnd = time.start('build:link') const promises = [] // sort the queue by node path, so that the module-local collision // detector in bin-links will always resolve the same way. for (const node of queue.sort(sortNodes)) { // TODO these run before they're awaited promises.push(this.#createBinLinks(node)) } await promiseAllRejectLate(promises) timeEnd() } async #createBinLinks (node) { if (this[_trashList].has(node.path)) { return } const timeEnd = time.start(`build:link:${node.location}`) const p = binLinks({ pkg: node.package, path: node.path, top: !!(node.isTop || node.globalTop), force: this.options.force, global: !!node.globalTop, }) await (this.#doHandleOptionalFailure ? this[_handleOptionalFailure](node, p) : p) timeEnd() } } PK ~\X""&@npmcli/arborist/lib/arborist/index.jsnu[// The arborist manages three trees: // - actual // - virtual // - ideal // // The actual tree is what's present on disk in the node_modules tree // and elsewhere that links may extend. // // The virtual tree is loaded from metadata (package.json and lock files). // // The ideal tree is what we WANT that actual tree to become. This starts // with the virtual tree, and then applies the options requesting // add/remove/update actions. // // To reify a tree, we calculate a diff between the ideal and actual trees, // and then turn the actual tree into the ideal tree by taking the actions // required. At the end of the reification process, the actualTree is // updated to reflect the changes. // // Each tree has an Inventory at the root. Shrinkwrap is tracked by Arborist // instance. It always refers to the actual tree, but is updated (and written // to disk) on reification. // Each of the mixin "classes" adds functionality, but are not dependent on // constructor call order. So, we just load them in an array, and build up // the base class, so that the overall voltron class is easier to test and // cover, and separation of concerns can be maintained. const { resolve } = require('node:path') const { homedir } = require('node:os') const { depth } = require('treeverse') const mapWorkspaces = require('@npmcli/map-workspaces') const { log, time } = require('proc-log') const { saveTypeMap } = require('../add-rm-pkg-deps.js') const AuditReport = require('../audit-report.js') const relpath = require('../relpath.js') const PackumentCache = require('../packument-cache.js') const mixins = [ require('../tracker.js'), require('./build-ideal-tree.js'), require('./load-actual.js'), require('./load-virtual.js'), require('./rebuild.js'), require('./reify.js'), require('./isolated-reifier.js'), ] const _setWorkspaces = Symbol.for('setWorkspaces') const Base = mixins.reduce((a, b) => b(a), require('node:events')) // if it's 1, 2, or 3, set it explicitly that. // if undefined or null, set it null // otherwise, throw. const lockfileVersion = lfv => { if (lfv === 1 || lfv === 2 || lfv === 3) { return lfv } if (lfv === undefined || lfv === null) { return null } throw new TypeError('Invalid lockfileVersion config: ' + lfv) } class Arborist extends Base { constructor (options = {}) { const timeEnd = time.start('arborist:ctor') super(options) this.options = { nodeVersion: process.version, ...options, Arborist: this.constructor, binLinks: 'binLinks' in options ? !!options.binLinks : true, cache: options.cache || `${homedir()}/.npm/_cacache`, dryRun: !!options.dryRun, formatPackageLock: 'formatPackageLock' in options ? !!options.formatPackageLock : true, force: !!options.force, global: !!options.global, ignoreScripts: !!options.ignoreScripts, installStrategy: options.global ? 'shallow' : (options.installStrategy ? options.installStrategy : 'hoisted'), lockfileVersion: lockfileVersion(options.lockfileVersion), packageLockOnly: !!options.packageLockOnly, packumentCache: options.packumentCache || new PackumentCache(), path: options.path || '.', rebuildBundle: 'rebuildBundle' in options ? !!options.rebuildBundle : true, replaceRegistryHost: options.replaceRegistryHost, savePrefix: 'savePrefix' in options ? options.savePrefix : '^', scriptShell: options.scriptShell, workspaces: options.workspaces || [], workspacesEnabled: options.workspacesEnabled !== false, } // TODO we only ever look at this.options.replaceRegistryHost, not // this.replaceRegistryHost. Defaulting needs to be written back to // this.options to work properly this.replaceRegistryHost = this.options.replaceRegistryHost = (!this.options.replaceRegistryHost || this.options.replaceRegistryHost === 'npmjs') ? 'registry.npmjs.org' : this.options.replaceRegistryHost if (options.saveType && !saveTypeMap.get(options.saveType)) { throw new Error(`Invalid saveType ${options.saveType}`) } this.cache = resolve(this.options.cache) this.diff = null this.path = resolve(this.options.path) timeEnd() } // TODO: We should change these to static functions instead // of methods for the next major version // Get the actual nodes corresponding to a root node's child workspaces, // given a list of workspace names. workspaceNodes (tree, workspaces) { const wsMap = tree.workspaces if (!wsMap) { log.warn('workspaces', 'filter set, but no workspaces present') return [] } const nodes = [] for (const name of workspaces) { const path = wsMap.get(name) if (!path) { log.warn('workspaces', `${name} in filter set, but not in workspaces`) continue } const loc = relpath(tree.realpath, path) const node = tree.inventory.get(loc) if (!node) { log.warn('workspaces', `${name} in filter set, but no workspace folder present`) continue } nodes.push(node) } return nodes } // returns a set of workspace nodes and all their deps // TODO why is includeWorkspaceRoot a param? // TODO why is workspaces a param? workspaceDependencySet (tree, workspaces, includeWorkspaceRoot) { const wsNodes = this.workspaceNodes(tree, workspaces) if (includeWorkspaceRoot) { for (const edge of tree.edgesOut.values()) { if (edge.type !== 'workspace' && edge.to) { wsNodes.push(edge.to) } } } const wsDepSet = new Set(wsNodes) const extraneous = new Set() for (const node of wsDepSet) { for (const edge of node.edgesOut.values()) { const dep = edge.to if (dep) { wsDepSet.add(dep) if (dep.isLink) { wsDepSet.add(dep.target) } } } for (const child of node.children.values()) { if (child.extraneous) { extraneous.add(child) } } } for (const extra of extraneous) { wsDepSet.add(extra) } return wsDepSet } // returns a set of root dependencies, excluding dependencies that are // exclusively workspace dependencies excludeWorkspacesDependencySet (tree) { const rootDepSet = new Set() depth({ tree, visit: node => { for (const { to } of node.edgesOut.values()) { if (!to || to.isWorkspace) { continue } for (const edgeIn of to.edgesIn.values()) { if (edgeIn.from.isRoot || rootDepSet.has(edgeIn.from)) { rootDepSet.add(to) } } } return node }, filter: node => node, getChildren: (node, tree) => [...tree.edgesOut.values()].map(edge => edge.to), }) return rootDepSet } async [_setWorkspaces] (node) { const workspaces = await mapWorkspaces({ cwd: node.path, pkg: node.package, }) if (node && workspaces.size) { node.workspaces = workspaces } return node } async audit (options = {}) { this.addTracker('audit') if (this.options.global) { throw Object.assign( new Error('`npm audit` does not support testing globals'), { code: 'EAUDITGLOBAL' } ) } // allow the user to set options on the ctor as well. // XXX: deprecate separate method options objects. options = { ...this.options, ...options } const timeEnd = time.start('audit') let tree if (options.packageLock === false) { // build ideal tree await this.loadActual(options) await this.buildIdealTree() tree = this.idealTree } else { tree = await this.loadVirtual() } if (this.options.workspaces.length) { options.filterSet = this.workspaceDependencySet( tree, this.options.workspaces, this.options.includeWorkspaceRoot ) } if (!options.workspacesEnabled) { options.filterSet = this.excludeWorkspacesDependencySet(tree) } this.auditReport = await AuditReport.load(tree, options) const ret = options.fix ? this.reify(options) : this.auditReport timeEnd() this.finishTracker('audit') return ret } async dedupe (options = {}) { // allow the user to set options on the ctor as well. // XXX: deprecate separate method options objects. options = { ...this.options, ...options } const tree = await this.loadVirtual().catch(() => this.loadActual()) const names = [] for (const name of tree.inventory.query('name')) { if (tree.inventory.query('name', name).size > 1) { names.push(name) } } return this.reify({ ...options, preferDedupe: true, update: { names }, }) } } module.exports = Arborist PK ~\kѼ~%~%-@npmcli/arborist/lib/arborist/load-virtual.jsnu[// mixin providing the loadVirtual method const mapWorkspaces = require('@npmcli/map-workspaces') const { resolve } = require('node:path') const nameFromFolder = require('@npmcli/name-from-folder') const consistentResolve = require('../consistent-resolve.js') const Shrinkwrap = require('../shrinkwrap.js') const Node = require('../node.js') const Link = require('../link.js') const relpath = require('../relpath.js') const calcDepFlags = require('../calc-dep-flags.js') const rpj = require('read-package-json-fast') const treeCheck = require('../tree-check.js') const flagsSuspect = Symbol.for('flagsSuspect') const setWorkspaces = Symbol.for('setWorkspaces') module.exports = cls => class VirtualLoader extends cls { #rootOptionProvided constructor (options) { super(options) // the virtual tree we load from a shrinkwrap this.virtualTree = options.virtualTree this[flagsSuspect] = false } // public method async loadVirtual (options = {}) { if (this.virtualTree) { return this.virtualTree } // allow the user to set reify options on the ctor as well. // XXX: deprecate separate reify() options object. options = { ...this.options, ...options } if (options.root && options.root.meta) { await this.#loadFromShrinkwrap(options.root.meta, options.root) return treeCheck(this.virtualTree) } const s = await Shrinkwrap.load({ path: this.path, lockfileVersion: this.options.lockfileVersion, resolveOptions: this.options, }) if (!s.loadedFromDisk && !options.root) { const er = new Error('loadVirtual requires existing shrinkwrap file') throw Object.assign(er, { code: 'ENOLOCK' }) } // when building the ideal tree, we pass in a root node to this function // otherwise, load it from the root package json or the lockfile const { root = await this.#loadRoot(s), } = options this.#rootOptionProvided = options.root await this.#loadFromShrinkwrap(s, root) root.assertRootOverrides() return treeCheck(this.virtualTree) } async #loadRoot (s) { const pj = this.path + '/package.json' const pkg = await rpj(pj).catch(() => s.data.packages['']) || {} return this[setWorkspaces](this.#loadNode('', pkg, true)) } async #loadFromShrinkwrap (s, root) { if (!this.#rootOptionProvided) { // root is never any of these things, but might be a brand new // baby Node object that never had its dep flags calculated. root.extraneous = false root.dev = false root.optional = false root.devOptional = false root.peer = false } else { this[flagsSuspect] = true } this.#checkRootEdges(s, root) root.meta = s this.virtualTree = root const { links, nodes } = this.#resolveNodes(s, root) await this.#resolveLinks(links, nodes) if (!(s.originalLockfileVersion >= 2)) { this.#assignBundles(nodes) } if (this[flagsSuspect]) { // reset all dep flags // can't use inventory here, because virtualTree might not be root for (const node of nodes.values()) { if (node.isRoot || node === this.#rootOptionProvided) { continue } node.extraneous = true node.dev = true node.optional = true node.devOptional = true node.peer = true } calcDepFlags(this.virtualTree, !this.#rootOptionProvided) } return root } // check the lockfile deps, and see if they match. if they do not // then we have to reset dep flags at the end. for example, if the // user manually edits their package.json file, then we need to know // that the idealTree is no longer entirely trustworthy. #checkRootEdges (s, root) { // loaded virtually from tree, no chance of being out of sync // ancient lockfiles are critically damaged by this process, // so we need to just hope for the best in those cases. if (!s.loadedFromDisk || s.ancientLockfile) { return } const lock = s.get('') const prod = lock.dependencies || {} const dev = lock.devDependencies || {} const optional = lock.optionalDependencies || {} const peer = lock.peerDependencies || {} const peerOptional = {} if (lock.peerDependenciesMeta) { for (const [name, meta] of Object.entries(lock.peerDependenciesMeta)) { if (meta.optional && peer[name] !== undefined) { peerOptional[name] = peer[name] delete peer[name] } } } for (const name of Object.keys(optional)) { delete prod[name] } const lockWS = {} const workspaces = mapWorkspaces.virtual({ cwd: this.path, lockfile: s.data, }) for (const [name, path] of workspaces.entries()) { lockWS[name] = `file:${path.replace(/#/g, '%23')}` } // Should rootNames exclude optional? const rootNames = new Set(root.edgesOut.keys()) const lockByType = ({ dev, optional, peer, peerOptional, prod, workspace: lockWS }) // Find anything in shrinkwrap deps that doesn't match root's type or spec for (const type in lockByType) { const deps = lockByType[type] for (const name in deps) { const edge = root.edgesOut.get(name) if (!edge || edge.type !== type || edge.spec !== deps[name]) { return this[flagsSuspect] = true } rootNames.delete(name) } } // Something was in root that's not accounted for in shrinkwrap if (rootNames.size) { return this[flagsSuspect] = true } } // separate out link metadatas, and create Node objects for nodes #resolveNodes (s, root) { const links = new Map() const nodes = new Map([['', root]]) for (const [location, meta] of Object.entries(s.data.packages)) { // skip the root because we already got it if (!location) { continue } if (meta.link) { links.set(location, meta) } else { nodes.set(location, this.#loadNode(location, meta)) } } return { links, nodes } } // links is the set of metadata, and nodes is the map of non-Link nodes // Set the targets to nodes in the set, if we have them (we might not) async #resolveLinks (links, nodes) { for (const [location, meta] of links.entries()) { const targetPath = resolve(this.path, meta.resolved) const targetLoc = relpath(this.path, targetPath) const target = nodes.get(targetLoc) const link = this.#loadLink(location, targetLoc, target, meta) nodes.set(location, link) nodes.set(targetLoc, link.target) // we always need to read the package.json for link targets // outside node_modules because they can be changed by the local user if (!link.target.parent) { const pj = link.realpath + '/package.json' const pkg = await rpj(pj).catch(() => null) if (pkg) { link.target.package = pkg } } } } #assignBundles (nodes) { for (const [location, node] of nodes) { // Skip assignment of parentage for the root package if (!location || node.isLink && !node.target.location) { continue } const { name, parent, package: { inBundle } } = node if (!parent) { continue } // read inBundle from package because 'package' here is // actually a v2 lockfile metadata entry. // If the *parent* is also bundled, though, or if the parent has // no dependency on it, then we assume that it's being pulled in // just by virtue of its parent or a transitive dep being bundled. const { package: ppkg } = parent const { inBundle: parentBundled } = ppkg if (inBundle && !parentBundled && parent.edgesOut.has(node.name)) { if (!ppkg.bundleDependencies) { ppkg.bundleDependencies = [name] } else { ppkg.bundleDependencies.push(name) } } } } #loadNode (location, sw, loadOverrides) { const p = this.virtualTree ? this.virtualTree.realpath : this.path const path = resolve(p, location) // shrinkwrap doesn't include package name unless necessary if (!sw.name) { sw.name = nameFromFolder(path) } const dev = sw.dev const optional = sw.optional const devOptional = dev || optional || sw.devOptional const peer = sw.peer const node = new Node({ installLinks: this.installLinks, legacyPeerDeps: this.legacyPeerDeps, root: this.virtualTree, path, realpath: path, integrity: sw.integrity, resolved: consistentResolve(sw.resolved, this.path, path), pkg: sw, hasShrinkwrap: sw.hasShrinkwrap, dev, optional, devOptional, peer, loadOverrides, }) // cast to boolean because they're undefined in the lock file when false node.extraneous = !!sw.extraneous node.devOptional = !!(sw.devOptional || sw.dev || sw.optional) node.peer = !!sw.peer node.optional = !!sw.optional node.dev = !!sw.dev return node } #loadLink (location, targetLoc, target) { const path = resolve(this.path, location) const link = new Link({ installLinks: this.installLinks, legacyPeerDeps: this.legacyPeerDeps, path, realpath: resolve(this.path, targetLoc), target, pkg: target && target.package, }) link.extraneous = target.extraneous link.devOptional = target.devOptional link.peer = target.peer link.optional = target.optional link.dev = target.dev return link } } PK ~\?&@npmcli/arborist/lib/arborist/reify.jsnu[// mixin implementing the reify method const onExit = require('../signal-handling.js') const pacote = require('pacote') const AuditReport = require('../audit-report.js') const { subset, intersects } = require('semver') const npa = require('npm-package-arg') const semver = require('semver') const debug = require('../debug.js') const { walkUp } = require('walk-up-path') const { log, time } = require('proc-log') const hgi = require('hosted-git-info') const rpj = require('read-package-json-fast') const { dirname, resolve, relative, join } = require('node:path') const { depth: dfwalk } = require('treeverse') const { lstat, mkdir, rm, symlink, } = require('node:fs/promises') const { moveFile } = require('@npmcli/fs') const PackageJson = require('@npmcli/package-json') const packageContents = require('@npmcli/installed-package-contents') const runScript = require('@npmcli/run-script') const { checkEngine, checkPlatform } = require('npm-install-checks') const treeCheck = require('../tree-check.js') const relpath = require('../relpath.js') const Diff = require('../diff.js') const retirePath = require('../retire-path.js') const promiseAllRejectLate = require('promise-all-reject-late') const { callLimit: promiseCallLimit } = require('promise-call-limit') const optionalSet = require('../optional-set.js') const calcDepFlags = require('../calc-dep-flags.js') const { saveTypeMap, hasSubKey } = require('../add-rm-pkg-deps.js') const Shrinkwrap = require('../shrinkwrap.js') const { defaultLockfileVersion } = Shrinkwrap // Part of steps (steps need refactoring before we can do anything about these) const _retireShallowNodes = Symbol.for('retireShallowNodes') const _loadBundlesAndUpdateTrees = Symbol.for('loadBundlesAndUpdateTrees') const _submitQuickAudit = Symbol('submitQuickAudit') const _addOmitsToTrashList = Symbol('addOmitsToTrashList') const _unpackNewModules = Symbol.for('unpackNewModules') const _build = Symbol.for('build') // shared by rebuild mixin const _trashList = Symbol.for('trashList') const _handleOptionalFailure = Symbol.for('handleOptionalFailure') const _loadTrees = Symbol.for('loadTrees') // defined by rebuild mixin const _checkBins = Symbol.for('checkBins') // shared symbols for swapping out when testing // TODO tests should not be this deep into internals const _diffTrees = Symbol.for('diffTrees') const _createSparseTree = Symbol.for('createSparseTree') const _loadShrinkwrapsAndUpdateTrees = Symbol.for('loadShrinkwrapsAndUpdateTrees') const _reifyNode = Symbol.for('reifyNode') const _updateAll = Symbol.for('updateAll') const _updateNames = Symbol.for('updateNames') const _moveContents = Symbol.for('moveContents') const _moveBackRetiredUnchanged = Symbol.for('moveBackRetiredUnchanged') const _removeTrash = Symbol.for('removeTrash') const _renamePath = Symbol.for('renamePath') const _rollbackRetireShallowNodes = Symbol.for('rollbackRetireShallowNodes') const _rollbackCreateSparseTree = Symbol.for('rollbackCreateSparseTree') const _rollbackMoveBackRetiredUnchanged = Symbol.for('rollbackMoveBackRetiredUnchanged') const _saveIdealTree = Symbol.for('saveIdealTree') const _reifyPackages = Symbol.for('reifyPackages') // defined by build-ideal-tree mixin const _resolvedAdd = Symbol.for('resolvedAdd') const _usePackageLock = Symbol.for('usePackageLock') // used by build-ideal-tree mixin const _addNodeToTrashList = Symbol.for('addNodeToTrashList') const _createIsolatedTree = Symbol.for('createIsolatedTree') module.exports = cls => class Reifier extends cls { #bundleMissing = new Set() // child nodes we'd EXPECT to be included in a bundle, but aren't #bundleUnpacked = new Set() // the nodes we unpack to read their bundles #dryRun #nmValidated = new Set() #omitDev #omitPeer #omitOptional #retiredPaths = {} #retiredUnchanged = {} #savePrefix #shrinkwrapInflated = new Set() #sparseTreeDirs = new Set() #sparseTreeRoots = new Set() constructor (options) { super(options) this[_trashList] = new Set() } // public method async reify (options = {}) { const linked = (options.installStrategy || this.options.installStrategy) === 'linked' if (this.options.packageLockOnly && this.options.global) { const er = new Error('cannot generate lockfile for global packages') er.code = 'ESHRINKWRAPGLOBAL' throw er } const omit = new Set(options.omit || []) this.#omitDev = omit.has('dev') this.#omitOptional = omit.has('optional') this.#omitPeer = omit.has('peer') // start tracker block this.addTracker('reify') const timeEnd = time.start('reify') // don't create missing dirs on dry runs if (!this.options.packageLockOnly && !this.options.dryRun) { // we do NOT want to set ownership on this folder, especially // recursively, because it can have other side effects to do that // in a project directory. We just want to make it if it's missing. await mkdir(resolve(this.path), { recursive: true }) // do not allow the top-level node_modules to be a symlink await this.#validateNodeModules(resolve(this.path, 'node_modules')) } await this[_loadTrees](options) const oldTree = this.idealTree if (linked) { // swap out the tree with the isolated tree // this is currently technical debt which will be resolved in a refactor // of Node/Link trees log.warn('reify', 'The "linked" install strategy is EXPERIMENTAL and may contain bugs.') this.idealTree = await this[_createIsolatedTree]() } await this[_diffTrees]() await this[_reifyPackages]() if (linked) { // swap back in the idealTree // so that the lockfile is preserved this.idealTree = oldTree } await this[_saveIdealTree](options) // clean up any trash that is still in the tree for (const path of this[_trashList]) { const loc = relpath(this.idealTree.realpath, path) const node = this.idealTree.inventory.get(loc) if (node && node.root === this.idealTree) { node.parent = null } } // if we filtered to only certain nodes, then anything ELSE needs // to be untouched in the resulting actual tree, even if it differs // in the idealTree. Copy over anything that was in the actual and // was not changed, delete anything in the ideal and not actual. // Then we move the entire idealTree over to this.actualTree, and // save the hidden lockfile. if (this.diff && this.diff.filterSet.size) { const reroot = new Set() const { filterSet } = this.diff const seen = new Set() for (const [loc, ideal] of this.idealTree.inventory.entries()) { seen.add(loc) // if it's an ideal node from the filter set, then skip it // because we already made whatever changes were necessary if (filterSet.has(ideal)) { continue } // otherwise, if it's not in the actualTree, then it's not a thing // that we actually added. And if it IS in the actualTree, then // it's something that we left untouched, so we need to record // that. const actual = this.actualTree.inventory.get(loc) if (!actual) { ideal.root = null } else { if ([...actual.linksIn].some(link => filterSet.has(link))) { seen.add(actual.location) continue } const { realpath, isLink } = actual if (isLink && ideal.isLink && ideal.realpath === realpath) { continue } else { reroot.add(actual) } } } // now find any actual nodes that may not be present in the ideal // tree, but were left behind by virtue of not being in the filter for (const [loc, actual] of this.actualTree.inventory.entries()) { if (seen.has(loc)) { continue } seen.add(loc) // we know that this is something that ISN'T in the idealTree, // or else we will have addressed it in the previous loop. // If it's in the filterSet, that means we intentionally removed // it, so nothing to do here. if (filterSet.has(actual)) { continue } reroot.add(actual) } // go through the rerooted actual nodes, and move them over. for (const actual of reroot) { actual.root = this.idealTree } // prune out any tops that lack a linkIn, they are no longer relevant. for (const top of this.idealTree.tops) { if (top.linksIn.size === 0) { top.root = null } } // need to calculate dep flags, since nodes may have been marked // as extraneous or otherwise incorrect during transit. calcDepFlags(this.idealTree) } // save the ideal's meta as a hidden lockfile after we actualize it this.idealTree.meta.filename = this.idealTree.realpath + '/node_modules/.package-lock.json' this.idealTree.meta.hiddenLockfile = true this.idealTree.meta.lockfileVersion = defaultLockfileVersion this.actualTree = this.idealTree this.idealTree = null if (!this.options.global) { await this.actualTree.meta.save() const ignoreScripts = !!this.options.ignoreScripts // if we aren't doing a dry run or ignoring scripts and we actually made changes to the dep // tree, then run the dependencies scripts if (!this.options.dryRun && !ignoreScripts && this.diff && this.diff.children.length) { const { path, package: pkg } = this.actualTree.target const stdio = this.options.foregroundScripts ? 'inherit' : 'pipe' const { scripts = {} } = pkg for (const event of ['predependencies', 'dependencies', 'postdependencies']) { if (Object.prototype.hasOwnProperty.call(scripts, event)) { log.info('run', pkg._id, event, scripts[event]) await time.start(`reify:run:${event}`, () => runScript({ event, path, pkg, stdio, scriptShell: this.options.scriptShell, })) } } } } // This is a very bad pattern and I can't wait to stop doing it this.auditReport = await this.auditReport this.finishTracker('reify') timeEnd() return treeCheck(this.actualTree) } async [_reifyPackages] () { // we don't submit the audit report or write to disk on dry runs if (this.options.dryRun) { return } if (this.options.packageLockOnly) { // we already have the complete tree, so just audit it now, // and that's all we have to do here. return this[_submitQuickAudit]() } // ok, we're about to start touching the fs. need to roll back // if we get an early termination. let reifyTerminated = null const removeHandler = onExit(({ signal }) => { // only call once. if signal hits twice, we just terminate removeHandler() reifyTerminated = Object.assign(new Error('process terminated'), { signal, }) return false }) // [rollbackfn, [...actions]] // after each step, if the process was terminated, execute the rollback // note that each rollback *also* calls the previous one when it's // finished, and then the first one throws the error, so we only need // a new rollback step when we have a new thing that must be done to // revert the install. const steps = [ [_rollbackRetireShallowNodes, [ _retireShallowNodes, ]], [_rollbackCreateSparseTree, [ _createSparseTree, _addOmitsToTrashList, _loadShrinkwrapsAndUpdateTrees, _loadBundlesAndUpdateTrees, _submitQuickAudit, _unpackNewModules, ]], [_rollbackMoveBackRetiredUnchanged, [ _moveBackRetiredUnchanged, _build, ]], ] for (const [rollback, actions] of steps) { for (const action of actions) { try { await this[action]() if (reifyTerminated) { throw reifyTerminated } } catch (er) { // TODO rollbacks shouldn't be relied on to throw err await this[rollback](er) /* istanbul ignore next - rollback throws, should never hit this */ throw er } } } // no rollback for this one, just exit with the error, since the // install completed and can't be safely recovered at this point. await this[_removeTrash]() if (reifyTerminated) { throw reifyTerminated } // done modifying the file system, no need to keep listening for sigs removeHandler() } // when doing a local install, we load everything and figure it all out. // when doing a global install, we *only* care about the explicit requests. [_loadTrees] (options) { const timeEnd = time.start('reify:loadTrees') const bitOpt = { ...options, complete: this.options.packageLockOnly || this.options.dryRun, } // if we're only writing a package lock, then it doesn't matter what's here if (this.options.packageLockOnly) { return this.buildIdealTree(bitOpt).then(timeEnd) } const actualOpt = this.options.global ? { ignoreMissing: true, global: true, filter: (node, kid) => { // if it's not the project root, and we have no explicit requests, // then we're already into a nested dep, so we keep it if (this.explicitRequests.size === 0 || !node.isProjectRoot) { return true } // if we added it as an edgeOut, then we want it if (this.idealTree.edgesOut.has(kid)) { return true } // if it's an explicit request, then we want it const hasExplicit = [...this.explicitRequests] .some(edge => edge.name === kid) if (hasExplicit) { return true } // ignore the rest of the global install folder return false }, } : { ignoreMissing: true } if (!this.options.global) { return Promise.all([ this.loadActual(actualOpt), this.buildIdealTree(bitOpt), ]).then(timeEnd) } // the global install space tends to have a lot of stuff in it. don't // load all of it, just what we care about. we won't be saving a // hidden lockfile in there anyway. Note that we have to load ideal // BEFORE loading actual, so that the actualOpt can use the // explicitRequests which is set during buildIdealTree return this.buildIdealTree(bitOpt) .then(() => this.loadActual(actualOpt)) .then(timeEnd) } [_diffTrees] () { if (this.options.packageLockOnly) { return } const timeEnd = time.start('reify:diffTrees') // XXX if we have an existing diff already, there should be a way // to just invalidate the parts that changed, but avoid walking the // whole tree again. const includeWorkspaces = this.options.workspacesEnabled const includeRootDeps = !includeWorkspaces || this.options.includeWorkspaceRoot && this.options.workspaces.length > 0 const filterNodes = [] if (this.options.global && this.explicitRequests.size) { const idealTree = this.idealTree.target const actualTree = this.actualTree.target // we ONLY are allowed to make changes in the global top-level // children where there's an explicit request. for (const { name } of this.explicitRequests) { const ideal = idealTree.children.get(name) if (ideal) { filterNodes.push(ideal) } const actual = actualTree.children.get(name) if (actual) { filterNodes.push(actual) } } } else { if (includeWorkspaces) { // add all ws nodes to filterNodes for (const ws of this.options.workspaces) { const ideal = this.idealTree.children.get(ws) if (ideal) { filterNodes.push(ideal) } const actual = this.actualTree.children.get(ws) if (actual) { filterNodes.push(actual) } } } if (includeRootDeps) { // add all non-workspace nodes to filterNodes for (const tree of [this.idealTree, this.actualTree]) { for (const { type, to } of tree.edgesOut.values()) { if (type !== 'workspace' && to) { filterNodes.push(to) } } } } } // find all the nodes that need to change between the actual // and ideal trees. this.diff = Diff.calculate({ shrinkwrapInflated: this.#shrinkwrapInflated, filterNodes, actual: this.actualTree, ideal: this.idealTree, }) // we don't have to add 'removed' folders to the trashlist, because // they'll be moved aside to a retirement folder, and then the retired // folder will be deleted at the end. This is important when we have // a folder like FOO being "removed" in favor of a folder like "foo", // because if we remove node_modules/FOO on case-insensitive systems, // it will remove the dep that we *want* at node_modules/foo. timeEnd() } // add the node and all its bins to the list of things to be // removed later on in the process. optionally, also mark them // as a retired paths, so that we move them out of the way and // replace them when rolling back on failure. [_addNodeToTrashList] (node, retire = false) { const paths = [node.path, ...node.binPaths] const moves = this.#retiredPaths log.silly('reify', 'mark', retire ? 'retired' : 'deleted', paths) for (const path of paths) { if (retire) { const retired = retirePath(path) moves[path] = retired this[_trashList].add(retired) } else { this[_trashList].add(path) } } } // move aside the shallowest nodes in the tree that have to be // changed or removed, so that we can rollback if necessary. [_retireShallowNodes] () { const timeEnd = time.start('reify:retireShallow') const moves = this.#retiredPaths = {} for (const diff of this.diff.children) { if (diff.action === 'CHANGE' || diff.action === 'REMOVE') { // we'll have to clean these up at the end, so add them to the list this[_addNodeToTrashList](diff.actual, true) } } log.silly('reify', 'moves', moves) const movePromises = Object.entries(moves) .map(([from, to]) => this[_renamePath](from, to)) return promiseAllRejectLate(movePromises).then(timeEnd) } [_renamePath] (from, to, didMkdirp = false) { return moveFile(from, to) .catch(er => { // Occasionally an expected bin file might not exist in the package, // or a shim/symlink might have been moved aside. If we've already // handled the most common cause of ENOENT (dir doesn't exist yet), // then just ignore any ENOENT. if (er.code === 'ENOENT') { return didMkdirp ? null : mkdir(dirname(to), { recursive: true }).then(() => this[_renamePath](from, to, true)) } else if (er.code === 'EEXIST') { return rm(to, { recursive: true, force: true }).then(() => moveFile(from, to)) } else { throw er } }) } [_rollbackRetireShallowNodes] (er) { const timeEnd = time.start('reify:rollback:retireShallow') const moves = this.#retiredPaths const movePromises = Object.entries(moves) .map(([from, to]) => this[_renamePath](to, from)) return promiseAllRejectLate(movePromises) // ignore subsequent rollback errors .catch(() => {}) .then(timeEnd) .then(() => { throw er }) } // adding to the trash list will skip reifying, and delete them // if they are currently in the tree and otherwise untouched. [_addOmitsToTrashList] () { if (!this.#omitDev && !this.#omitOptional && !this.#omitPeer) { return } const timeEnd = time.start('reify:trashOmits') for (const node of this.idealTree.inventory.values()) { const { top } = node // if the top is not the root or workspace then we do not want to omit it if (!top.isProjectRoot && !top.isWorkspace) { continue } // if a diff filter has been created, then we do not omit the node if the // top node is not in that set if (this.diff?.filterSet?.size && !this.diff.filterSet.has(top)) { continue } // omit node if the dep type matches any omit flags that were set if ( node.peer && this.#omitPeer || node.dev && this.#omitDev || node.optional && this.#omitOptional || node.devOptional && this.#omitOptional && this.#omitDev ) { this[_addNodeToTrashList](node) } } timeEnd() } [_createSparseTree] () { const timeEnd = time.start('reify:createSparse') // if we call this fn again, we look for the previous list // so that we can avoid making the same directory multiple times const leaves = this.diff.leaves .filter(diff => { return (diff.action === 'ADD' || diff.action === 'CHANGE') && !this.#sparseTreeDirs.has(diff.ideal.path) && !diff.ideal.isLink }) .map(diff => diff.ideal) // we check this in parallel, so guard against multiple attempts to // retire the same path at the same time. const dirsChecked = new Set() return promiseAllRejectLate(leaves.map(async node => { for (const d of walkUp(node.path)) { if (d === node.top.path) { break } if (dirsChecked.has(d)) { continue } dirsChecked.add(d) const st = await lstat(d).catch(() => null) // this can happen if we have a link to a package with a name // that the filesystem treats as if it is the same thing. // would be nice to have conditional istanbul ignores here... /* istanbul ignore next - defense in depth */ if (st && !st.isDirectory()) { const retired = retirePath(d) this.#retiredPaths[d] = retired this[_trashList].add(retired) await this[_renamePath](d, retired) } } this.#sparseTreeDirs.add(node.path) const made = await mkdir(node.path, { recursive: true }) // if the directory already exists, made will be undefined. if that's the case // we don't want to remove it because we aren't the ones who created it so we // omit it from the #sparseTreeRoots if (made) { this.#sparseTreeRoots.add(made) } })).then(timeEnd) } [_rollbackCreateSparseTree] (er) { const timeEnd = time.start('reify:rollback:createSparse') // cut the roots of the sparse tree that were created, not the leaves const roots = this.#sparseTreeRoots // also delete the moves that we retired, so that we can move them back const failures = [] const targets = [...roots, ...Object.keys(this.#retiredPaths)] const unlinks = targets .map(path => rm(path, { recursive: true, force: true }).catch(er => failures.push([path, er]))) return promiseAllRejectLate(unlinks).then(() => { // eslint-disable-next-line promise/always-return if (failures.length) { log.warn('cleanup', 'Failed to remove some directories', failures) } }) .then(timeEnd) .then(() => this[_rollbackRetireShallowNodes](er)) } // shrinkwrap nodes define their dependency branches with a file, so // we need to unpack them, read that shrinkwrap file, and then update // the tree by calling loadVirtual with the node as the root. [_loadShrinkwrapsAndUpdateTrees] () { const seen = this.#shrinkwrapInflated const shrinkwraps = this.diff.leaves .filter(d => (d.action === 'CHANGE' || d.action === 'ADD' || !d.action) && d.ideal.hasShrinkwrap && !seen.has(d.ideal) && !this[_trashList].has(d.ideal.path)) if (!shrinkwraps.length) { return } const timeEnd = time.start('reify:loadShrinkwraps') const Arborist = this.constructor return promiseAllRejectLate(shrinkwraps.map(diff => { const node = diff.ideal seen.add(node) return diff.action ? this[_reifyNode](node) : node })) .then(nodes => promiseAllRejectLate(nodes.map(node => new Arborist({ ...this.options, path: node.path, }).loadVirtual({ root: node })))) // reload the diff and sparse tree because the ideal tree changed .then(() => this[_diffTrees]()) .then(() => this[_createSparseTree]()) .then(() => this[_addOmitsToTrashList]()) .then(() => this[_loadShrinkwrapsAndUpdateTrees]()) .then(timeEnd) } // create a symlink for Links, extract for Nodes // return the node object, since we usually want that // handle optional dep failures here // If node is in trash list, skip it // If reifying fails, and the node is optional, add it and its optionalSet // to the trash list // Always return the node. [_reifyNode] (node) { if (this[_trashList].has(node.path)) { return node } const timeEnd = time.start(`reifyNode:${node.location}`) this.addTracker('reify', node.name, node.location) const { npmVersion, nodeVersion, cpu, os, libc } = this.options const p = Promise.resolve().then(async () => { // when we reify an optional node, check the engine and platform // first. be sure to ignore the --force and --engine-strict flags, // since we always want to skip any optional packages we can't install. // these checks throwing will result in a rollback and removal // of the mismatches // eslint-disable-next-line promise/always-return if (node.optional) { checkEngine(node.package, npmVersion, nodeVersion, false) checkPlatform(node.package, false, { cpu, os, libc }) } await this[_checkBins](node) await this.#extractOrLink(node) const { _id, deprecated } = node.package // The .catch is in _handleOptionalFailure. Not ideal, this should be cleaned up. // eslint-disable-next-line promise/always-return if (deprecated) { log.warn('deprecated', `${_id}: ${deprecated}`) } }) return this[_handleOptionalFailure](node, p) .then(() => { this.finishTracker('reify', node.name, node.location) timeEnd() return node }) } // do not allow node_modules to be a symlink async #validateNodeModules (nm) { if (this.options.force || this.#nmValidated.has(nm)) { return } const st = await lstat(nm).catch(() => null) if (!st || st.isDirectory()) { this.#nmValidated.add(nm) return } log.warn('reify', 'Removing non-directory', nm) await rm(nm, { recursive: true, force: true }) } async #extractOrLink (node) { const nm = resolve(node.parent.path, 'node_modules') await this.#validateNodeModules(nm) if (!node.isLink) { // in normal cases, node.resolved should *always* be set by now. // however, it is possible when a lockfile is damaged, or very old, // or in some other race condition bugs in npm v6, that a previously // bundled dependency will have just a version, but no resolved value, // and no 'bundled: true' setting. // Do the best with what we have, or else remove it from the tree // entirely, since we can't possibly reify it. let res = null if (node.resolved) { const registryResolved = this.#registryResolved(node.resolved) if (registryResolved) { res = `${node.name}@${registryResolved}` } } else if (node.package.name && node.version) { res = `${node.package.name}@${node.version}` } // no idea what this thing is. remove it from the tree. if (!res) { const warning = 'invalid or damaged lockfile detected\n' + 'please re-try this operation once it completes\n' + 'so that the damage can be corrected, or perform\n' + 'a fresh install with no lockfile if the problem persists.' log.warn('reify', warning) log.verbose('reify', 'unrecognized node in tree', node.path) node.parent = null node.fsParent = null this[_addNodeToTrashList](node) return } await debug(async () => { const st = await lstat(node.path).catch(() => null) if (st && !st.isDirectory()) { debug.log('unpacking into a non-directory', node) throw Object.assign(new Error('ENOTDIR: not a directory'), { code: 'ENOTDIR', path: node.path, }) } }) await pacote.extract(res, node.path, { ...this.options, resolved: node.resolved, integrity: node.integrity, }) // store nodes don't use Node class so node.package doesn't get updated if (node.isInStore) { const pkg = await rpj(join(node.path, 'package.json')) node.package.scripts = pkg.scripts } return } // node.isLink await rm(node.path, { recursive: true, force: true }) // symlink const dir = dirname(node.path) const target = node.realpath const rel = relative(dir, target) await mkdir(dir, { recursive: true }) return symlink(rel, node.path, 'junction') } // if the node is optional, then the failure of the promise is nonfatal // just add it and its optional set to the trash list. [_handleOptionalFailure] (node, p) { return (node.optional ? p.catch(() => { const set = optionalSet(node) for (node of set) { log.verbose('reify', 'failed optional dependency', node.path) this[_addNodeToTrashList](node) } }) : p).then(() => node) } #registryResolved (resolved) { // the default registry url is a magic value meaning "the currently // configured registry". // `resolved` must never be falsey. // // XXX: use a magic string that isn't also a valid value, like // ${REGISTRY} or something. This has to be threaded through the // Shrinkwrap and Node classes carefully, so for now, just treat // the default reg as the magical animal that it has been. const resolvedURL = hgi.parseUrl(resolved) if (!resolvedURL) { // if we could not parse the url at all then returning nothing // here means it will get removed from the tree in the next step return } if ((this.options.replaceRegistryHost === resolvedURL.hostname) || this.options.replaceRegistryHost === 'always') { // this.registry always has a trailing slash return `${this.registry.slice(0, -1)}${resolvedURL.pathname}${resolvedURL.searchParams}` } return resolved } // bundles are *sort of* like shrinkwraps, in that the branch is defined // by the contents of the package. however, in their case, rather than // shipping a virtual tree that must be reified, they ship an entire // reified actual tree that must be unpacked and not modified. [_loadBundlesAndUpdateTrees] (depth = 0, bundlesByDepth) { let maxBundleDepth if (!bundlesByDepth) { bundlesByDepth = new Map() maxBundleDepth = -1 dfwalk({ tree: this.diff, visit: diff => { const node = diff.ideal if (!node) { return } if (node.isProjectRoot) { return } const { bundleDependencies } = node.package if (bundleDependencies && bundleDependencies.length) { maxBundleDepth = Math.max(maxBundleDepth, node.depth) if (!bundlesByDepth.has(node.depth)) { bundlesByDepth.set(node.depth, [node]) } else { bundlesByDepth.get(node.depth).push(node) } } }, getChildren: diff => diff.children, }) bundlesByDepth.set('maxBundleDepth', maxBundleDepth) } else { maxBundleDepth = bundlesByDepth.get('maxBundleDepth') } if (depth === 0) { time.start('reify:loadBundles') } if (depth > maxBundleDepth) { // if we did something, then prune the tree and update the diffs if (maxBundleDepth !== -1) { this.#pruneBundledMetadeps(bundlesByDepth) this[_diffTrees]() } time.end('reify:loadBundles') return } // skip any that have since been removed from the tree, eg by a // shallower bundle overwriting them with a bundled meta-dep. const set = (bundlesByDepth.get(depth) || []) .filter(node => node.root === this.idealTree && node.target !== node.root && !this[_trashList].has(node.path)) if (!set.length) { return this[_loadBundlesAndUpdateTrees](depth + 1, bundlesByDepth) } // extract all the nodes with bundles return promiseCallLimit(set.map(node => { return () => { this.#bundleUnpacked.add(node) return this[_reifyNode](node) } }), { rejectLate: true }) // then load their unpacked children and move into the ideal tree .then(nodes => promiseAllRejectLate(nodes.map(async node => { const arb = new this.constructor({ ...this.options, path: node.path, }) const notTransplanted = new Set(node.children.keys()) await arb.loadActual({ root: node, // don't transplant any sparse folders we created // loadActual will set node.package to {} for empty directories // if by chance there are some empty folders in the node_modules // tree for some other reason, then ok, ignore those too. transplantFilter: node => { if (node.package._id) { // it's actually in the bundle if it gets transplanted notTransplanted.delete(node.name) return true } else { return false } }, }) for (const name of notTransplanted) { this.#bundleMissing.add(node.children.get(name)) } }))) // move onto the next level of bundled items .then(() => this[_loadBundlesAndUpdateTrees](depth + 1, bundlesByDepth)) } // https://github.com/npm/cli/issues/1597#issuecomment-667639545 #pruneBundledMetadeps (bundlesByDepth) { const bundleShadowed = new Set() // Example dep graph: // root -> (a, c) // a -> BUNDLE(b) // b -> c // c -> b // // package tree: // root // +-- a // | +-- b(1) // | +-- c(1) // +-- b(2) // +-- c(2) // 1. mark everything that's shadowed by anything in the bundle. This // marks b(2) and c(2). // 2. anything with edgesIn from outside the set, mark not-extraneous, // remove from set. This unmarks c(2). // 3. continue until no change // 4. remove everything in the set from the tree. b(2) is pruned // create the list of nodes shadowed by children of bundlers for (const bundles of bundlesByDepth.values()) { // skip the 'maxBundleDepth' item if (!Array.isArray(bundles)) { continue } for (const node of bundles) { for (const name of node.children.keys()) { const shadow = node.parent.resolve(name) if (!shadow) { continue } bundleShadowed.add(shadow) shadow.extraneous = true } } } // lib -> (a@1.x) BUNDLE(a@1.2.3 (b@1.2.3)) // a@1.2.3 -> (b@1.2.3) // a@1.3.0 -> (b@2) // b@1.2.3 -> () // b@2 -> (c@2) // // root // +-- lib // | +-- a@1.2.3 // | +-- b@1.2.3 // +-- b@2 <-- shadowed, now extraneous // +-- c@2 <-- also shadowed, because only dependent is shadowed for (const shadow of bundleShadowed) { for (const shadDep of shadow.edgesOut.values()) { /* istanbul ignore else - pretty unusual situation, just being * defensive here. Would mean that a bundled dep has a dependency * that is unmet. which, weird, but if you bundle it, we take * whatever you put there and assume the publisher knows best. */ if (shadDep.to) { bundleShadowed.add(shadDep.to) shadDep.to.extraneous = true } } } let changed do { changed = false for (const shadow of bundleShadowed) { for (const edge of shadow.edgesIn) { if (!bundleShadowed.has(edge.from)) { shadow.extraneous = false bundleShadowed.delete(shadow) changed = true break } } } } while (changed) for (const shadow of bundleShadowed) { this[_addNodeToTrashList](shadow) shadow.root = null } } async [_submitQuickAudit] () { if (this.options.audit === false) { this.auditReport = null return } // we submit the quick audit at this point in the process, as soon as // we have all the deps resolved, so that it can overlap with the other // actions as much as possible. Stash the promise, which we resolve // before finishing the reify() and returning the tree. Thus, we do // NOT return the promise, as the intent is for this to run in parallel // with the reification, and be resolved at a later time. const timeEnd = time.start('reify:audit') const options = { ...this.options } const tree = this.idealTree // if we're operating on a workspace, only audit the workspace deps if (this.options.workspaces.length) { options.filterSet = this.workspaceDependencySet( tree, this.options.workspaces, this.options.includeWorkspaceRoot ) } this.auditReport = AuditReport.load(tree, options).then(res => { timeEnd() return res }) } // ok! actually unpack stuff into their target locations! // The sparse tree has already been created, so we walk the diff // kicking off each unpack job. If any fail, we rm the sparse // tree entirely and try to put everything back where it was. [_unpackNewModules] () { const timeEnd = time.start('reify:unpack') const unpacks = [] dfwalk({ tree: this.diff, visit: diff => { // no unpacking if we don't want to change this thing if (diff.action !== 'CHANGE' && diff.action !== 'ADD') { return } const node = diff.ideal const bd = this.#bundleUnpacked.has(node) const sw = this.#shrinkwrapInflated.has(node) const bundleMissing = this.#bundleMissing.has(node) // check whether we still need to unpack this one. // test the inDepBundle last, since that's potentially a tree walk. const doUnpack = node && // can't unpack if removed! // root node already exists !node.isRoot && // already unpacked to read bundle !bd && // already unpacked to read sw !sw && // already unpacked by another dep's bundle (bundleMissing || !node.inDepBundle) if (doUnpack) { unpacks.push(this[_reifyNode](node)) } }, getChildren: diff => diff.children, }) return promiseAllRejectLate(unpacks).then(timeEnd) } // This is the part where we move back the unchanging nodes that were // the children of a node that did change. If this fails, the rollback // is a three-step process. First, we try to move the retired unchanged // nodes BACK to their retirement folders, then delete the sparse tree, // then move everything out of retirement. [_moveBackRetiredUnchanged] () { // get a list of all unchanging children of any shallow retired nodes // if they are not the ancestor of any node in the diff set, then the // directory won't already exist, so just rename it over. // This is sort of an inverse diff tree, of all the nodes where // the actualTree and idealTree _don't_ differ, starting from the // shallowest nodes that we moved aside in the first place. const timeEnd = time.start('reify:unretire') const moves = this.#retiredPaths this.#retiredUnchanged = {} return promiseAllRejectLate(this.diff.children.map(diff => { // skip if nothing was retired if (diff.action !== 'CHANGE' && diff.action !== 'REMOVE') { return } const { path: realFolder } = diff.actual const retireFolder = moves[realFolder] /* istanbul ignore next - should be impossible */ debug(() => { if (!retireFolder) { const er = new Error('trying to un-retire but not retired') throw Object.assign(er, { realFolder, retireFolder, actual: diff.actual, ideal: diff.ideal, action: diff.action, }) } }) this.#retiredUnchanged[retireFolder] = [] return promiseAllRejectLate(diff.unchanged.map(node => { // no need to roll back links, since we'll just delete them anyway if (node.isLink) { return mkdir(dirname(node.path), { recursive: true, force: true }) .then(() => this[_reifyNode](node)) } // will have been moved/unpacked along with bundler if (node.inDepBundle && !this.#bundleMissing.has(node)) { return } this.#retiredUnchanged[retireFolder].push(node) const rel = relative(realFolder, node.path) const fromPath = resolve(retireFolder, rel) // if it has bundleDependencies, then make node_modules. otherwise // skip it. const bd = node.package.bundleDependencies const dir = bd && bd.length ? node.path + '/node_modules' : node.path return mkdir(dir, { recursive: true }).then(() => this[_moveContents](node, fromPath)) })) })).then(timeEnd) } // move the contents from the fromPath to the node.path [_moveContents] (node, fromPath) { return packageContents({ path: fromPath, depth: 1, packageJsonCache: new Map([[fromPath + '/package.json', node.package]]), }).then(res => promiseAllRejectLate(res.map(path => { const rel = relative(fromPath, path) const to = resolve(node.path, rel) return this[_renamePath](path, to) }))) } [_rollbackMoveBackRetiredUnchanged] (er) { const moves = this.#retiredPaths // flip the mapping around to go back const realFolders = new Map(Object.entries(moves).map(([k, v]) => [v, k])) const promises = Object.entries(this.#retiredUnchanged) .map(([retireFolder, nodes]) => promiseAllRejectLate(nodes.map(node => { const realFolder = realFolders.get(retireFolder) const rel = relative(realFolder, node.path) const fromPath = resolve(retireFolder, rel) return this[_moveContents]({ ...node, path: fromPath }, node.path) }))) return promiseAllRejectLate(promises) .then(() => this[_rollbackCreateSparseTree](er)) } [_build] () { const timeEnd = time.start('reify:build') // for all the things being installed, run their appropriate scripts // run in tip->root order, so as to be more likely to build a node's // deps before attempting to build it itself const nodes = [] dfwalk({ tree: this.diff, leave: diff => { if (!diff.ideal.isProjectRoot) { nodes.push(diff.ideal) } }, // process adds before changes, ignore removals getChildren: diff => diff && diff.children, filter: diff => diff.action === 'ADD' || diff.action === 'CHANGE', }) // pick up link nodes from the unchanged list as we want to run their // scripts in every install despite of having a diff status change for (const node of this.diff.unchanged) { const tree = node.root.target // skip links that only live within node_modules as they are most // likely managed by packages we installed, we only want to rebuild // unchanged links we directly manage const linkedFromRoot = node.parent === tree || node.target.fsTop === tree if (node.isLink && linkedFromRoot) { nodes.push(node) } } return this.rebuild({ nodes, handleOptionalFailure: true }).then(timeEnd) } // the tree is pretty much built now, so it's cleanup time. // remove the retired folders, and any deleted nodes // If this fails, there isn't much we can do but tell the user about it. // Thankfully, it's pretty unlikely that it'll fail, since rm is a node builtin. async [_removeTrash] () { const timeEnd = time.start('reify:trash') const promises = [] const failures = [] const _rm = path => rm(path, { recursive: true, force: true }).catch(er => failures.push([path, er])) for (const path of this[_trashList]) { promises.push(_rm(path)) } await promiseAllRejectLate(promises) if (failures.length) { log.warn('cleanup', 'Failed to remove some directories', failures) } timeEnd() } // last but not least, we save the ideal tree metadata to the package-lock // or shrinkwrap file, and any additions or removals to package.json async [_saveIdealTree] (options) { // the ideal tree is actualized now, hooray! // it still contains all the references to optional nodes that were removed // for install failures. Those still end up in the shrinkwrap, so we // save it first, then prune out the optional trash, and then return it. const save = !(options.save === false) // we check for updates in order to make sure we run save ideal tree // even though save=false since we want `npm update` to be able to // write to package-lock files by default const hasUpdates = this[_updateAll] || this[_updateNames].length // we're going to completely skip save ideal tree in case of a global or // dry-run install and also if the save option is set to false, EXCEPT for // update since the expected behavior for npm7+ is for update to // NOT save to package.json, we make that exception since we still want // saveIdealTree to be able to write the lockfile by default. const saveIdealTree = !( (!save && !hasUpdates) || this.options.global || this.options.dryRun ) if (!saveIdealTree) { return false } const timeEnd = time.start('reify:save') const updatedTrees = new Set() const updateNodes = nodes => { for (const { name, tree: addTree } of nodes) { // addTree either the root, or a workspace const edge = addTree.edgesOut.get(name) const pkg = addTree.package const req = npa.resolve(name, edge.spec, addTree.realpath) const { rawSpec, subSpec } = req const spec = subSpec ? subSpec.rawSpec : rawSpec const child = edge.to // if we tried to install an optional dep, but it was a version // that we couldn't resolve, this MAY be missing. if we haven't // blown up by now, it's because it was not a problem, though, so // just move on. if (!child || !addTree.isTop) { continue } let newSpec // True if the dependency is getting installed from a local file path // In this case it is not possible to do the normal version comparisons // as the new version will be a file path const isLocalDep = req.type === 'directory' || req.type === 'file' if (req.registry) { const version = child.version const prefixRange = version ? this.options.savePrefix + version : '*' // if we installed a range, then we save the range specified // if it is not a subset of the ^x.y.z. eg, installing a range // of `1.x <1.2.3` will not be saved as `^1.2.0`, because that // would allow versions outside the requested range. Tags and // specific versions save with the save-prefix. const isRange = (subSpec || req).type === 'range' let range = spec if ( !isRange || spec === '*' || subset(prefixRange, spec, { loose: true }) ) { range = prefixRange } const pname = child.packageName const alias = name !== pname newSpec = alias ? `npm:${pname}@${range}` : range } else if (req.hosted) { // save the git+https url if it has auth, otherwise shortcut const h = req.hosted const opt = { noCommittish: false } if (h.https && h.auth) { newSpec = `git+${h.https(opt)}` } else { newSpec = h.shortcut(opt) } } else if (isLocalDep) { // when finding workspace nodes, make sure that // we save them using their version instead of // using their relative path if (edge.type === 'workspace') { const { version } = edge.to.target const prefixRange = version ? this.options.savePrefix + version : '*' newSpec = prefixRange } else { // save the relative path in package.json // Normally saveSpec is updated with the proper relative // path already, but it's possible to specify a full absolute // path initially, in which case we can end up with the wrong // thing, so just get the ultimate fetchSpec and relativize it. const p = req.fetchSpec.replace(/^file:/, '') const rel = relpath(addTree.realpath, p).replace(/#/g, '%23') newSpec = `file:${rel}` } } else { newSpec = req.saveSpec } if (options.saveType) { const depType = saveTypeMap.get(options.saveType) pkg[depType][name] = newSpec // rpj will have moved it here if it was in both // if it is empty it will be deleted later if (options.saveType === 'prod' && pkg.optionalDependencies) { delete pkg.optionalDependencies[name] } } else { if (hasSubKey(pkg, 'dependencies', name)) { pkg.dependencies[name] = newSpec } if (hasSubKey(pkg, 'devDependencies', name)) { pkg.devDependencies[name] = newSpec // don't update peer or optional if we don't have to if (hasSubKey(pkg, 'peerDependencies', name) && (isLocalDep || !intersects(newSpec, pkg.peerDependencies[name]))) { pkg.peerDependencies[name] = newSpec } if (hasSubKey(pkg, 'optionalDependencies', name) && (isLocalDep || !intersects(newSpec, pkg.optionalDependencies[name]))) { pkg.optionalDependencies[name] = newSpec } } else { if (hasSubKey(pkg, 'peerDependencies', name)) { pkg.peerDependencies[name] = newSpec } if (hasSubKey(pkg, 'optionalDependencies', name)) { pkg.optionalDependencies[name] = newSpec } } } updatedTrees.add(addTree) } } // Returns true if any of the edges from this node has a semver // range definition that is an exact match to the version installed // e.g: should return true if for a given an installed version 1.0.0, // range is either =1.0.0 or 1.0.0 const exactVersion = node => { for (const edge of node.edgesIn) { try { if (semver.subset(edge.spec, node.version)) { return false } } catch { // ignore errors } } return true } // helper that retrieves an array of nodes that were // potentially updated during the reify process, in order // to limit the number of nodes to check and update, only // select nodes from the inventory that are direct deps // of a given package.json (project root or a workspace) // and in ase of using a list of `names`, restrict nodes // to only names that are found in this list const retrieveUpdatedNodes = names => { const filterDirectDependencies = node => !node.isRoot && node.resolveParent && node.resolveParent.isRoot && (!names || names.includes(node.name)) && exactVersion(node) // skip update for exact ranges const directDeps = this.idealTree.inventory .filter(filterDirectDependencies) // traverses the list of direct dependencies and collect all nodes // to be updated, since any of them might have changed during reify const nodes = [] for (const node of directDeps) { for (const edgeIn of node.edgesIn) { nodes.push({ name: node.name, tree: edgeIn.from.target, }) } } return nodes } if (save) { // when using update all alongside with save, we'll make // sure to refresh every dependency of the root idealTree if (this[_updateAll]) { const nodes = retrieveUpdatedNodes() updateNodes(nodes) } else { // resolvedAdd is the list of user add requests, but with names added // to things like git repos and tarball file/urls. However, if the // user requested 'foo@', and we have a foo@file:../foo, then we should // end up saving the spec we actually used, not whatever they gave us. if (this[_resolvedAdd].length) { updateNodes(this[_resolvedAdd]) } // if updating given dependencies by name, restrict the list of // nodes to check to only those currently in _updateNames if (this[_updateNames].length) { const nodes = retrieveUpdatedNodes(this[_updateNames]) updateNodes(nodes) } // grab any from explicitRequests that had deps removed for (const { from: tree } of this.explicitRequests) { updatedTrees.add(tree) } } } if (save) { for (const tree of updatedTrees) { // refresh the edges so they have the correct specs tree.package = tree.package const pkgJson = await PackageJson.load(tree.path, { create: true }) const { dependencies = {}, devDependencies = {}, optionalDependencies = {}, peerDependencies = {}, // bundleDependencies is not required by PackageJson like the other // fields here PackageJson also doesn't omit an empty array for this // field so defaulting this to an empty array would add that field to // every package.json file. bundleDependencies, } = tree.package pkgJson.update({ dependencies, devDependencies, optionalDependencies, peerDependencies, bundleDependencies, }) await pkgJson.save() } } // before now edge specs could be changing, affecting the `requires` field // in the package lock, so we hold off saving to the very last action if (this[_usePackageLock]) { // preserve indentation, if possible let format = this.idealTree.package[Symbol.for('indent')] if (format === undefined) { format = ' ' } // TODO this ignores options.save await this.idealTree.meta.save({ format: (this.options.formatPackageLock && format) ? format : this.options.formatPackageLock, }) } timeEnd() return true } } PK ~\o1@npmcli/arborist/lib/arborist/build-ideal-tree.jsnu[// mixin implementing the buildIdealTree method const localeCompare = require('@isaacs/string-locale-compare')('en') const rpj = require('read-package-json-fast') const npa = require('npm-package-arg') const pacote = require('pacote') const cacache = require('cacache') const { callLimit: promiseCallLimit } = require('promise-call-limit') const realpath = require('../../lib/realpath.js') const { resolve, dirname } = require('node:path') const treeCheck = require('../tree-check.js') const { readdirScoped } = require('@npmcli/fs') const { lstat, readlink } = require('node:fs/promises') const { depth } = require('treeverse') const { log, time } = require('proc-log') const { redact } = require('@npmcli/redact') const { OK, REPLACE, CONFLICT, } = require('../can-place-dep.js') const PlaceDep = require('../place-dep.js') const debug = require('../debug.js') const fromPath = require('../from-path.js') const calcDepFlags = require('../calc-dep-flags.js') const Shrinkwrap = require('../shrinkwrap.js') const { defaultLockfileVersion } = Shrinkwrap const Node = require('../node.js') const Link = require('../link.js') const addRmPkgDeps = require('../add-rm-pkg-deps.js') const optionalSet = require('../optional-set.js') const { checkEngine, checkPlatform } = require('npm-install-checks') const relpath = require('../relpath.js') const resetDepFlags = require('../reset-dep-flags.js') // note: some of these symbols are shared so we can hit // them with unit tests and reuse them across mixins const _updateAll = Symbol.for('updateAll') const _flagsSuspect = Symbol.for('flagsSuspect') const _setWorkspaces = Symbol.for('setWorkspaces') const _updateNames = Symbol.for('updateNames') const _resolvedAdd = Symbol.for('resolvedAdd') const _usePackageLock = Symbol.for('usePackageLock') const _rpcache = Symbol.for('realpathCache') const _stcache = Symbol.for('statCache') // used by Reify mixin const _addNodeToTrashList = Symbol.for('addNodeToTrashList') // Push items in, pop them sorted by depth and then path // Sorts physically shallower deps up to the front of the queue, because // they'll affect things deeper in, then alphabetical for consistency between // installs class DepsQueue { #deps = [] #sorted = true get length () { return this.#deps.length } push (item) { if (!this.#deps.includes(item)) { this.#sorted = false this.#deps.push(item) } } pop () { if (!this.#sorted) { this.#deps.sort((a, b) => (a.depth - b.depth) || localeCompare(a.path, b.path)) this.#sorted = true } return this.#deps.shift() } } module.exports = cls => class IdealTreeBuilder extends cls { #complete #currentDep = null #depsQueue = new DepsQueue() #depsSeen = new Set() #explicitRequests = new Set() #follow #installStrategy #linkNodes = new Set() #loadFailures = new Set() #manifests = new Map() #mutateTree = false // a map of each module in a peer set to the thing that depended on // that set of peers in the first place. Use a WeakMap so that we // don't hold onto references for nodes that are garbage collected. #peerSetSource = new WeakMap() #preferDedupe = false #prune #strictPeerDeps #virtualRoots = new Map() constructor (options) { super(options) // normalize trailing slash const registry = options.registry || 'https://registry.npmjs.org' options.registry = this.registry = registry.replace(/\/+$/, '') + '/' const { follow = false, installStrategy = 'hoisted', idealTree = null, installLinks = false, legacyPeerDeps = false, packageLock = true, strictPeerDeps = false, workspaces, global, } = options this.#strictPeerDeps = !!strictPeerDeps this.idealTree = idealTree this.installLinks = installLinks this.legacyPeerDeps = legacyPeerDeps this[_usePackageLock] = packageLock this.#installStrategy = global ? 'shallow' : installStrategy this.#follow = !!follow if (workspaces?.length && global) { throw new Error('Cannot operate on workspaces in global mode') } this[_updateAll] = false this[_updateNames] = [] this[_resolvedAdd] = [] } get explicitRequests () { return new Set(this.#explicitRequests) } // public method async buildIdealTree (options = {}) { if (this.idealTree) { return this.idealTree } // allow the user to set reify options on the ctor as well. // XXX: deprecate separate reify() options object. options = { ...this.options, ...options } // an empty array or any falsey value is the same as null if (!options.add || options.add.length === 0) { options.add = null } if (!options.rm || options.rm.length === 0) { options.rm = null } const timeEnd = time.start('idealTree') if (!options.add && !options.rm && !options.update && this.options.global) { throw new Error('global requires add, rm, or update option') } // first get the virtual tree, if possible. If there's a lockfile, then // that defines the ideal tree, unless the root package.json is not // satisfied by what the ideal tree provides. // from there, we start adding nodes to it to satisfy the deps requested // by the package.json in the root. this.#parseSettings(options) // start tracker block this.addTracker('idealTree') try { await this.#initTree() await this.#inflateAncientLockfile() await this.#applyUserRequests(options) await this.#buildDeps() await this.#fixDepFlags() await this.#pruneFailedOptional() await this.#checkEngineAndPlatform() } finally { timeEnd() this.finishTracker('idealTree') } return treeCheck(this.idealTree) } async #checkEngineAndPlatform () { const { engineStrict, npmVersion, nodeVersion } = this.options for (const node of this.idealTree.inventory.values()) { if (!node.optional) { try { checkEngine(node.package, npmVersion, nodeVersion, this.options.force) } catch (err) { if (engineStrict) { throw err } log.warn(err.code, err.message, { package: err.pkgid, required: err.required, current: err.current, }) } checkPlatform(node.package, this.options.force) } } } #parseSettings (options) { const update = options.update === true ? { all: true } : Array.isArray(options.update) ? { names: options.update } : options.update || {} if (update.all || !Array.isArray(update.names)) { update.names = [] } this.#complete = !!options.complete this.#preferDedupe = !!options.preferDedupe // validates list of update names, they must // be dep names only, no semver ranges are supported for (const name of update.names) { const spec = npa(name) const validationError = new TypeError(`Update arguments must only contain package names, eg: npm update ${spec.name}`) validationError.code = 'EUPDATEARGS' // If they gave us anything other than a bare package name if (spec.raw !== spec.name) { throw validationError } } this[_updateNames] = update.names this[_updateAll] = update.all // we prune by default unless explicitly set to boolean false this.#prune = options.prune !== false // set if we add anything, but also set here if we know we'll make // changes and thus have to maybe prune later. this.#mutateTree = !!( options.add || options.rm || update.all || update.names.length ) } // load the initial tree, either the virtualTree from a shrinkwrap, // or just the root node from a package.json async #initTree () { const timeEnd = time.start('idealTree:init') let root if (this.options.global) { root = await this.#globalRootNode() } else { try { const pkg = await rpj(this.path + '/package.json') root = await this.#rootNodeFromPackage(pkg) } catch (err) { if (err.code === 'EJSONPARSE') { throw err } root = await this.#rootNodeFromPackage({}) } } return this[_setWorkspaces](root) // ok to not have a virtual tree. probably initial install. // When updating all, we load the shrinkwrap, but don't bother // to build out the full virtual tree from it, since we'll be // reconstructing it anyway. .then(root => this.options.global ? root : !this[_usePackageLock] || this[_updateAll] ? Shrinkwrap.reset({ path: this.path, lockfileVersion: this.options.lockfileVersion, resolveOptions: this.options, }).then(meta => Object.assign(root, { meta })) : this.loadVirtual({ root })) // if we don't have a lockfile to go from, then start with the // actual tree, so we only make the minimum required changes. // don't do this for global installs or updates, because in those // cases we don't use a lockfile anyway. // Load on a new Arborist object, so the Nodes aren't the same, // or else it'll get super confusing when we change them! .then(async root => { if ((!this[_updateAll] && !this.options.global && !root.meta.loadedFromDisk) || (this.options.global && this[_updateNames].length)) { await new this.constructor(this.options).loadActual({ root }) const tree = root.target // even though we didn't load it from a package-lock.json FILE, // we still loaded it "from disk", meaning we have to reset // dep flags before assuming that any mutations were reflected. if (tree.children.size) { root.meta.loadedFromDisk = true // set these so that we don't try to ancient lockfile reload it root.meta.originalLockfileVersion = root.meta.lockfileVersion = this.options.lockfileVersion || defaultLockfileVersion } } root.meta.inferFormattingOptions(root.package) return root }) .then(tree => { // search the virtual tree for invalid edges, if any are found add their source to // the depsQueue so that we'll fix it later depth({ tree, getChildren: (node) => { const children = [] for (const edge of node.edgesOut.values()) { children.push(edge.to) } return children }, filter: node => node, visit: node => { for (const edge of node.edgesOut.values()) { if (!edge.valid) { this.#depsQueue.push(node) break // no need to continue the loop after the first hit } } }, }) // null the virtual tree, because we're about to hack away at it // if you want another one, load another copy. this.idealTree = tree this.virtualTree = null timeEnd() return tree }) } async #globalRootNode () { const root = await this.#rootNodeFromPackage({ dependencies: {} }) // this is a gross kludge to handle the fact that we don't save // metadata on the root node in global installs, because the "root" // node is something like /usr/local/lib. const meta = new Shrinkwrap({ path: this.path, lockfileVersion: this.options.lockfileVersion, resolveOptions: this.options, }) meta.reset() root.meta = meta return root } async #rootNodeFromPackage (pkg) { // if the path doesn't exist, then we explode at this point. Note that // this is not a problem for reify(), since it creates the root path // before ever loading trees. // TODO: make buildIdealTree() and loadActual handle a missing root path, // or a symlink to a missing target, and let reify() create it as needed. const real = await realpath(this.path, this[_rpcache], this[_stcache]) const Cls = real === this.path ? Node : Link const root = new Cls({ path: this.path, realpath: real, pkg, extraneous: false, dev: false, devOptional: false, peer: false, optional: false, global: this.options.global, installLinks: this.installLinks, legacyPeerDeps: this.legacyPeerDeps, loadOverrides: true, }) if (root.isLink) { root.target = new Node({ path: real, realpath: real, pkg, extraneous: false, dev: false, devOptional: false, peer: false, optional: false, global: this.options.global, installLinks: this.installLinks, legacyPeerDeps: this.legacyPeerDeps, root, }) } return root } // process the add/rm requests by modifying the root node, and the // update.names request by queueing nodes dependent on those named. async #applyUserRequests (options) { const timeEnd = time.start('idealTree:userRequests') const tree = this.idealTree.target if (!this.options.workspaces.length) { await this.#applyUserRequestsToNode(tree, options) } else { const nodes = this.workspaceNodes(tree, this.options.workspaces) if (this.options.includeWorkspaceRoot) { nodes.push(tree) } const appliedRequests = nodes.map( node => this.#applyUserRequestsToNode(node, options) ) await Promise.all(appliedRequests) } timeEnd() } async #applyUserRequestsToNode (tree, options) { // If we have a list of package names to update, and we know it's // going to update them wherever they are, add any paths into those // named nodes to the buildIdealTree queue. if (!this.options.global && this[_updateNames].length) { this.#queueNamedUpdates() } // global updates only update the globalTop nodes, but we need to know // that they're there, and not reinstall the world unnecessarily. const globalExplicitUpdateNames = [] if (this.options.global && (this[_updateAll] || this[_updateNames].length)) { const nm = resolve(this.path, 'node_modules') const paths = await readdirScoped(nm).catch(() => []) for (const p of paths) { const name = p.replace(/\\/g, '/') tree.package.dependencies = tree.package.dependencies || {} const updateName = this[_updateNames].includes(name) if (this[_updateAll] || updateName) { if (updateName) { globalExplicitUpdateNames.push(name) } const dir = resolve(nm, name) const st = await lstat(dir) .catch(/* istanbul ignore next */ () => null) if (st && st.isSymbolicLink()) { const target = await readlink(dir) const real = resolve(dirname(dir), target).replace(/#/g, '%23') tree.package.dependencies[name] = `file:${real}` } else { tree.package.dependencies[name] = '*' } } } } if (this.auditReport && this.auditReport.size > 0) { await this.#queueVulnDependents(options) } const { add, rm } = options if (rm && rm.length) { addRmPkgDeps.rm(tree.package, rm) for (const name of rm) { this.#explicitRequests.add({ from: tree, name, action: 'DELETE' }) } } if (add && add.length) { await this.#add(tree, options) } // triggers a refresh of all edgesOut. this has to be done BEFORE // adding the edges to explicitRequests, because the package setter // resets all edgesOut. if (add && add.length || rm && rm.length || this.options.global) { tree.package = tree.package } for (const spec of this[_resolvedAdd]) { if (spec.tree === tree) { this.#explicitRequests.add(tree.edgesOut.get(spec.name)) } } for (const name of globalExplicitUpdateNames) { this.#explicitRequests.add(tree.edgesOut.get(name)) } this.#depsQueue.push(tree) } // This returns a promise because we might not have the name yet, and need to // call pacote.manifest to find the name. async #add (tree, { add, saveType = null, saveBundle = false }) { // If we have a link it will need to be added relative to the target's path const path = tree.target.path // get the name for each of the specs in the list. // ie, doing `foo@bar` we just return foo but if it's a url or git, we // don't know the name until we fetch it and look in its manifest. await Promise.all(add.map(async rawSpec => { // We do NOT provide the path to npa here, because user-additions need to // be resolved relative to the tree being added to. let spec = npa(rawSpec) // if it's just @'' then we reload whatever's there, or get latest // if it's an explicit tag, we need to install that specific tag version const isTag = spec.rawSpec && spec.type === 'tag' // look up the names of file/directory/git specs if (!spec.name || isTag) { const mani = await pacote.manifest(spec, { ...this.options }) if (isTag) { // translate tag to a version spec = npa(`${mani.name}@${mani.version}`) } spec.name = mani.name } const { name } = spec if (spec.type === 'file') { spec = npa(`file:${relpath(path, spec.fetchSpec).replace(/#/g, '%23')}`, path) spec.name = name } else if (spec.type === 'directory') { try { const real = await realpath(spec.fetchSpec, this[_rpcache], this[_stcache]) spec = npa(`file:${relpath(path, real).replace(/#/g, '%23')}`, path) spec.name = name } catch { // TODO: create synthetic test case to simulate realpath failure } } spec.tree = tree this[_resolvedAdd].push(spec) })) // now this._resolvedAdd is a list of spec objects with names. // find a home for each of them! addRmPkgDeps.add({ pkg: tree.package, add: this[_resolvedAdd], saveBundle, saveType, }) } // TODO: provide a way to fix bundled deps by exposing metadata about // what's in the bundle at each published manifest. Without that, we // can't possibly fix bundled deps without breaking a ton of other stuff, // and leaving the user subject to getting it overwritten later anyway. async #queueVulnDependents (options) { for (const vuln of this.auditReport.values()) { for (const node of vuln.nodes) { const bundler = node.getBundler() // XXX this belongs in the audit report itself, not here. // We shouldn't even get these things here, and they shouldn't // be printed by npm-audit-report as if they can be fixed, because // they can't. if (bundler) { log.warn(`audit fix ${node.name}@${node.version}`, `${node.location}\nis a bundled dependency of\n${ bundler.name}@${bundler.version} at ${bundler.location}\n` + 'It cannot be fixed automatically.\n' + `Check for updates to the ${bundler.name} package.`) continue } for (const edge of node.edgesIn) { this.addTracker('idealTree', edge.from.name, edge.from.location) this.#depsQueue.push(edge.from) } } } // note any that can't be fixed at the root level without --force // if there's a fix, we use that. otherwise, the user has to remove it, // find a different thing, fix the upstream, etc. // // XXX: how to handle top nodes that aren't the root? Maybe the report // just tells the user to cd into that directory and fix it? if (this.options.force && this.auditReport && this.auditReport.topVulns.size) { options.add = options.add || [] options.rm = options.rm || [] const nodesTouched = new Set() for (const [name, topVuln] of this.auditReport.topVulns.entries()) { const { simpleRange, topNodes, fixAvailable, } = topVuln for (const node of topNodes) { if (!node.isProjectRoot && !node.isWorkspace) { // not something we're going to fix, sorry. have to cd into // that directory and fix it yourself. log.warn('audit', 'Manual fix required in linked project ' + `at ./${node.location} for ${name}@${simpleRange}.\n` + `'cd ./${node.location}' and run 'npm audit' for details.`) continue } if (!fixAvailable) { log.warn('audit', `No fix available for ${name}@${simpleRange}`) continue } // name may be different if parent fixes the dep // see Vuln fixAvailable setter const { isSemVerMajor, version, name: fixName } = fixAvailable const breakingMessage = isSemVerMajor ? 'a SemVer major change' : 'outside your stated dependency range' log.warn('audit', `Updating ${fixName} to ${version}, ` + `which is ${breakingMessage}.`) await this.#add(node, { add: [`${fixName}@${version}`] }) nodesTouched.add(node) } } for (const node of nodesTouched) { node.package = node.package } } } #avoidRange (name) { if (!this.auditReport) { return null } const vuln = this.auditReport.get(name) if (!vuln) { return null } return vuln.range } #queueNamedUpdates () { // ignore top nodes, since they are not loaded the same way, and // probably have their own project associated with them. // for every node with one of the names on the list, we add its // dependents to the queue to be evaluated. in buildDepStep, // anything on the update names list will get refreshed, even if // it isn't a problem. // XXX this could be faster by doing a series of inventory.query('name') // calls rather than walking over everything in the tree. for (const node of this.idealTree.inventory.values()) { // XXX add any invalid edgesOut to the queue if (this[_updateNames].includes(node.name) && !node.isTop && !node.inDepBundle && !node.inShrinkwrap) { for (const edge of node.edgesIn) { this.addTracker('idealTree', edge.from.name, edge.from.location) this.#depsQueue.push(edge.from) } } } } async #inflateAncientLockfile () { const { meta, inventory } = this.idealTree const ancient = meta.ancientLockfile const old = meta.loadedFromDisk && !(meta.originalLockfileVersion >= 2) if (inventory.size === 0 || !ancient && !old) { return } // if the lockfile is from node v5 or earlier, then we'll have to reload // all the manifests of everything we encounter. this is costly, but at // least it's just a one-time hit. const timeEnd = time.start('idealTree:inflate') // don't warn if we're not gonna actually write it back anyway. const heading = ancient ? 'ancient lockfile' : 'old lockfile' if (ancient || !this.options.lockfileVersion || this.options.lockfileVersion >= defaultLockfileVersion) { log.warn(heading, ` The ${meta.type} file was created with an old version of npm, so supplemental metadata must be fetched from the registry. This is a one-time fix-up, please be patient... `) } this.addTracker('idealTree:inflate') const queue = [] for (const node of inventory.values()) { if (node.isProjectRoot) { continue } // if the node's location isn't within node_modules then this is actually // a link target, so skip it. the link node itself will be queued later. if (!node.location.startsWith('node_modules')) { continue } queue.push(async () => { log.silly('inflate', node.location) const { resolved, version, path, name, location, integrity } = node // don't try to hit the registry for linked deps const useResolved = resolved && ( !version || resolved.startsWith('file:') ) const id = useResolved ? resolved : version const spec = npa.resolve(name, id, dirname(path)) const t = `idealTree:inflate:${location}` this.addTracker(t) try { const mani = await pacote.manifest(spec, { ...this.options, resolved: resolved, integrity: integrity, fullMetadata: false, }) node.package = { ...mani, _id: `${mani.name}@${mani.version}` } } catch (er) { const warning = `Could not fetch metadata for ${name}@${id}` log.warn(heading, warning, er) } this.finishTracker(t) }) } await promiseCallLimit(queue) // have to re-calc dep flags, because the nodes don't have edges // until their packages get assigned, so everything looks extraneous calcDepFlags(this.idealTree) // yes, yes, this isn't the "original" version, but now that it's been // upgraded, we need to make sure we don't do the work to upgrade it // again, since it's now as new as can be. if (!this.options.lockfileVersion && !meta.hiddenLockfile) { meta.originalLockfileVersion = defaultLockfileVersion } this.finishTracker('idealTree:inflate') timeEnd() } // at this point we have a virtual tree with the actual root node's // package deps, which may be partly or entirely incomplete, invalid // or extraneous. #buildDeps () { const timeEnd = time.start('idealTree:buildDeps') const tree = this.idealTree.target tree.assertRootOverrides() this.#depsQueue.push(tree) // XXX also push anything that depends on a node with a name // in the override list log.silly('idealTree', 'buildDeps') this.addTracker('idealTree', tree.name, '') return this.#buildDepStep().then(timeEnd) } async #buildDepStep () { // removes tracker of previous dependency in the queue if (this.#currentDep) { const { location, name } = this.#currentDep time.end(`idealTree:${location || '#root'}`) this.finishTracker('idealTree', name, location) this.#currentDep = null } if (!this.#depsQueue.length) { return this.#resolveLinks() } const node = this.#depsQueue.pop() const bd = node.package.bundleDependencies const hasBundle = bd && Array.isArray(bd) && bd.length const { hasShrinkwrap } = node // if the node was already visited, or has since been removed from the // tree, skip over it and process the rest of the queue. If a node has // a shrinkwrap, also skip it, because it's going to get its deps // satisfied by whatever's in that file anyway. if (this.#depsSeen.has(node) || node.root !== this.idealTree || hasShrinkwrap && !this.#complete) { return this.#buildDepStep() } this.#depsSeen.add(node) this.#currentDep = node time.start(`idealTree:${node.location || '#root'}`) // if we're loading a _complete_ ideal tree, for a --package-lock-only // installation for example, we have to crack open the tarball and // look inside if it has bundle deps or shrinkwraps. note that this is // not necessary during a reification, because we just update the // ideal tree by reading bundles/shrinkwraps in place. // Don't bother if the node is from the actual tree and hasn't // been resolved, because we can't fetch it anyway, could be anything! const crackOpen = this.#complete && node !== this.idealTree && node.resolved && (hasBundle || hasShrinkwrap) if (crackOpen) { const Arborist = this.constructor const opt = { ...this.options } await cacache.tmp.withTmp(this.cache, opt, async path => { await pacote.extract(node.resolved, path, { ...opt, Arborist, resolved: node.resolved, integrity: node.integrity, }) if (hasShrinkwrap) { await new Arborist({ ...this.options, path }) .loadVirtual({ root: node }) } if (hasBundle) { await new Arborist({ ...this.options, path }) .loadActual({ root: node, ignoreMissing: true }) } }) } // if any deps are missing or invalid, then we fetch the manifest for // the thing we want, and build a new dep node from that. // Then, find the ideal placement for that node. The ideal placement // searches from the node's deps (or parent deps in the case of non-root // peer deps), and walks up the tree until it finds the highest spot // where it doesn't cause any conflicts. // // A conflict can be: // - A node by that name already exists at that location. // - The parent has a peer dep on that name // - One of the node's peer deps conflicts at that location, unless the // peer dep is met by a node at that location, which is fine. // // If we create a new node, then build its ideal deps as well. // // Note: this is the same "maximally naive" deduping tree-building // algorithm that npm has used since v3. In a case like this: // // root -> (a@1, b@1||2) // a -> (b@1) // // You'll end up with a tree like this: // // root // +-- a@1 // | +-- b@1 // +-- b@2 // // rather than this, more deduped, but just as correct tree: // // root // +-- a@1 // +-- b@1 // // Another way to look at it is that this algorithm favors getting higher // version deps at higher levels in the tree, even if that reduces // potential deduplication. // // Set `preferDedupe: true` in the options to replace the shallower // dep if allowed. const tasks = [] const peerSource = this.#peerSetSource.get(node) || node for (const edge of this.#problemEdges(node)) { if (edge.peerConflicted) { continue } // peerSetSource is only relevant when we have a peerEntryEdge // otherwise we're setting regular non-peer deps as if they have // a virtual root of whatever brought in THIS node. // so we VR the node itself if the edge is not a peer const source = edge.peer ? peerSource : node const virtualRoot = this.#virtualRoot(source, true) // reuse virtual root if we already have one, but don't // try to do the override ahead of time, since we MAY be able // to create a more correct tree than the virtual root could. const vrEdge = virtualRoot && virtualRoot.edgesOut.get(edge.name) const vrDep = vrEdge && vrEdge.valid && vrEdge.to // only re-use the virtualRoot if it's a peer edge we're placing. // otherwise, we end up in situations where we override peer deps that // we could have otherwise found homes for. Eg: // xy -> (x, y) // x -> PEER(z@1) // y -> PEER(z@2) // If xy is a dependency, we can resolve this like: // project // +-- xy // | +-- y // | +-- z@2 // +-- x // +-- z@1 // But if x and y are loaded in the same virtual root, then they will // be forced to agree on a version of z. const required = new Set([edge.from]) const parent = edge.peer ? virtualRoot : null const dep = vrDep && vrDep.satisfies(edge) ? vrDep : await this.#nodeFromEdge(edge, parent, null, required) /* istanbul ignore next */ debug(() => { if (!dep) { throw new Error('no dep??') } }) tasks.push({ edge, dep }) } const placeDeps = tasks.sort((a, b) => localeCompare(a.edge.name, b.edge.name)) const promises = [] for (const { edge, dep } of placeDeps) { const pd = new PlaceDep({ edge, dep, auditReport: this.auditReport, explicitRequest: this.#explicitRequests.has(edge), force: this.options.force, installLinks: this.installLinks, installStrategy: this.#installStrategy, legacyPeerDeps: this.legacyPeerDeps, preferDedupe: this.#preferDedupe, strictPeerDeps: this.#strictPeerDeps, updateNames: this[_updateNames], }) // placing a dep is actually a tree of placing the dep itself // and all of its peer group that aren't already met by the tree depth({ tree: pd, getChildren: pd => pd.children, visit: pd => { const { placed, edge, canPlace: cpd } = pd // if we didn't place anything, nothing to do here if (!placed) { return } // we placed something, that means we changed the tree if (placed.errors.length) { this.#loadFailures.add(placed) } this.#mutateTree = true if (cpd.canPlaceSelf === OK) { for (const edgeIn of placed.edgesIn) { if (edgeIn === edge) { continue } const { from, valid, peerConflicted } = edgeIn if (!peerConflicted && !valid && !this.#depsSeen.has(from)) { this.addTracker('idealTree', from.name, from.location) this.#depsQueue.push(edgeIn.from) } } } else { /* istanbul ignore else - should be only OK or REPLACE here */ if (cpd.canPlaceSelf === REPLACE) { // this may also create some invalid edges, for example if we're // intentionally causing something to get nested which was // previously placed in this location. for (const edgeIn of placed.edgesIn) { if (edgeIn === edge) { continue } const { valid, peerConflicted } = edgeIn if (!valid && !peerConflicted) { // if it's already been visited, we have to re-visit // otherwise, just enqueue normally. this.#depsSeen.delete(edgeIn.from) this.#depsQueue.push(edgeIn.from) } } } } /* istanbul ignore if - should be impossible */ if (cpd.canPlaceSelf === CONFLICT) { debug(() => { const er = new Error('placed with canPlaceSelf=CONFLICT') throw Object.assign(er, { placeDep: pd }) }) return } // lastly, also check for the missing deps of the node we placed, // and any holes created by pruning out conflicted peer sets. this.#depsQueue.push(placed) for (const dep of pd.needEvaluation) { this.#depsSeen.delete(dep) this.#depsQueue.push(dep) } // pre-fetch any problem edges, since we'll need these soon // if it fails at this point, though, dont' worry because it // may well be an optional dep that has gone missing. it'll // fail later anyway. for (const e of this.#problemEdges(placed)) { // XXX This is somehow load bearing. This makes tests that print // the ideal tree of a tree with tarball dependencies fail. This // can't be changed or removed till we figure out why // The test is named "tarball deps with transitive tarball deps" promises.push(() => this.#fetchManifest(npa.resolve(e.name, e.spec, fromPath(placed, e))) .catch(() => null) ) } }, }) } for (const { to } of node.edgesOut.values()) { if (to && to.isLink && to.target) { this.#linkNodes.add(to) } } await promiseCallLimit(promises) return this.#buildDepStep() } // loads a node from an edge, and then loads its peer deps (and their // peer deps, on down the line) into a virtual root parent. async #nodeFromEdge (edge, parent_, secondEdge, required) { // create a virtual root node with the same deps as the node that // is requesting this one, so that we can get all the peer deps in // a context where they're likely to be resolvable. // Note that the virtual root will also have virtual copies of the // targets of any child Links, so that they resolve appropriately. const parent = parent_ || this.#virtualRoot(edge.from) const spec = npa.resolve(edge.name, edge.spec, edge.from.path) const first = await this.#nodeFromSpec(edge.name, spec, parent, edge) // we might have a case where the parent has a peer dependency on // `foo@*` which resolves to v2, but another dep in the set has a // peerDependency on `foo@1`. In that case, if we force it to be v2, // we're unnecessarily triggering an ERESOLVE. // If we have a second edge to worry about, and it's not satisfied // by the first node, try a second and see if that satisfies the // original edge here. const spec2 = secondEdge && npa.resolve( edge.name, secondEdge.spec, secondEdge.from.path ) const second = secondEdge && !secondEdge.valid ? await this.#nodeFromSpec(edge.name, spec2, parent, secondEdge) : null // pick the second one if they're both happy with that, otherwise first const node = second && edge.valid ? second : first // ensure the one we want is the one that's placed node.parent = parent if (required.has(edge.from) && edge.type !== 'peerOptional' || secondEdge && ( required.has(secondEdge.from) && secondEdge.type !== 'peerOptional')) { required.add(node) } // keep track of the thing that caused this node to be included. const src = parent.sourceReference this.#peerSetSource.set(node, src) // do not load the peers along with the set if this is a global top pkg // otherwise we'll be tempted to put peers as other top-level installed // things, potentially clobbering what's there already, which is not // what we want. the missing edges will be picked up on the next pass. if (this.options.global && edge.from.isProjectRoot) { return node } // otherwise, we have to make sure that our peers can go along with us. return this.#loadPeerSet(node, required) } #virtualRoot (node, reuse = false) { if (reuse && this.#virtualRoots.has(node)) { return this.#virtualRoots.get(node) } const vr = new Node({ path: node.realpath, sourceReference: node, installLinks: this.installLinks, legacyPeerDeps: this.legacyPeerDeps, overrides: node.overrides, }) // also need to set up any targets from any link deps, so that // they are properly reflected in the virtual environment for (const child of node.children.values()) { if (child.isLink) { new Node({ path: child.realpath, sourceReference: child.target, root: vr, }) } } this.#virtualRoots.set(node, vr) return vr } #problemEdges (node) { // skip over any bundled deps, they're not our problem. // Note that this WILL fetch bundled meta-deps which are also dependencies // but not listed as bundled deps. When reifying, we first unpack any // nodes that have bundleDependencies, then do a loadActual on them, move // the nodes into the ideal tree, and then prune. So, fetching those // possibly-bundled meta-deps at this point doesn't cause any worse // problems than a few unnecessary packument fetches. // also skip over any nodes in the tree that failed to load, since those // will crash the install later on anyway. const bd = node.isProjectRoot || node.isWorkspace ? null : node.package.bundleDependencies const bundled = new Set(bd || []) const problems = [] for (const edge of node.edgesOut.values()) { // If it's included in a bundle, we take whatever is specified. if (bundled.has(edge.name)) { continue } // If it's already been logged as a load failure, skip it. if (edge.to && this.#loadFailures.has(edge.to)) { continue } // If it's shrinkwrapped, we use what the shrinkwap wants. if (edge.to && edge.to.inShrinkwrap) { continue } // If the edge has no destination, that's a problem, unless // if it's peerOptional and not explicitly requested. if (!edge.to) { if (edge.type !== 'peerOptional' || this.#explicitRequests.has(edge)) { problems.push(edge) } continue } // If the edge has an error, there's a problem. if (!edge.valid) { problems.push(edge) continue } // If the edge is a workspace, and it's valid, leave it alone if (edge.to.isWorkspace) { continue } // user explicitly asked to update this package by name, problem if (this[_updateNames].includes(edge.name)) { problems.push(edge) continue } // fixing a security vulnerability with this package, problem if (this.auditReport && this.auditReport.isVulnerable(edge.to)) { problems.push(edge) continue } // user has explicitly asked to install this package, problem if (this.#explicitRequests.has(edge)) { problems.push(edge) continue } } return problems } async #fetchManifest (spec) { const options = { ...this.options, avoid: this.#avoidRange(spec.name), fullMetadata: true, } // get the intended spec and stored metadata from yarn.lock file, // if available and valid. spec = this.idealTree.meta.checkYarnLock(spec, options) if (this.#manifests.has(spec.raw)) { return this.#manifests.get(spec.raw) } else { log.silly('fetch manifest', spec.raw.replace(spec.rawSpec, redact(spec.rawSpec))) const mani = await pacote.manifest(spec, options) this.#manifests.set(spec.raw, mani) return mani } } #nodeFromSpec (name, spec, parent, edge) { // pacote will slap integrity on its options, so we have to clone // the object so it doesn't get mutated. // Don't bother to load the manifest for link deps, because the target // might be within another package that doesn't exist yet. const { installLinks, legacyPeerDeps } = this const isWorkspace = this.idealTree.workspaces && this.idealTree.workspaces.has(spec.name) // spec is a directory, link it unless installLinks is set or it's a workspace // TODO post arborist refactor, will need to check for installStrategy=linked if (spec.type === 'directory' && (isWorkspace || !installLinks)) { return this.#linkFromSpec(name, spec, parent, edge) } // if the spec matches a workspace name, then see if the workspace node will // satisfy the edge. if it does, we return the workspace node to make sure it // takes priority. if (isWorkspace) { const existingNode = this.idealTree.edgesOut.get(spec.name).to if (existingNode && existingNode.isWorkspace && existingNode.satisfies(edge)) { return existingNode } } // spec isn't a directory, and either isn't a workspace or the workspace we have // doesn't satisfy the edge. try to fetch a manifest and build a node from that. return this.#fetchManifest(spec) .then(pkg => new Node({ name, pkg, parent, installLinks, legacyPeerDeps }), error => { error.requiredBy = edge.from.location || '.' // failed to load the spec, either because of enotarget or // fetch failure of some other sort. save it so we can verify // later that it's optional, otherwise the error is fatal. const n = new Node({ name, parent, error, installLinks, legacyPeerDeps, }) this.#loadFailures.add(n) return n }) } #linkFromSpec (name, spec, parent) { const realpath = spec.fetchSpec const { installLinks, legacyPeerDeps } = this return rpj(realpath + '/package.json').catch(() => ({})).then(pkg => { const link = new Link({ name, parent, realpath, pkg, installLinks, legacyPeerDeps }) this.#linkNodes.add(link) return link }) } // load all peer deps and meta-peer deps into the node's parent // At the end of this, the node's peer-type outward edges are all // resolved, and so are all of theirs, but other dep types are not. // We prefer to get peer deps that meet the requiring node's dependency, // if possible, since that almost certainly works (since that package was // developed with this set of deps) and will typically be more restrictive. // Note that the peers in the set can conflict either with each other, // or with a direct dependency from the virtual root parent! In strict // mode, this is always an error. In force mode, it never is, and we // prefer the parent's non-peer dep over a peer dep, or the version that // gets placed first. In non-strict mode, we behave strictly if the // virtual root is based on the root project, and allow non-peer parent // deps to override, but throw if no preference can be determined. async #loadPeerSet (node, required) { const peerEdges = [...node.edgesOut.values()] // we typically only install non-optional peers, but we have to // factor them into the peerSet so that we can avoid conflicts .filter(e => e.peer && !(e.valid && e.to)) .sort(({ name: a }, { name: b }) => localeCompare(a, b)) for (const edge of peerEdges) { // already placed this one, and we're happy with it. if (edge.valid && edge.to) { continue } const parentEdge = node.parent.edgesOut.get(edge.name) const { isProjectRoot, isWorkspace } = node.parent.sourceReference const isMine = isProjectRoot || isWorkspace const conflictOK = this.options.force || !isMine && !this.#strictPeerDeps if (!edge.to) { if (!parentEdge) { // easy, just put the thing there await this.#nodeFromEdge(edge, node.parent, null, required) continue } else { // if the parent's edge is very broad like >=1, and the edge in // question is something like 1.x, then we want to get a 1.x, not // a 2.x. pass along the child edge as an advisory guideline. // if the parent edge doesn't satisfy the child edge, and the // child edge doesn't satisfy the parent edge, then we have // a conflict. this is always a problem in strict mode, never // in force mode, and a problem in non-strict mode if this isn't // on behalf of our project. in all such cases, we warn at least. const dep = await this.#nodeFromEdge( parentEdge, node.parent, edge, required ) // hooray! that worked! if (edge.valid) { continue } // allow it. either we're overriding, or it's not something // that will be installed by default anyway, and we'll fail when // we get to the point where we need to, if we need to. if (conflictOK || !required.has(dep)) { edge.peerConflicted = true continue } // problem this.#failPeerConflict(edge, parentEdge) } } // There is something present already, and we're not happy about it // See if the thing we WOULD be happy with is also going to satisfy // the other dependents on the current node. const current = edge.to const dep = await this.#nodeFromEdge(edge, null, null, required) if (dep.canReplace(current)) { await this.#nodeFromEdge(edge, node.parent, null, required) continue } // at this point we know that there is a dep there, and // we don't like it. always fail strictly, always allow forcibly or // in non-strict mode if it's not our fault. don't warn here, because // we are going to warn again when we place the deps, if we end up // overriding for something else. If the thing that has this dep // isn't also required, then there's a good chance we won't need it, // so allow it for now and let it conflict if it turns out to actually // be necessary for the installation. if (conflictOK || !required.has(edge.from)) { continue } // ok, it's the root, or we're in unforced strict mode, so this is bad this.#failPeerConflict(edge, parentEdge) } return node } #failPeerConflict (edge, currentEdge) { const expl = this.#explainPeerConflict(edge, currentEdge) throw Object.assign(new Error('unable to resolve dependency tree'), expl) } #explainPeerConflict (edge, currentEdge) { const node = edge.from const curNode = node.resolve(edge.name) const current = curNode.explain() return { code: 'ERESOLVE', current, // it SHOULD be impossible to get here without a current node in place, // but this at least gives us something report on when bugs creep into // the tree handling logic. currentEdge: currentEdge ? currentEdge.explain() : null, edge: edge.explain(), strictPeerDeps: this.#strictPeerDeps, force: this.options.force, } } // go through all the links in the this.#linkNodes set // for each one: // - if outside the root, ignore it, assume it's fine, it's not our problem // - if a node in the tree already, assign the target to that node. // - if a path under an existing node, then assign that as the fsParent, // and add it to the _depsQueue // // call buildDepStep if anything was added to the queue, otherwise we're done #resolveLinks () { for (const link of this.#linkNodes) { this.#linkNodes.delete(link) // link we never ended up placing, skip it if (link.root !== this.idealTree) { continue } const tree = this.idealTree.target const external = !link.target.isDescendantOf(tree) // outside the root, somebody else's problem, ignore it if (external && !this.#follow) { continue } // didn't find a parent for it or it has not been seen yet // so go ahead and process it. const unseenLink = (link.target.parent || link.target.fsParent) && !this.#depsSeen.has(link.target) if (this.#follow && !link.target.parent && !link.target.fsParent || unseenLink) { this.addTracker('idealTree', link.target.name, link.target.location) this.#depsQueue.push(link.target) } } if (this.#depsQueue.length) { return this.#buildDepStep() } } #fixDepFlags () { const timeEnd = time.start('idealTree:fixDepFlags') const metaFromDisk = this.idealTree.meta.loadedFromDisk const flagsSuspect = this[_flagsSuspect] const mutateTree = this.#mutateTree // if the options set prune:false, then we don't prune, but we still // mark the extraneous items in the tree if we modified it at all. // If we did no modifications, we just iterate over the extraneous nodes. // if we started with an empty tree, then the dep flags are already // all set to true, and there can be nothing extraneous, so there's // nothing to prune, because we built it from scratch. if we didn't // add or remove anything, then also nothing to do. if (metaFromDisk && mutateTree) { resetDepFlags(this.idealTree) } // update all the dev/optional/etc flags in the tree // either we started with a fresh tree, or we // reset all the flags to find the extraneous nodes. // // if we started from a blank slate, or changed something, then // the dep flags will be all set to true. if (!metaFromDisk || mutateTree) { calcDepFlags(this.idealTree) } else { // otherwise just unset all the flags on the root node // since they will sometimes have the default value this.idealTree.extraneous = false this.idealTree.dev = false this.idealTree.optional = false this.idealTree.devOptional = false this.idealTree.peer = false } // at this point, any node marked as extraneous should be pruned. // if we started from a shrinkwrap, and then added/removed something, // then the tree is suspect. Prune what is marked as extraneous. // otherwise, don't bother. const needPrune = metaFromDisk && (mutateTree || flagsSuspect) if (this.#prune && needPrune) { this.#idealTreePrune() for (const node of this.idealTree.inventory.values()) { if (node.extraneous) { node.parent = null } } } timeEnd() } #idealTreePrune () { for (const node of this.idealTree.inventory.values()) { if (node.extraneous) { node.parent = null } } } #pruneFailedOptional () { for (const node of this.#loadFailures) { if (!node.optional) { throw node.errors[0] } const set = optionalSet(node) for (const node of set) { node.parent = null } } } async prune (options = {}) { // allow the user to set options on the ctor as well. // XXX: deprecate separate method options objects. options = { ...this.options, ...options } await this.buildIdealTree(options) this.#idealTreePrune() if (!this.options.workspacesEnabled) { const excludeNodes = this.excludeWorkspacesDependencySet(this.idealTree) for (const node of this.idealTree.inventory.values()) { if ( node.parent !== null && !node.isProjectRoot && !excludeNodes.has(node) ) { this[_addNodeToTrashList](node) } } } return this.reify(options) } } PK ~\=,@npmcli/arborist/lib/case-insensitive-map.jsnu[// package children are represented with a Map object, but many file systems // are case-insensitive and unicode-normalizing, so we need to treat // node.children.get('FOO') and node.children.get('foo') as the same thing. module.exports = class CIMap extends Map { #keys = new Map() constructor (items = []) { super() for (const [key, val] of items) { this.set(key, val) } } #normKey (key) { if (typeof key !== 'string') { return key } return key.normalize('NFKD').toLowerCase() } get (key) { const normKey = this.#normKey(key) return this.#keys.has(normKey) ? super.get(this.#keys.get(normKey)) : undefined } set (key, val) { const normKey = this.#normKey(key) if (this.#keys.has(normKey)) { super.delete(this.#keys.get(normKey)) } this.#keys.set(normKey, key) return super.set(key, val) } delete (key) { const normKey = this.#normKey(key) if (this.#keys.has(normKey)) { const prevKey = this.#keys.get(normKey) this.#keys.delete(normKey) return super.delete(prevKey) } } has (key) { const normKey = this.#normKey(key) return this.#keys.has(normKey) && super.has(this.#keys.get(normKey)) } } PK ~\wII$@npmcli/arborist/lib/optional-set.jsnu[// when an optional dep fails to install, we need to remove the branch of the // graph up to the first optionalDependencies, as well as any nodes that are // only required by other nodes in the set. // // This function finds the set of nodes that will need to be removed in that // case. // // Note that this is *only* going to work with trees where calcDepFlags // has been called, because we rely on the node.optional flag. const gatherDepSet = require('./gather-dep-set.js') const optionalSet = node => { if (!node.optional) { return new Set() } // start with the node, then walk up the dependency graph until we // get to the boundaries that define the optional set. since the // node is optional, we know that all paths INTO this area of the // graph are optional, but there may be non-optional dependencies // WITHIN the area. const set = new Set([node]) for (const node of set) { for (const edge of node.edgesIn) { if (!edge.optional) { set.add(edge.from) } } } // now that we've hit the boundary, gather the rest of the nodes in // the optional section. that's the set of dependencies that are only // depended upon by other nodes within the set, or optional dependencies // from outside the set. return gatherDepSet(set, edge => !edge.optional) } module.exports = optionalSet PK ~\ee@npmcli/arborist/lib/signals.jsnu[// copied from signal-exit // This is not the set of all possible signals. // // It IS, however, the set of all signals that trigger // an exit on either Linux or BSD systems. Linux is a // superset of the signal names supported on BSD, and // the unknown signals just fail to register, so we can // catch that easily enough. // // Don't bother with SIGKILL. It's uncatchable, which // means that we can't fire any callbacks anyway. // // If a user does happen to register a handler on a non- // fatal signal like SIGWINCH or something, and then // exit, it'll end up firing `process.emit('exit')`, so // the handler will be fired anyway. // // SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised // artificially, inherently leave the process in a // state from which it is not safe to try and enter JS // listeners. const platform = global.__ARBORIST_FAKE_PLATFORM__ || process.platform module.exports = [ 'SIGABRT', 'SIGALRM', 'SIGHUP', 'SIGINT', 'SIGTERM', ] if (platform !== 'win32') { module.exports.push( 'SIGVTALRM', 'SIGXCPU', 'SIGXFSZ', 'SIGUSR2', 'SIGTRAP', 'SIGSYS', 'SIGQUIT', 'SIGIOT' // should detect profiler and enable/disable accordingly. // see #21 // 'SIGPROF' ) } if (platform === 'linux') { module.exports.push( 'SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT', 'SIGUNUSED' ) } PK ~\|<@npmcli/arborist/lib/relpath.jsnu[const { relative } = require('node:path') const relpath = (from, to) => relative(from, to).replace(/\\/g, '/') module.exports = relpath PK ~\h=*=*!@npmcli/arborist/lib/yarn-lock.jsnu[// parse a yarn lock file // basic format // // [, ...]: // // : // // // Assume that any key or value might be quoted, though that's only done // in practice if certain chars are in the string. When writing back, we follow // Yarn's rules for quoting, to cause minimal friction. // // The data format would support nested objects, but at this time, it // appears that yarn does not use that for anything, so in the interest // of a simpler parser algorithm, this implementation only supports a // single layer of sub objects. // // This doesn't deterministically define the shape of the tree, and so // cannot be used (on its own) for Arborist.loadVirtual. // But it can give us resolved, integrity, and version, which is useful // for Arborist.loadActual and for building the ideal tree. // // At the very least, when a yarn.lock file is present, we update it // along the way, and save it back in Shrinkwrap.save() // // NIHing this rather than using @yarnpkg/lockfile because that module // is an impenetrable 10kloc of webpack flow output, which is overkill // for something relatively simple and tailored to Arborist's use case. const localeCompare = require('@isaacs/string-locale-compare')('en') const consistentResolve = require('./consistent-resolve.js') const { dirname } = require('node:path') const { breadth } = require('treeverse') // Sort Yarn entries respecting the yarn.lock sort order const yarnEntryPriorities = { name: 1, version: 2, uid: 3, resolved: 4, integrity: 5, registry: 6, dependencies: 7, } const priorityThenLocaleCompare = (a, b) => { if (!yarnEntryPriorities[a] && !yarnEntryPriorities[b]) { return localeCompare(a, b) } /* istanbul ignore next */ return (yarnEntryPriorities[a] || 100) > (yarnEntryPriorities[b] || 100) ? 1 : -1 } const quoteIfNeeded = val => { if ( typeof val === 'boolean' || typeof val === 'number' || val.startsWith('true') || val.startsWith('false') || /[:\s\n\\",[\]]/g.test(val) || !/^[a-zA-Z]/g.test(val) ) { return JSON.stringify(val) } return val } // sort a key/value object into a string of JSON stringified keys and vals const sortKV = obj => Object.keys(obj) .sort(localeCompare) .map(k => ` ${quoteIfNeeded(k)} ${quoteIfNeeded(obj[k])}`) .join('\n') // for checking against previous entries const match = (p, n) => p.integrity && n.integrity ? p.integrity === n.integrity : p.resolved && n.resolved ? p.resolved === n.resolved : p.version && n.version ? p.version === n.version : true const prefix = `# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1 ` const nullSymbol = Symbol('null') class YarnLock { static parse (data) { return new YarnLock().parse(data) } static fromTree (tree) { return new YarnLock().fromTree(tree) } constructor () { this.entries = null this.endCurrent() } endCurrent () { this.current = null this.subkey = nullSymbol } parse (data) { const ENTRY_START = /^[^\s].*:$/ const SUBKEY = /^ {2}[^\s]+:$/ const SUBVAL = /^ {4}[^\s]+ .+$/ const METADATA = /^ {2}[^\s]+ .+$/ this.entries = new Map() this.current = null const linere = /([^\r\n]*)\r?\n/gm let match let lineNum = 0 if (!/\n$/.test(data)) { data += '\n' } while (match = linere.exec(data)) { const line = match[1] lineNum++ if (line.charAt(0) === '#') { continue } if (line === '') { this.endCurrent() continue } if (ENTRY_START.test(line)) { this.endCurrent() const specs = this.splitQuoted(line.slice(0, -1), /, */) this.current = new YarnLockEntry(specs) specs.forEach(spec => this.entries.set(spec, this.current)) continue } if (SUBKEY.test(line)) { this.subkey = line.slice(2, -1) this.current[this.subkey] = {} continue } if (SUBVAL.test(line) && this.current && this.current[this.subkey]) { const subval = this.splitQuoted(line.trimLeft(), ' ') if (subval.length === 2) { this.current[this.subkey][subval[0]] = subval[1] continue } } // any other metadata if (METADATA.test(line) && this.current) { const metadata = this.splitQuoted(line.trimLeft(), ' ') if (metadata.length === 2) { // strip off the legacy shasum hashes if (metadata[0] === 'resolved') { metadata[1] = metadata[1].replace(/#.*/, '') } this.current[metadata[0]] = metadata[1] continue } } throw Object.assign(new Error('invalid or corrupted yarn.lock file'), { position: match.index, content: match[0], line: lineNum, }) } this.endCurrent() return this } splitQuoted (str, delim) { // a,"b,c",d"e,f => ['a','"b','c"','d"e','f'] => ['a','b,c','d"e','f'] const split = str.split(delim) const out = [] let o = 0 for (let i = 0; i < split.length; i++) { const chunk = split[i] if (/^".*"$/.test(chunk)) { out[o++] = chunk.trim().slice(1, -1) } else if (/^"/.test(chunk)) { let collect = chunk.trimLeft().slice(1) while (++i < split.length) { const n = split[i] // something that is not a slash, followed by an even number // of slashes then a " then end => ending on an unescaped " if (/[^\\](\\\\)*"$/.test(n)) { collect += n.trimRight().slice(0, -1) break } else { collect += n } } out[o++] = collect } else { out[o++] = chunk.trim() } } return out } toString () { return prefix + [...new Set([...this.entries.values()])] .map(e => e.toString()) .sort((a, b) => localeCompare(a.replace(/"/g, ''), b.replace(/"/g, ''))).join('\n\n') + '\n' } fromTree (tree) { this.entries = new Map() // walk the tree in a deterministic order, breadth-first, alphabetical breadth({ tree, visit: node => this.addEntryFromNode(node), getChildren: node => [...node.children.values(), ...node.fsChildren] .sort((a, b) => a.depth - b.depth || localeCompare(a.name, b.name)), }) return this } addEntryFromNode (node) { const specs = [...node.edgesIn] .map(e => `${node.name}@${e.spec}`) .sort(localeCompare) // Note: // yarn will do excessive duplication in a case like this: // root -> (x@1.x, y@1.x, z@1.x) // y@1.x -> (x@1.1, z@2.x) // z@1.x -> () // z@2.x -> (x@1.x) // // where x@1.2 exists, because the "x@1.x" spec will *always* resolve // to x@1.2, which doesn't work for y's dep on x@1.1, so you'll get this: // // root // +-- x@1.2.0 // +-- y // | +-- x@1.1.0 // | +-- z@2 // | +-- x@1.2.0 // +-- z@1 // // instead of this more deduped tree that arborist builds by default: // // root // +-- x@1.2.0 (dep is x@1.x, from root) // +-- y // | +-- x@1.1.0 // | +-- z@2 (dep on x@1.x deduped to x@1.1.0 under y) // +-- z@1 // // In order to not create an invalid yarn.lock file with conflicting // entries, AND not tell yarn to create an invalid tree, we need to // ignore the x@1.x spec coming from z, since it's already in the entries. // // So, if the integrity and resolved don't match a previous entry, skip it. // We call this method on shallower nodes first, so this is fine. const n = this.entryDataFromNode(node) let priorEntry = null const newSpecs = [] for (const s of specs) { const prev = this.entries.get(s) // no previous entry for this spec at all, so it's new if (!prev) { // if we saw a match already, then assign this spec to it as well if (priorEntry) { priorEntry.addSpec(s) } else { newSpecs.push(s) } continue } const m = match(prev, n) // there was a prior entry, but a different thing. skip this one if (!m) { continue } // previous matches, but first time seeing it, so already has this spec. // go ahead and add all the previously unseen specs, though if (!priorEntry) { priorEntry = prev for (const s of newSpecs) { priorEntry.addSpec(s) this.entries.set(s, priorEntry) } newSpecs.length = 0 continue } // have a prior entry matching n, and matching the prev we just saw // add the spec to it priorEntry.addSpec(s) this.entries.set(s, priorEntry) } // if we never found a matching prior, then this is a whole new thing if (!priorEntry) { const entry = Object.assign(new YarnLockEntry(newSpecs), n) for (const s of newSpecs) { this.entries.set(s, entry) } } else { // pick up any new info that we got for this node, so that we can // decorate with integrity/resolved/etc. Object.assign(priorEntry, n) } } entryDataFromNode (node) { const n = {} if (node.package.dependencies) { n.dependencies = node.package.dependencies } if (node.package.optionalDependencies) { n.optionalDependencies = node.package.optionalDependencies } if (node.version) { n.version = node.version } if (node.resolved) { n.resolved = consistentResolve( node.resolved, node.isLink ? dirname(node.path) : node.path, node.root.path, true ) } if (node.integrity) { n.integrity = node.integrity } return n } static get Entry () { return YarnLockEntry } } class YarnLockEntry { #specs constructor (specs) { this.#specs = new Set(specs) this.resolved = null this.version = null this.integrity = null this.dependencies = null this.optionalDependencies = null } toString () { // sort objects to the bottom, then alphabetical return ([...this.#specs] .sort(localeCompare) .map(quoteIfNeeded).join(', ') + ':\n' + Object.getOwnPropertyNames(this) .filter(prop => this[prop] !== null) .sort(priorityThenLocaleCompare) .map(prop => typeof this[prop] !== 'object' ? ` ${prop} ${prop === 'integrity' ? this[prop] : JSON.stringify(this[prop])}\n` : Object.keys(this[prop]).length === 0 ? '' : ` ${prop}:\n` + sortKV(this[prop]) + '\n') .join('')).trim() } addSpec (spec) { this.#specs.add(spec) } } module.exports = YarnLock PK ~\ٖ.."@npmcli/arborist/lib/tree-check.jsnu[const debug = require('./debug.js') const checkTree = (tree, checkUnreachable = true) => { const log = [['START TREE CHECK', tree.path]] // this can only happen in tests where we have a "tree" object // that isn't actually a tree. if (!tree.root || !tree.root.inventory) { return tree } const { inventory } = tree.root const seen = new Set() const check = (node, via = tree, viaType = 'self') => { log.push([ 'CHECK', node && node.location, via && via.location, viaType, 'seen=' + seen.has(node), 'promise=' + !!(node && node.then), 'root=' + !!(node && node.isRoot), ]) if (!node || seen.has(node) || node.then) { return } seen.add(node) if (node.isRoot && node !== tree.root) { throw Object.assign(new Error('double root'), { node: node.path, realpath: node.realpath, tree: tree.path, root: tree.root.path, via: via.path, viaType, log, }) } if (node.root !== tree.root) { throw Object.assign(new Error('node from other root in tree'), { node: node.path, realpath: node.realpath, tree: tree.path, root: tree.root.path, via: via.path, viaType, otherRoot: node.root && node.root.path, log, }) } if (!node.isRoot && node.inventory.size !== 0) { throw Object.assign(new Error('non-root has non-zero inventory'), { node: node.path, tree: tree.path, root: tree.root.path, via: via.path, viaType, inventory: [...node.inventory.values()].map(node => [node.path, node.location]), log, }) } if (!node.isRoot && !inventory.has(node) && !node.dummy) { throw Object.assign(new Error('not in inventory'), { node: node.path, tree: tree.path, root: tree.root.path, via: via.path, viaType, log, }) } const devEdges = [...node.edgesOut.values()].filter(e => e.dev) if (!node.isTop && devEdges.length) { throw Object.assign(new Error('dev edges on non-top node'), { node: node.path, tree: tree.path, root: tree.root.path, via: via.path, viaType, devEdges: devEdges.map(e => [e.type, e.name, e.spec, e.error]), log, }) } if (node.path === tree.root.path && node !== tree.root && !tree.root.isLink) { throw Object.assign(new Error('node with same path as root'), { node: node.path, tree: tree.path, root: tree.root.path, via: via.path, viaType, log, }) } if (!node.isLink && node.path !== node.realpath) { throw Object.assign(new Error('non-link with mismatched path/realpath'), { node: node.path, tree: tree.path, realpath: node.realpath, root: tree.root.path, via: via.path, viaType, log, }) } const { parent, fsParent, target } = node check(parent, node, 'parent') check(fsParent, node, 'fsParent') check(target, node, 'target') log.push(['CHILDREN', node.location, ...node.children.keys()]) for (const kid of node.children.values()) { check(kid, node, 'children') } for (const kid of node.fsChildren) { check(kid, node, 'fsChildren') } for (const link of node.linksIn) { check(link, node, 'linksIn') } for (const top of node.tops) { check(top, node, 'tops') } log.push(['DONE', node.location]) } check(tree) if (checkUnreachable) { for (const node of inventory.values()) { if (!seen.has(node) && node !== tree.root) { throw Object.assign(new Error('unreachable in inventory'), { node: node.path, realpath: node.realpath, location: node.location, root: tree.root.path, tree: tree.path, log, }) } } } return tree } // should only ever run this check in debug mode module.exports = tree => tree debug(() => module.exports = checkTree) PK ~\zK}@npmcli/arborist/lib/index.jsnu[module.exports = require('./arborist/index.js') module.exports.Arborist = module.exports module.exports.Node = require('./node.js') module.exports.Link = require('./link.js') module.exports.Edge = require('./edge.js') module.exports.Shrinkwrap = require('./shrinkwrap.js') PK ~\WFF@npmcli/arborist/lib/vuln.jsnu[// An object representing a vulnerability either as the result of an // advisory or due to the package in question depending exclusively on // vulnerable versions of a dep. // // - name: package name // - range: Set of vulnerable versions // - nodes: Set of nodes affected // - effects: Set of vulns triggered by this one // - advisories: Set of advisories (including metavulns) causing this vuln. // All of the entries in via are vulnerability objects returned by // @npmcli/metavuln-calculator // - via: dependency vulns which cause this one const { satisfies, simplifyRange } = require('semver') const semverOpt = { loose: true, includePrerelease: true } const localeCompare = require('@isaacs/string-locale-compare')('en') const npa = require('npm-package-arg') const severities = new Map([ ['info', 0], [0, 'info'], ['low', 1], [1, 'low'], ['moderate', 2], [2, 'moderate'], ['high', 3], [3, 'high'], ['critical', 4], [4, 'critical'], [null, -1], [-1, null], ]) class Vuln { #range = null #simpleRange = null // assume a fix is available unless it hits a top node // that locks it in place, setting this false or {isSemVerMajor, version}. #fixAvailable = true constructor ({ name, advisory }) { this.name = name this.via = new Set() this.advisories = new Set() this.severity = null this.effects = new Set() this.topNodes = new Set() this.nodes = new Set() this.addAdvisory(advisory) this.packument = advisory.packument this.versions = advisory.versions } get fixAvailable () { return this.#fixAvailable } set fixAvailable (f) { this.#fixAvailable = f // if there's a fix available for this at the top level, it means that // it will also fix the vulns that led to it being there. to get there, // we set the vias to the most "strict" of fix availables. // - false: no fix is available // - {name, version, isSemVerMajor} fix requires -f, is semver major // - {name, version} fix requires -f, not semver major // - true: fix does not require -f // TODO: duped entries may require different fixes but the current // structure does not support this, so the case were a top level fix // corrects a duped entry may mean you have to run fix more than once for (const v of this.via) { // don't blow up on loops if (v.fixAvailable === f) { continue } if (f === false) { v.fixAvailable = f } else if (v.fixAvailable === true) { v.fixAvailable = f } else if (typeof f === 'object' && ( typeof v.fixAvailable !== 'object' || !v.fixAvailable.isSemVerMajor)) { v.fixAvailable = f } } } get isDirect () { for (const node of this.nodes.values()) { for (const edge of node.edgesIn) { if (edge.from.isProjectRoot || edge.from.isWorkspace) { return true } } } return false } testSpec (spec) { const specObj = npa(spec) if (!specObj.registry) { return true } if (specObj.subSpec) { spec = specObj.subSpec.rawSpec } for (const v of this.versions) { if (satisfies(v, spec) && !satisfies(v, this.range, semverOpt)) { return false } } return true } toJSON () { return { name: this.name, severity: this.severity, isDirect: this.isDirect, // just loop over the advisories, since via is only Vuln objects, // and calculated advisories have all the info we need via: [...this.advisories].map(v => v.type === 'metavuln' ? v.dependency : { ...v, versions: undefined, vulnerableVersions: undefined, id: undefined, }).sort((a, b) => localeCompare(String(a.source || a), String(b.source || b))), effects: [...this.effects].map(v => v.name).sort(localeCompare), range: this.simpleRange, nodes: [...this.nodes].map(n => n.location).sort(localeCompare), fixAvailable: this.#fixAvailable, } } addVia (v) { this.via.add(v) v.effects.add(this) // call the setter since we might add vias _after_ setting fixAvailable this.fixAvailable = this.fixAvailable } deleteVia (v) { this.via.delete(v) v.effects.delete(this) } deleteAdvisory (advisory) { this.advisories.delete(advisory) // make sure we have the max severity of all the vulns causing this one this.severity = null this.#range = null this.#simpleRange = null // refresh severity for (const advisory of this.advisories) { this.addAdvisory(advisory) } // remove any effects that are no longer relevant const vias = new Set([...this.advisories].map(a => a.dependency)) for (const via of this.via) { if (!vias.has(via.name)) { this.deleteVia(via) } } } addAdvisory (advisory) { this.advisories.add(advisory) const sev = severities.get(advisory.severity) this.#range = null this.#simpleRange = null if (sev > severities.get(this.severity)) { this.severity = advisory.severity } } get range () { if (!this.#range) { this.#range = [...this.advisories].map(v => v.range).join(' || ') } return this.#range } get simpleRange () { if (this.#simpleRange && this.#simpleRange === this.#range) { return this.#simpleRange } const versions = [...this.advisories][0].versions const range = this.range this.#simpleRange = simplifyRange(versions, range, semverOpt) this.#range = this.#simpleRange return this.#simpleRange } isVulnerable (node) { if (this.nodes.has(node)) { return true } const { version } = node.package if (!version) { return false } for (const v of this.advisories) { if (v.testVersion(version)) { this.nodes.add(node) return true } } return false } } module.exports = Vuln PK ~\AA !@npmcli/arborist/lib/inventory.jsnu[// a class to manage an inventory and set of indexes of a set of objects based // on specific fields. const { hasOwnProperty } = Object.prototype const debug = require('./debug.js') const keys = ['name', 'license', 'funding', 'realpath', 'packageName'] class Inventory extends Map { #index constructor () { super() this.#index = new Map() for (const key of keys) { this.#index.set(key, new Map()) } } // XXX where is this used? get primaryKey () { return 'location' } // XXX where is this used? get indexes () { return [...keys] } * filter (fn) { for (const node of this.values()) { if (fn(node)) { yield node } } } add (node) { const root = super.get('') if (root && node.root !== root && node.root !== root.root) { debug(() => { throw Object.assign(new Error('adding external node to inventory'), { root: root.path, node: node.path, nodeRoot: node.root.path, }) }) return } const current = super.get(node.location) if (current) { if (current === node) { return } this.delete(current) } super.set(node.location, node) for (const [key, map] of this.#index.entries()) { let val if (hasOwnProperty.call(node, key)) { // if the node has the value, use it even if it's false val = node[key] } else if (key === 'license' && node.package) { // handling for the outdated "licenses" array, just pick the first one // also support the alternative spelling "licence" if (node.package.license) { val = node.package.license } else if (node.package.licence) { val = node.package.licence } else if (Array.isArray(node.package.licenses)) { val = node.package.licenses[0] } else if (Array.isArray(node.package.licences)) { val = node.package.licences[0] } } else if (node[key]) { val = node[key] } else { val = node.package?.[key] } if (val && typeof val === 'object') { // We currently only use license and funding /* istanbul ignore next - not used */ if (key === 'license') { val = val.type } else if (key === 'funding') { val = val.url } } if (!map.has(val)) { map.set(val, new Set()) } map.get(val).add(node) } } delete (node) { if (!this.has(node)) { return } super.delete(node.location) for (const [key, map] of this.#index.entries()) { let val if (node[key] !== undefined) { val = node[key] } else { val = node.package?.[key] } const set = map.get(val) if (set) { set.delete(node) if (set.size === 0) { map.delete(node[key]) } } } } query (key, val) { const map = this.#index.get(key) if (arguments.length === 2) { if (map.has(val)) { return map.get(val) } return new Set() } return map.keys() } has (node) { return super.get(node.location) === node } set () { throw new Error('direct set() not supported, use inventory.add(node)') } } module.exports = Inventory PK ~\vq#@npmcli/arborist/lib/retire-path.jsnu[const crypto = require('node:crypto') const { dirname, basename, resolve } = require('node:path') // use sha1 because it's faster, and collisions extremely unlikely anyway const pathSafeHash = s => crypto.createHash('sha1') .update(s) .digest('base64') .replace(/[^a-zA-Z0-9]+/g, '') .slice(0, 8) const retirePath = from => { const d = dirname(from) const b = basename(from) const hash = pathSafeHash(from) return resolve(d, `.${b}-${hash}`) } module.exports = retirePath PK ~\g<@npmcli/arborist/lib/edge.jsnu[// An edge in the dependency graph // Represents a dependency relationship of some kind const util = require('node:util') const npa = require('npm-package-arg') const depValid = require('./dep-valid.js') class ArboristEdge { constructor (edge) { this.name = edge.name this.spec = edge.spec this.type = edge.type const edgeFrom = edge.from?.location const edgeTo = edge.to?.location const override = edge.overrides?.value if (edgeFrom != null) { this.from = edgeFrom } if (edgeTo) { this.to = edgeTo } if (edge.error) { this.error = edge.error } if (edge.peerConflicted) { this.peerConflicted = true } if (override) { this.overridden = override } } } class Edge { #accept #error #explanation #from #name #spec #to #type static types = Object.freeze([ 'prod', 'dev', 'optional', 'peer', 'peerOptional', 'workspace', ]) // XXX where is this used? static errors = Object.freeze([ 'DETACHED', 'MISSING', 'PEER LOCAL', 'INVALID', ]) constructor (options) { const { type, name, spec, accept, from, overrides } = options // XXX are all of these error states even possible? if (typeof spec !== 'string') { throw new TypeError('must provide string spec') } if (!Edge.types.includes(type)) { throw new TypeError(`invalid type: ${type}\n(valid types are: ${Edge.types.join(', ')})`) } if (type === 'workspace' && npa(spec).type !== 'directory') { throw new TypeError('workspace edges must be a symlink') } if (typeof name !== 'string') { throw new TypeError('must provide dependency name') } if (!from) { throw new TypeError('must provide "from" node') } if (accept !== undefined) { if (typeof accept !== 'string') { throw new TypeError('accept field must be a string if provided') } this.#accept = accept || '*' } if (overrides !== undefined) { this.overrides = overrides } this.#name = name this.#type = type this.#spec = spec this.#explanation = null this.#from = from from.edgesOut.get(this.#name)?.detach() from.addEdgeOut(this) this.reload(true) this.peerConflicted = false } satisfiedBy (node) { if (node.name !== this.#name) { return false } // NOTE: this condition means we explicitly do not support overriding // bundled or shrinkwrapped dependencies if (node.hasShrinkwrap || node.inShrinkwrap || node.inBundle) { return depValid(node, this.rawSpec, this.#accept, this.#from) } return depValid(node, this.spec, this.#accept, this.#from) } // return the edge data, and an explanation of how that edge came to be here explain (seen = []) { if (!this.#explanation) { const explanation = { type: this.#type, name: this.#name, spec: this.spec, } if (this.rawSpec !== this.spec) { explanation.rawSpec = this.rawSpec explanation.overridden = true } if (this.bundled) { explanation.bundled = this.bundled } if (this.error) { explanation.error = this.error } if (this.#from) { explanation.from = this.#from.explain(null, seen) } this.#explanation = explanation } return this.#explanation } get bundled () { return !!this.#from?.package?.bundleDependencies?.includes(this.#name) } get workspace () { return this.#type === 'workspace' } get prod () { return this.#type === 'prod' } get dev () { return this.#type === 'dev' } get optional () { return this.#type === 'optional' || this.#type === 'peerOptional' } get peer () { return this.#type === 'peer' || this.#type === 'peerOptional' } get type () { return this.#type } get name () { return this.#name } get rawSpec () { return this.#spec } get spec () { if (this.overrides?.value && this.overrides.value !== '*' && this.overrides.name === this.#name) { if (this.overrides.value.startsWith('$')) { const ref = this.overrides.value.slice(1) // we may be a virtual root, if we are we want to resolve reference overrides // from the real root, not the virtual one const pkg = this.#from.sourceReference ? this.#from.sourceReference.root.package : this.#from.root.package if (pkg.devDependencies?.[ref]) { return pkg.devDependencies[ref] } if (pkg.optionalDependencies?.[ref]) { return pkg.optionalDependencies[ref] } if (pkg.dependencies?.[ref]) { return pkg.dependencies[ref] } if (pkg.peerDependencies?.[ref]) { return pkg.peerDependencies[ref] } throw new Error(`Unable to resolve reference ${this.overrides.value}`) } return this.overrides.value } return this.#spec } get accept () { return this.#accept } get valid () { return !this.error } get missing () { return this.error === 'MISSING' } get invalid () { return this.error === 'INVALID' } get peerLocal () { return this.error === 'PEER LOCAL' } get error () { if (!this.#error) { if (!this.#to) { if (this.optional) { this.#error = null } else { this.#error = 'MISSING' } } else if (this.peer && this.#from === this.#to.parent && !this.#from.isTop) { this.#error = 'PEER LOCAL' } else if (!this.satisfiedBy(this.#to)) { this.#error = 'INVALID' } else { this.#error = 'OK' } } if (this.#error === 'OK') { return null } return this.#error } reload (hard = false) { this.#explanation = null if (this.#from.overrides) { this.overrides = this.#from.overrides.getEdgeRule(this) } else { delete this.overrides } const newTo = this.#from.resolve(this.#name) if (newTo !== this.#to) { if (this.#to) { this.#to.edgesIn.delete(this) } this.#to = newTo this.#error = null if (this.#to) { this.#to.addEdgeIn(this) } } else if (hard) { this.#error = null } } detach () { this.#explanation = null if (this.#to) { this.#to.edgesIn.delete(this) } this.#from.edgesOut.delete(this.#name) this.#to = null this.#error = 'DETACHED' this.#from = null } get from () { return this.#from } get to () { return this.#to } toJSON () { return new ArboristEdge(this) } [util.inspect.custom] () { return this.toJSON() } } module.exports = Edge PK ~\z &@npmcli/arborist/lib/calc-dep-flags.jsnu[const { depth } = require('treeverse') const calcDepFlags = (tree, resetRoot = true) => { if (resetRoot) { tree.dev = false tree.optional = false tree.devOptional = false tree.peer = false } const ret = depth({ tree, visit: node => calcDepFlagsStep(node), filter: node => node, getChildren: (node, tree) => [...tree.edgesOut.values()].map(edge => edge.to), }) return ret } const calcDepFlagsStep = (node) => { // This rewalk is necessary to handle cases where devDep and optional // or normal dependency graphs overlap deep in the dep graph. // Since we're only walking through deps that are not already flagged // as non-dev/non-optional, it's typically a very shallow traversal node.extraneous = false resetParents(node, 'extraneous') resetParents(node, 'dev') resetParents(node, 'peer') resetParents(node, 'devOptional') resetParents(node, 'optional') // for links, map their hierarchy appropriately if (node.isLink) { node.target.dev = node.dev node.target.optional = node.optional node.target.devOptional = node.devOptional node.target.peer = node.peer return calcDepFlagsStep(node.target) } node.edgesOut.forEach(({ peer, optional, dev, to }) => { // if the dep is missing, then its flags are already maximally unset if (!to) { return } // everything with any kind of edge into it is not extraneous to.extraneous = false // devOptional is the *overlap* of the dev and optional tree. // however, for convenience and to save an extra rewalk, we leave // it set when we are in *either* tree, and then omit it from the // package-lock if either dev or optional are set. const unsetDevOpt = !node.devOptional && !node.dev && !node.optional && !dev && !optional // if we are not in the devOpt tree, then we're also not in // either the dev or opt trees const unsetDev = unsetDevOpt || !node.dev && !dev const unsetOpt = unsetDevOpt || !node.optional && !optional const unsetPeer = !node.peer && !peer if (unsetPeer) { unsetFlag(to, 'peer') } if (unsetDevOpt) { unsetFlag(to, 'devOptional') } if (unsetDev) { unsetFlag(to, 'dev') } if (unsetOpt) { unsetFlag(to, 'optional') } }) return node } const resetParents = (node, flag) => { if (node[flag]) { return } for (let p = node; p && (p === node || p[flag]); p = p.resolveParent) { p[flag] = false } } // typically a short walk, since it only traverses deps that have the flag set. const unsetFlag = (node, flag) => { if (node[flag]) { node[flag] = false depth({ tree: node, visit: node => { node.extraneous = node[flag] = false if (node.isLink) { node.target.extraneous = node.target[flag] = false } }, getChildren: node => { const children = [] for (const edge of node.target.edgesOut.values()) { if (edge.to && edge.to[flag] && (flag !== 'peer' && edge.type === 'peer' || edge.type === 'prod') ) { children.push(edge.to) } } return children }, }) } } module.exports = calcDepFlags PK ~\#"@npmcli/arborist/lib/shrinkwrap.jsnu[// a module that manages a shrinkwrap file (npm-shrinkwrap.json or // package-lock.json). // Increment whenever the lockfile version updates // v1 - npm <=6 // v2 - arborist v1, npm v7, backwards compatible with v1, add 'packages' // v3 will drop the 'dependencies' field, backwards comp with v2, not v1 // // We cannot bump to v3 until npm v6 is out of common usage, and // definitely not before npm v8. const localeCompare = require('@isaacs/string-locale-compare')('en') const defaultLockfileVersion = 3 // for comparing nodes to yarn.lock entries const mismatch = (a, b) => a && b && a !== b // this.tree => the root node for the tree (ie, same path as this) // - Set the first time we do `this.add(node)` for a path matching this.path // // this.add(node) => // - decorate the node with the metadata we have, if we have it, and it matches // - add to the map of nodes needing to be committed, so that subsequent // changes are captured when we commit that location's metadata. // // this.commit() => // - commit all nodes awaiting update to their metadata entries // - re-generate this.data and this.yarnLock based on this.tree // // Note that between this.add() and this.commit(), `this.data` will be out of // date! Always call `commit()` before relying on it. // // After calling this.commit(), any nodes not present in the tree will have // been removed from the shrinkwrap data as well. const { log } = require('proc-log') const YarnLock = require('./yarn-lock.js') const { readFile, readdir, readlink, rm, stat, writeFile, } = require('node:fs/promises') const { resolve, basename, relative } = require('node:path') const specFromLock = require('./spec-from-lock.js') const versionFromTgz = require('./version-from-tgz.js') const npa = require('npm-package-arg') const pkgJson = require('@npmcli/package-json') const parseJSON = require('parse-conflict-json') const stringify = require('json-stringify-nice') const swKeyOrder = [ 'name', 'version', 'lockfileVersion', 'resolved', 'integrity', 'requires', 'packages', 'dependencies', ] // used to rewrite from yarn registry to npm registry const yarnRegRe = /^https?:\/\/registry\.yarnpkg\.com\// const npmRegRe = /^https?:\/\/registry\.npmjs\.org\// // sometimes resolved: is weird or broken, or something npa can't handle const specFromResolved = resolved => { try { return npa(resolved) } catch (er) { return {} } } const relpath = require('./relpath.js') const consistentResolve = require('./consistent-resolve.js') const { overrideResolves } = require('./override-resolves.js') const pkgMetaKeys = [ // note: name is included if necessary, for alias packages 'version', 'dependencies', 'peerDependencies', 'peerDependenciesMeta', 'optionalDependencies', 'bundleDependencies', 'acceptDependencies', 'funding', 'engines', 'os', 'cpu', '_integrity', 'license', '_hasShrinkwrap', 'hasInstallScript', 'bin', 'deprecated', 'workspaces', ] const nodeMetaKeys = [ 'integrity', 'inBundle', 'hasShrinkwrap', 'hasInstallScript', ] const metaFieldFromPkg = (pkg, key) => { const val = pkg[key] if (val) { // get only the license type, not the full object if (key === 'license' && typeof val === 'object' && val.type) { return val.type } // skip empty objects and falsey values if (typeof val !== 'object' || Object.keys(val).length) { return val } } return null } // check to make sure that there are no packages newer than or missing from the hidden lockfile const assertNoNewer = async (path, data, lockTime, dir, seen) => { const base = basename(dir) const isNM = dir !== path && base === 'node_modules' const isScope = dir !== path && base.startsWith('@') const isParent = (dir === path) || isNM || isScope const parent = isParent ? dir : resolve(dir, 'node_modules') const rel = relpath(path, dir) seen.add(rel) let entries if (dir === path) { entries = [{ name: 'node_modules', isDirectory: () => true }] } else { const { mtime: dirTime } = await stat(dir) if (dirTime > lockTime) { throw new Error(`out of date, updated: ${rel}`) } if (!isScope && !isNM && !data.packages[rel]) { throw new Error(`missing from lockfile: ${rel}`) } entries = await readdir(parent, { withFileTypes: true }).catch(() => []) } // TODO limit concurrency here, this is recursive await Promise.all(entries.map(async dirent => { const child = resolve(parent, dirent.name) if (dirent.isDirectory() && !dirent.name.startsWith('.')) { await assertNoNewer(path, data, lockTime, child, seen) } else if (dirent.isSymbolicLink()) { const target = resolve(parent, await readlink(child)) const tstat = await stat(target).catch( /* istanbul ignore next - windows */ () => null) seen.add(relpath(path, child)) /* istanbul ignore next - windows cannot do this */ if (tstat?.isDirectory() && !seen.has(relpath(path, target))) { await assertNoNewer(path, data, lockTime, target, seen) } } })) if (dir !== path) { return } // assert that all the entries in the lockfile were seen for (const loc in data.packages) { if (!seen.has(loc)) { throw new Error(`missing from node_modules: ${loc}`) } } } class Shrinkwrap { static get defaultLockfileVersion () { return defaultLockfileVersion } static load (options) { return new Shrinkwrap(options).load() } static get keyOrder () { return swKeyOrder } static async reset (options) { // still need to know if it was loaded from the disk, but don't // bother reading it if we're gonna just throw it away. const s = new Shrinkwrap(options) s.reset() const [sw, lock] = await s.resetFiles // XXX this is duplicated in this.load(), but using loadFiles instead of resetFiles if (s.hiddenLockfile) { s.filename = resolve(s.path, 'node_modules/.package-lock.json') } else if (s.shrinkwrapOnly || sw) { s.filename = resolve(s.path, 'npm-shrinkwrap.json') } else { s.filename = resolve(s.path, 'package-lock.json') } s.loadedFromDisk = !!(sw || lock) // TODO what uses this? s.type = basename(s.filename) return s } static metaFromNode (node, path, options = {}) { if (node.isLink) { return { resolved: relpath(path, node.realpath), link: true, } } const meta = {} for (const key of pkgMetaKeys) { const val = metaFieldFromPkg(node.package, key) if (val) { meta[key.replace(/^_/, '')] = val } } // we only include name if different from the node path name, and for the // root to help prevent churn based on the name of the directory the // project is in const pname = node.packageName if (pname && (node === node.root || pname !== node.name)) { meta.name = pname } if (node.isTop && node.package.devDependencies) { meta.devDependencies = node.package.devDependencies } for (const key of nodeMetaKeys) { if (node[key]) { meta[key] = node[key] } } const resolved = consistentResolve(node.resolved, node.path, path, true) // hide resolved from registry dependencies. if (!resolved) { // no-op } else if (node.isRegistryDependency) { meta.resolved = overrideResolves(resolved, options) } else { meta.resolved = resolved } if (node.extraneous) { meta.extraneous = true } else { if (node.peer) { meta.peer = true } if (node.dev) { meta.dev = true } if (node.optional) { meta.optional = true } if (node.devOptional && !node.dev && !node.optional) { meta.devOptional = true } } return meta } #awaitingUpdate = new Map() constructor (options = {}) { const { path, indent = 2, newline = '\n', shrinkwrapOnly = false, hiddenLockfile = false, lockfileVersion, resolveOptions = {}, } = options if (hiddenLockfile) { this.lockfileVersion = 3 } else if (lockfileVersion) { this.lockfileVersion = parseInt(lockfileVersion, 10) } else { this.lockfileVersion = null } this.tree = null this.path = resolve(path || '.') this.filename = null this.data = null this.indent = indent this.newline = newline this.loadedFromDisk = false this.type = null this.yarnLock = null this.hiddenLockfile = hiddenLockfile this.loadingError = null this.resolveOptions = resolveOptions // only load npm-shrinkwrap.json in dep trees, not package-lock this.shrinkwrapOnly = shrinkwrapOnly } // check to see if a spec is present in the yarn.lock file, and if so, // if we should use it, and what it should resolve to. This is only // done when we did not load a shrinkwrap from disk. Also, decorate // the options object if provided with the resolved and integrity that // we expect. checkYarnLock (spec, options = {}) { spec = npa(spec) const { yarnLock, loadedFromDisk } = this const useYarnLock = yarnLock && !loadedFromDisk const fromYarn = useYarnLock && yarnLock.entries.get(spec.raw) if (fromYarn && fromYarn.version) { // if it's the yarn or npm default registry, use the version as // our effective spec. if it's any other kind of thing, use that. const { resolved, version, integrity } = fromYarn const isYarnReg = spec.registry && yarnRegRe.test(resolved) const isnpmReg = spec.registry && !isYarnReg && npmRegRe.test(resolved) const isReg = isnpmReg || isYarnReg // don't use the simple version if the "registry" url is // something else entirely! const tgz = isReg && versionFromTgz(spec.name, resolved) || {} let yspec = resolved if (tgz.name === spec.name && tgz.version === version) { yspec = version } else if (isReg && tgz.name && tgz.version) { yspec = `npm:${tgz.name}@${tgz.version}` } if (yspec) { options.resolved = resolved.replace(yarnRegRe, 'https://registry.npmjs.org/') options.integrity = integrity return npa(`${spec.name}@${yspec}`) } } return spec } // throw away the shrinkwrap data so we can start fresh // still worth doing a load() first so we know which files to write. reset () { this.tree = null this.#awaitingUpdate = new Map() const lockfileVersion = this.lockfileVersion || defaultLockfileVersion this.originalLockfileVersion = lockfileVersion this.data = { lockfileVersion, requires: true, packages: {}, dependencies: {}, } } // files to potentially read from and write to, in order of priority get #filenameSet () { if (this.shrinkwrapOnly) { return [`${this.path}/npm-shrinkwrap.json`] } if (this.hiddenLockfile) { return [`${this.path}/node_modules/.package-lock.json`] } return [ `${this.path}/npm-shrinkwrap.json`, `${this.path}/package-lock.json`, `${this.path}/yarn.lock`, ] } get loadFiles () { return Promise.all( this.#filenameSet.map(file => file && readFile(file, 'utf8').then(d => d, er => { /* istanbul ignore else - can't test without breaking module itself */ if (er.code === 'ENOENT') { return '' } else { throw er } })) ) } get resetFiles () { // slice out yarn, we only care about lock or shrinkwrap when checking // this way, since we're not actually loading the full lock metadata return Promise.all(this.#filenameSet.slice(0, 2) .map(file => file && stat(file).then(st => st.isFile(), er => { /* istanbul ignore else - can't test without breaking module itself */ if (er.code === 'ENOENT') { return null } else { throw er } }) ) ) } inferFormattingOptions (packageJSONData) { const { [Symbol.for('indent')]: indent, [Symbol.for('newline')]: newline, } = packageJSONData if (indent !== undefined) { this.indent = indent } if (newline !== undefined) { this.newline = newline } } async load () { // we don't need to load package-lock.json except for top of tree nodes, // only npm-shrinkwrap.json. let data try { const [sw, lock, yarn] = await this.loadFiles data = sw || lock || '{}' // use shrinkwrap only for deps, otherwise prefer package-lock // and ignore npm-shrinkwrap if both are present. // TODO: emit a warning here or something if both are present. if (this.hiddenLockfile) { this.filename = resolve(this.path, 'node_modules/.package-lock.json') } else if (this.shrinkwrapOnly || sw) { this.filename = resolve(this.path, 'npm-shrinkwrap.json') } else { this.filename = resolve(this.path, 'package-lock.json') } this.type = basename(this.filename) this.loadedFromDisk = Boolean(sw || lock) if (yarn) { this.yarnLock = new YarnLock() // ignore invalid yarn data. we'll likely clobber it later anyway. try { this.yarnLock.parse(yarn) } catch { // ignore errors } } data = parseJSON(data) this.inferFormattingOptions(data) if (this.hiddenLockfile && data.packages) { // add a few ms just to account for jitter const lockTime = +(await stat(this.filename)).mtime + 10 await assertNoNewer(this.path, data, lockTime, this.path, new Set()) } // all good! hidden lockfile is the newest thing in here. } catch (er) { /* istanbul ignore else */ if (typeof this.filename === 'string') { const rel = relpath(this.path, this.filename) log.verbose('shrinkwrap', `failed to load ${rel}`, er.message) } else { log.verbose('shrinkwrap', `failed to load ${this.path}`, er.message) } this.loadingError = er this.loadedFromDisk = false this.ancientLockfile = false data = {} } // auto convert v1 lockfiles to v3 // leave v2 in place unless configured // v3 by default let lockfileVersion = defaultLockfileVersion if (this.lockfileVersion) { lockfileVersion = this.lockfileVersion } else if (data.lockfileVersion && data.lockfileVersion !== 1) { lockfileVersion = data.lockfileVersion } this.data = { ...data, lockfileVersion, requires: true, packages: data.packages || {}, dependencies: data.dependencies || {}, } this.originalLockfileVersion = data.lockfileVersion // use default if it wasn't explicitly set, and the current file is // less than our default. otherwise, keep whatever is in the file, // unless we had an explicit setting already. if (!this.lockfileVersion) { this.lockfileVersion = this.data.lockfileVersion = lockfileVersion } this.ancientLockfile = this.loadedFromDisk && !(data.lockfileVersion >= 2) && !data.requires // load old lockfile deps into the packages listing if (data.dependencies && !data.packages) { let pkg try { pkg = await pkgJson.normalize(this.path) pkg = pkg.content } catch { pkg = {} } this.#loadAll('', null, this.data) this.#fixDependencies(pkg) } return this } #loadAll (location, name, lock) { // migrate a v1 package lock to the new format. const meta = this.#metaFromLock(location, name, lock) // dependencies nested under a link are actually under the link target if (meta.link) { location = meta.resolved } if (lock.dependencies) { for (const name in lock.dependencies) { const loc = location + (location ? '/' : '') + 'node_modules/' + name this.#loadAll(loc, name, lock.dependencies[name]) } } } // v1 lockfiles track the optional/dev flags, but they don't tell us // which thing had what kind of dep on what other thing, so we need // to correct that now, or every link will be considered prod #fixDependencies (pkg) { // we need the root package.json because legacy shrinkwraps just // have requires:true at the root level, which is even less useful // than merging all dep types into one object. const root = this.data.packages[''] for (const key of pkgMetaKeys) { const val = metaFieldFromPkg(pkg, key) if (val) { root[key.replace(/^_/, '')] = val } } for (const loc in this.data.packages) { const meta = this.data.packages[loc] if (!meta.requires || !loc) { continue } // resolve each require to a meta entry // if this node isn't optional, but the dep is, then it's an optionalDep // likewise for dev deps. // This isn't perfect, but it's a pretty good approximation, and at // least gets us out of having all 'prod' edges, which throws off the // buildIdealTree process for (const name in meta.requires) { const dep = this.#resolveMetaNode(loc, name) // this overwrites the false value set above // default to dependencies if the dep just isn't in the tree, which // maybe should be an error, since it means that the shrinkwrap is // invalid, but we can't do much better without any info. let depType = 'dependencies' /* istanbul ignore else - dev deps are only for the root level */ if (dep?.optional && !meta.optional) { depType = 'optionalDependencies' } else if (dep?.dev && !meta.dev) { // XXX is this even reachable? depType = 'devDependencies' } if (!meta[depType]) { meta[depType] = {} } meta[depType][name] = meta.requires[name] } delete meta.requires } } #resolveMetaNode (loc, name) { for (let path = loc; true; path = path.replace(/(^|\/)[^/]*$/, '')) { const check = `${path}${path ? '/' : ''}node_modules/${name}` if (this.data.packages[check]) { return this.data.packages[check] } if (!path) { break } } return null } #lockFromLoc (lock, path, i = 0) { if (!lock) { return null } if (path[i] === '') { i++ } if (i >= path.length) { return lock } if (!lock.dependencies) { return null } return this.#lockFromLoc(lock.dependencies[path[i]], path, i + 1) } // pass in a path relative to the root path, or an absolute path, // get back a /-normalized location based on root path. #pathToLoc (path) { return relpath(this.path, resolve(this.path, path)) } delete (nodePath) { if (!this.data) { throw new Error('run load() before getting or setting data') } const location = this.#pathToLoc(nodePath) this.#awaitingUpdate.delete(location) delete this.data.packages[location] const path = location.split(/(?:^|\/)node_modules\//) const name = path.pop() const pLock = this.#lockFromLoc(this.data, path) if (pLock && pLock.dependencies) { delete pLock.dependencies[name] } } get (nodePath) { if (!this.data) { throw new Error('run load() before getting or setting data') } const location = this.#pathToLoc(nodePath) if (this.#awaitingUpdate.has(location)) { this.#updateWaitingNode(location) } // first try to get from the newer spot, which we know has // all the things we need. if (this.data.packages[location]) { return this.data.packages[location] } // otherwise, fall back to the legacy metadata, and hope for the best // get the node in the shrinkwrap corresponding to this spot const path = location.split(/(?:^|\/)node_modules\//) const name = path[path.length - 1] const lock = this.#lockFromLoc(this.data, path) return this.#metaFromLock(location, name, lock) } #metaFromLock (location, name, lock) { // This function tries as hard as it can to figure out the metadata // from a lockfile which may be outdated or incomplete. Since v1 // lockfiles used the "version" field to contain a variety of // different possible types of data, this gets a little complicated. if (!lock) { return {} } // try to figure out a npm-package-arg spec from the lockfile entry // This will return null if we could not get anything valid out of it. const spec = specFromLock(name, lock, this.path) if (spec.type === 'directory') { // the "version" was a file: url to a non-tarball path // this is a symlink dep. We don't store much metadata // about symlinks, just the target. const target = relpath(this.path, spec.fetchSpec) this.data.packages[location] = { link: true, resolved: target, } // also save the link target, omitting version since we don't know // what it is, but we know it isn't a link to itself! if (!this.data.packages[target]) { this.#metaFromLock(target, name, { ...lock, version: null }) } return this.data.packages[location] } const meta = {} // when calling loadAll we'll change these into proper dep objects if (lock.requires && typeof lock.requires === 'object') { meta.requires = lock.requires } if (lock.optional) { meta.optional = true } if (lock.dev) { meta.dev = true } // the root will typically have a name from the root project's // package.json file. if (location === '') { meta.name = lock.name } // if we have integrity, save it now. if (lock.integrity) { meta.integrity = lock.integrity } if (lock.version && !lock.integrity) { // this is usually going to be a git url or symlink, but it could // also be a registry dependency that did not have integrity at // the time it was saved. // Symlinks were already handled above, so that leaves git. // // For git, always save the full SSH url. we'll actually fetch the // tgz most of the time, since it's faster, but it won't work for // private repos, and we can't get back to the ssh from the tgz, // so we store the ssh instead. // For unknown git hosts, just resolve to the raw spec in lock.version if (spec.type === 'git') { meta.resolved = consistentResolve(spec, this.path, this.path) // return early because there is nothing else we can do with this return this.data.packages[location] = meta } else if (spec.registry) { // registry dep that didn't save integrity. grab the version, and // fall through to pick up the resolved and potentially name. meta.version = lock.version } // only other possible case is a tarball without integrity. // fall through to do what we can with the filename later. } // at this point, we know that the spec is either a registry dep // (ie, version, because locking, which means a resolved url), // or a remote dep, or file: url. Remote deps and file urls // have a fetchSpec equal to the fully resolved thing. // Registry deps, we take what's in the lockfile. if (lock.resolved || (spec.type && !spec.registry)) { if (spec.registry) { meta.resolved = lock.resolved } else if (spec.type === 'file') { meta.resolved = consistentResolve(spec, this.path, this.path, true) } else if (spec.fetchSpec) { meta.resolved = spec.fetchSpec } } // at this point, if still we don't have a version, do our best to // infer it from the tarball url/file. This works a surprising // amount of the time, even though it's not guaranteed. if (!meta.version) { if (spec.type === 'file' || spec.type === 'remote') { const fromTgz = versionFromTgz(spec.name, spec.fetchSpec) || versionFromTgz(spec.name, meta.resolved) if (fromTgz) { meta.version = fromTgz.version if (fromTgz.name !== name) { meta.name = fromTgz.name } } } else if (spec.type === 'alias') { meta.name = spec.subSpec.name meta.version = spec.subSpec.fetchSpec } else if (spec.type === 'version') { meta.version = spec.fetchSpec } // ok, I did my best! good luck! } if (lock.bundled) { meta.inBundle = true } // save it for next time return this.data.packages[location] = meta } add (node) { if (!this.data) { throw new Error('run load() before getting or setting data') } // will be actually updated on read const loc = relpath(this.path, node.path) if (node.path === this.path) { this.tree = node } // if we have metadata about this node, and it's a match, then // try to decorate it. if (node.resolved === null || node.integrity === null) { const { resolved, integrity, hasShrinkwrap, version, } = this.get(node.path) let pathFixed = null if (resolved) { if (!/^file:/.test(resolved)) { pathFixed = resolved } else { pathFixed = `file:${resolve(this.path, resolved.slice(5)).replace(/#/g, '%23')}` } } // if we have one, only set the other if it matches // otherwise it could be for a completely different thing. const resolvedOk = !resolved || !node.resolved || node.resolved === pathFixed const integrityOk = !integrity || !node.integrity || node.integrity === integrity const versionOk = !version || !node.version || version === node.version const allOk = (resolved || integrity || version) && resolvedOk && integrityOk && versionOk if (allOk) { node.resolved = node.resolved || pathFixed || null node.integrity = node.integrity || integrity || null node.hasShrinkwrap = node.hasShrinkwrap || hasShrinkwrap || false } else { // try to read off the package or node itself const { resolved, integrity, hasShrinkwrap, } = Shrinkwrap.metaFromNode(node, this.path, this.resolveOptions) node.resolved = node.resolved || resolved || null node.integrity = node.integrity || integrity || null node.hasShrinkwrap = node.hasShrinkwrap || hasShrinkwrap || false } } this.#awaitingUpdate.set(loc, node) } addEdge (edge) { if (!this.yarnLock || !edge.valid) { return } const { to: node } = edge // if it's already set up, nothing to do if (node.resolved !== null && node.integrity !== null) { return } // if the yarn lock is empty, nothing to do if (!this.yarnLock.entries || !this.yarnLock.entries.size) { return } // we relativize the path here because that's how it shows up in the lock // XXX why is this different from pathFixed in this.add?? let pathFixed = null if (node.resolved) { if (!/file:/.test(node.resolved)) { pathFixed = node.resolved } else { pathFixed = consistentResolve(node.resolved, node.path, this.path, true) } } const spec = npa(`${node.name}@${edge.spec}`) const entry = this.yarnLock.entries.get(`${node.name}@${edge.spec}`) if (!entry || mismatch(node.version, entry.version) || mismatch(node.integrity, entry.integrity) || mismatch(pathFixed, entry.resolved)) { return } if (entry.resolved && yarnRegRe.test(entry.resolved) && spec.registry) { entry.resolved = entry.resolved.replace(yarnRegRe, 'https://registry.npmjs.org/') } node.integrity = node.integrity || entry.integrity || null node.resolved = node.resolved || consistentResolve(entry.resolved, this.path, node.path) || null this.#awaitingUpdate.set(relpath(this.path, node.path), node) } #updateWaitingNode (loc) { const node = this.#awaitingUpdate.get(loc) this.#awaitingUpdate.delete(loc) this.data.packages[loc] = Shrinkwrap.metaFromNode( node, this.path, this.resolveOptions) } commit () { if (this.tree) { if (this.yarnLock) { this.yarnLock.fromTree(this.tree) } const root = Shrinkwrap.metaFromNode( this.tree.target, this.path, this.resolveOptions) this.data.packages = {} if (Object.keys(root).length) { this.data.packages[''] = root } for (const node of this.tree.root.inventory.values()) { // only way this.tree is not root is if the root is a link to it if (node === this.tree || node.isRoot || node.location === '') { continue } const loc = relpath(this.path, node.path) this.data.packages[loc] = Shrinkwrap.metaFromNode( node, this.path, this.resolveOptions) } } else if (this.#awaitingUpdate.size > 0) { for (const loc of this.#awaitingUpdate.keys()) { this.#updateWaitingNode(loc) } } // if we haven't set it by now, use the default if (!this.lockfileVersion) { this.lockfileVersion = defaultLockfileVersion } this.data.lockfileVersion = this.lockfileVersion // hidden lockfiles don't include legacy metadata or a root entry if (this.hiddenLockfile) { delete this.data.packages[''] delete this.data.dependencies } else if (this.tree && this.lockfileVersion <= 3) { this.#buildLegacyLockfile(this.tree, this.data) } // lf version 1 = dependencies only // lf version 2 = dependencies and packages // lf version 3 = packages only if (this.lockfileVersion >= 3) { const { dependencies, ...data } = this.data return data } else if (this.lockfileVersion < 2) { const { packages, ...data } = this.data return data } else { return { ...this.data } } } #buildLegacyLockfile (node, lock, path = []) { if (node === this.tree) { // the root node lock.name = node.packageName || node.name if (node.version) { lock.version = node.version } } // npm v6 and before tracked 'from', meaning "the request that led // to this package being installed". However, that's inherently // racey and non-deterministic in a world where deps are deduped // ahead of fetch time. In order to maintain backwards compatibility // with v6 in the lockfile, we do this trick where we pick a valid // dep link out of the edgesIn set. Choose the edge with the fewest // number of `node_modules` sections in the requestor path, and then // lexically sort afterwards. const edge = [...node.edgesIn].filter(e => e.valid).sort((a, b) => { const aloc = a.from.location.split('node_modules') const bloc = b.from.location.split('node_modules') /* istanbul ignore next - sort calling order is indeterminate */ if (aloc.length > bloc.length) { return 1 } if (bloc.length > aloc.length) { return -1 } return localeCompare(aloc[aloc.length - 1], bloc[bloc.length - 1]) })[0] const res = consistentResolve(node.resolved, this.path, this.path, true) const rSpec = specFromResolved(res) // if we don't have anything (ie, it's extraneous) then use the resolved // value as if that was where we got it from, since at least it's true. // if we don't have either, just an empty object so nothing matches below. // This will effectively just save the version and resolved, as if it's // a standard version/range dep, which is a reasonable default. let spec = rSpec if (edge) { spec = npa.resolve(node.name, edge.spec, edge.from.realpath) } if (node.isLink) { lock.version = `file:${relpath(this.path, node.realpath).replace(/#/g, '%23')}` } else if (spec && (spec.type === 'file' || spec.type === 'remote')) { lock.version = spec.saveSpec } else if (spec && spec.type === 'git' || rSpec.type === 'git') { lock.version = node.resolved /* istanbul ignore else - don't think there are any cases where a git * spec (or indeed, ANY npa spec) doesn't have a .raw member */ if (spec.raw) { lock.from = spec.raw } } else if (!node.isRoot && node.package && node.packageName && node.packageName !== node.name) { lock.version = `npm:${node.packageName}@${node.version}` } else if (node.package && node.version) { lock.version = node.version } if (node.inDepBundle) { lock.bundled = true } // when we didn't resolve to git, file, or dir, and didn't request // git, file, dir, or remote, then the resolved value is necessary. if (node.resolved && !node.isLink && rSpec.type !== 'git' && rSpec.type !== 'file' && rSpec.type !== 'directory' && spec.type !== 'directory' && spec.type !== 'git' && spec.type !== 'file' && spec.type !== 'remote') { lock.resolved = overrideResolves(node.resolved, this.resolveOptions) } if (node.integrity) { lock.integrity = node.integrity } if (node.extraneous) { lock.extraneous = true } else if (!node.isLink) { if (node.peer) { lock.peer = true } if (node.devOptional && !node.dev && !node.optional) { lock.devOptional = true } if (node.dev) { lock.dev = true } if (node.optional) { lock.optional = true } } const depender = node.target if (depender.edgesOut.size > 0) { if (node !== this.tree) { const entries = [...depender.edgesOut.entries()] lock.requires = entries.reduce((set, [k, v]) => { // omit peer deps from legacy lockfile requires field, because // npm v6 doesn't handle peer deps, and this triggers some bad // behavior if the dep can't be found in the dependencies list. const { spec, peer } = v if (peer) { return set } if (spec.startsWith('file:')) { // turn absolute file: paths into relative paths from the node // this especially shows up with workspace edges when the root // node is also a workspace in the set. const p = resolve(node.realpath, spec.slice('file:'.length)) set[k] = `file:${relpath(node.realpath, p).replace(/#/g, '%23')}` } else { set[k] = spec } return set }, {}) } else { lock.requires = true } } // now we walk the children, putting them in the 'dependencies' object const { children } = node.target if (!children.size) { delete lock.dependencies } else { const kidPath = [...path, node.realpath] const dependencies = {} // skip any that are already in the descent path, so cyclical link // dependencies don't blow up with ELOOP. let found = false for (const [name, kid] of children.entries()) { if (path.includes(kid.realpath)) { continue } dependencies[name] = this.#buildLegacyLockfile(kid, {}, kidPath) found = true } if (found) { lock.dependencies = dependencies } } return lock } toJSON () { if (!this.data) { throw new Error('run load() before getting or setting data') } return this.commit() } toString (options = {}) { const data = this.toJSON() const { format = true } = options const defaultIndent = this.indent || 2 const indent = format === true ? defaultIndent : format || 0 const eol = format ? this.newline || '\n' : '' return stringify(data, swKeyOrder, indent).replace(/\n/g, eol) } save (options = {}) { if (!this.data) { throw new Error('run load() before saving data') } // This must be called before the lockfile conversion check below since it sets properties as part of `commit()` const json = this.toString(options) if ( !this.hiddenLockfile && this.originalLockfileVersion !== undefined && this.originalLockfileVersion !== this.lockfileVersion ) { log.warn( 'shrinkwrap', `Converting lock file (${relative(process.cwd(), this.filename)}) from v${this.originalLockfileVersion} -> v${this.lockfileVersion}` ) } return Promise.all([ writeFile(this.filename, json).catch(er => { if (this.hiddenLockfile) { // well, we did our best. // if we reify, and there's nothing there, then it might be lacking // a node_modules folder, but then the lockfile is not important. // Remove the file, so that in case there WERE deps, but we just // failed to update the file for some reason, it's not out of sync. return rm(this.filename, { recursive: true, force: true }) } throw er }), this.yarnLock && this.yarnLock.entries.size && writeFile(this.path + '/yarn.lock', this.yarnLock.toString()), ]) } } module.exports = Shrinkwrap PK ~\(~~'@npmcli/arborist/lib/reset-dep-flags.jsnu[// Sometimes we need to actually do a walk from the root, because you can // have a cycle of deps that all depend on each other, but no path from root. // Also, since the ideal tree is loaded from the shrinkwrap, it had extraneous // flags set false that might now be actually extraneous, and dev/optional // flags that are also now incorrect. This method sets all flags to true, so // we can find the set that is actually extraneous. module.exports = tree => { for (const node of tree.inventory.values()) { node.extraneous = true node.dev = true node.devOptional = true node.peer = true node.optional = true } } PK ~\5@npmcli/arborist/lib/debug.jsnu[// certain assertions we should do only when testing arborist itself, because // they are too expensive or aggressive and would break user programs if we // miss a situation where they are actually valid. // // call like this: // // /* istanbul ignore next - debug check */ // debug(() => { // if (someExpensiveCheck) // throw new Error('expensive check should have returned false') // }) // run in debug mode if explicitly requested, running arborist tests, // or working in the arborist project directory. const debug = process.env.ARBORIST_DEBUG !== '0' && ( process.env.ARBORIST_DEBUG === '1' || /\barborist\b/.test(process.env.NODE_DEBUG || '') || process.env.npm_package_name === '@npmcli/arborist' && ['test', 'snap'].includes(process.env.npm_lifecycle_event) || process.cwd() === require('node:path').resolve(__dirname, '..') ) module.exports = debug ? fn => fn() : () => {} const red = process.stderr.isTTY ? msg => `\x1B[31m${msg}\x1B[39m` : m => m module.exports.log = (...msg) => module.exports(() => { const { format } = require('node:util') const prefix = `\n${process.pid} ${red(format(msg.shift()))} ` msg = (prefix + format(...msg).trim().split('\n').join(prefix)).trim() /* eslint-disable-next-line no-console */ console.error(msg) }) PK ~\dtrv v $@npmcli/arborist/lib/override-set.jsnu[const npa = require('npm-package-arg') const semver = require('semver') class OverrideSet { constructor ({ overrides, key, parent }) { this.parent = parent this.children = new Map() if (typeof overrides === 'string') { overrides = { '.': overrides } } // change a literal empty string to * so we can use truthiness checks on // the value property later if (overrides['.'] === '') { overrides['.'] = '*' } if (parent) { const spec = npa(key) if (!spec.name) { throw new Error(`Override without name: ${key}`) } this.name = spec.name spec.name = '' this.key = key this.keySpec = spec.toString() this.value = overrides['.'] || this.keySpec } for (const [key, childOverrides] of Object.entries(overrides)) { if (key === '.') { continue } const child = new OverrideSet({ parent: this, key, overrides: childOverrides, }) this.children.set(child.key, child) } } getEdgeRule (edge) { for (const rule of this.ruleset.values()) { if (rule.name !== edge.name) { continue } // if keySpec is * we found our override if (rule.keySpec === '*') { return rule } let spec = npa(`${edge.name}@${edge.spec}`) if (spec.type === 'alias') { spec = spec.subSpec } if (spec.type === 'git') { if (spec.gitRange && semver.intersects(spec.gitRange, rule.keySpec)) { return rule } continue } if (spec.type === 'range' || spec.type === 'version') { if (semver.intersects(spec.fetchSpec, rule.keySpec)) { return rule } continue } // if we got this far, the spec type is one of tag, directory or file // which means we have no real way to make version comparisons, so we // just accept the override return rule } return this } getNodeRule (node) { for (const rule of this.ruleset.values()) { if (rule.name !== node.name) { continue } if (semver.satisfies(node.version, rule.keySpec) || semver.satisfies(node.version, rule.value)) { return rule } } return this } getMatchingRule (node) { for (const rule of this.ruleset.values()) { if (rule.name !== node.name) { continue } if (semver.satisfies(node.version, rule.keySpec) || semver.satisfies(node.version, rule.value)) { return rule } } return null } * ancestry () { for (let ancestor = this; ancestor; ancestor = ancestor.parent) { yield ancestor } } get isRoot () { return !this.parent } get ruleset () { const ruleset = new Map() for (const override of this.ancestry()) { for (const kid of override.children.values()) { if (!ruleset.has(kid.key)) { ruleset.set(kid.key, kid) } } if (!override.isRoot && !ruleset.has(override.key)) { ruleset.set(override.key, override) } } return ruleset } } module.exports = OverrideSet PK ~\ ]s]s*@npmcli/arborist/lib/query-selector-all.jsnu['use strict' const { resolve } = require('node:path') const { parser, arrayDelimiter } = require('@npmcli/query') const localeCompare = require('@isaacs/string-locale-compare')('en') const { log } = require('proc-log') const { minimatch } = require('minimatch') const npa = require('npm-package-arg') const pacote = require('pacote') const semver = require('semver') const fetch = require('npm-registry-fetch') // handle results for parsed query asts, results are stored in a map that has a // key that points to each ast selector node and stores the resulting array of // arborist nodes as its value, that is essential to how we handle multiple // query selectors, e.g: `#a, #b, #c` <- 3 diff ast selector nodes class Results { #currentAstSelector #initialItems #inventory #outdatedCache = new Map() #vulnCache #pendingCombinator #results = new Map() #targetNode constructor (opts) { this.#currentAstSelector = opts.rootAstNode.nodes[0] this.#inventory = opts.inventory this.#initialItems = opts.initialItems this.#vulnCache = opts.vulnCache this.#targetNode = opts.targetNode this.currentResults = this.#initialItems // We get this when first called and need to pass it to pacote this.flatOptions = opts.flatOptions || {} // reset by rootAstNode walker this.currentAstNode = opts.rootAstNode } get currentResults () { return this.#results.get(this.#currentAstSelector) } set currentResults (value) { this.#results.set(this.#currentAstSelector, value) } // retrieves the initial items to which start the filtering / matching // for most of the different types of recognized ast nodes, e.g: class (aka // depType), id, *, etc in different contexts we need to start with the // current list of filtered results, for example a query for `.workspace` // actually means the same as `*.workspace` so we want to start with the full // inventory if that's the first ast node we're reading but if it appears in // the middle of a query it should respect the previous filtered results, // combinators are a special case in which we always want to have the // complete inventory list in order to use the left-hand side ast node as a // filter combined with the element on its right-hand side get initialItems () { const firstParsed = (this.currentAstNode.parent.nodes[0] === this.currentAstNode) && (this.currentAstNode.parent.parent.type === 'root') if (firstParsed) { return this.#initialItems } if (this.currentAstNode.prev().type === 'combinator') { return this.#inventory } return this.currentResults } // combinators need information about previously filtered items along // with info of the items parsed / retrieved from the selector right // past the combinator, for this reason combinators are stored and // only ran as the last part of each selector logic processPendingCombinator (nextResults) { if (this.#pendingCombinator) { const res = this.#pendingCombinator(this.currentResults, nextResults) this.#pendingCombinator = null this.currentResults = res } else { this.currentResults = nextResults } } // when collecting results to a root astNode, we traverse the list of child // selector nodes and collect all of their resulting arborist nodes into a // single/flat Set of items, this ensures we also deduplicate items collect (rootAstNode) { return new Set(rootAstNode.nodes.flatMap(n => this.#results.get(n))) } // selector types map to the '.type' property of the ast nodes via `${astNode.type}Type` // // attribute selector [name=value], etc attributeType () { const nextResults = this.initialItems.filter(node => attributeMatch(this.currentAstNode, node.package) ) this.processPendingCombinator(nextResults) } // dependency type selector (i.e. .prod, .dev, etc) // css calls this class, we interpret is as dependency type classType () { const depTypeFn = depTypes[String(this.currentAstNode)] if (!depTypeFn) { throw Object.assign( new Error(`\`${String(this.currentAstNode)}\` is not a supported dependency type.`), { code: 'EQUERYNODEPTYPE' } ) } const nextResults = depTypeFn(this.initialItems) this.processPendingCombinator(nextResults) } // combinators (i.e. '>', ' ', '~') combinatorType () { this.#pendingCombinator = combinators[String(this.currentAstNode)] } // name selectors (i.e. #foo) // css calls this id, we interpret it as name idType () { const name = this.currentAstNode.value const nextResults = this.initialItems.filter(node => (name === node.name) || (name === node.package.name) ) this.processPendingCombinator(nextResults) } // pseudo selectors (prefixed with :) async pseudoType () { const pseudoFn = `${this.currentAstNode.value.slice(1)}Pseudo` if (!this[pseudoFn]) { throw Object.assign( new Error(`\`${this.currentAstNode.value }\` is not a supported pseudo selector.`), { code: 'EQUERYNOPSEUDO' } ) } const nextResults = await this[pseudoFn]() this.processPendingCombinator(nextResults) } selectorType () { this.#currentAstSelector = this.currentAstNode // starts a new array in which resulting items // can be stored for each given ast selector if (!this.currentResults) { this.currentResults = [] } } universalType () { this.processPendingCombinator(this.initialItems) } // pseudo selectors map to the 'value' property of the pseudo selectors in the ast nodes // via selectors via `${value.slice(1)}Pseudo` attrPseudo () { const { lookupProperties, attributeMatcher } = this.currentAstNode return this.initialItems.filter(node => { let objs = [node.package] for (const prop of lookupProperties) { // if an isArray symbol is found that means we'll need to iterate // over the previous found array to basically make sure we traverse // all its indexes testing for possible objects that may eventually // hold more keys specified in a selector if (prop === arrayDelimiter) { objs = objs.flat() continue } // otherwise just maps all currently found objs // to the next prop from the lookup properties list, // filters out any empty key lookup objs = objs.flatMap(obj => obj[prop] || []) // in case there's no property found in the lookup // just filters that item out const noAttr = objs.every(obj => !obj) if (noAttr) { return false } } // if any of the potential object matches // that item should be in the final result return objs.some(obj => attributeMatch(attributeMatcher, obj)) }) } emptyPseudo () { return this.initialItems.filter(node => node.edgesOut.size === 0) } extraneousPseudo () { return this.initialItems.filter(node => node.extraneous) } async hasPseudo () { const found = [] for (const item of this.initialItems) { // This is the one time initialItems differs from inventory const res = await retrieveNodesFromParsedAst({ flatOptions: this.flatOptions, initialItems: [item], inventory: this.#inventory, rootAstNode: this.currentAstNode.nestedNode, targetNode: item, vulnCache: this.#vulnCache, }) if (res.size > 0) { found.push(item) } } return found } invalidPseudo () { const found = [] for (const node of this.initialItems) { for (const edge of node.edgesIn) { if (edge.invalid) { found.push(node) break } } } return found } async isPseudo () { const res = await retrieveNodesFromParsedAst({ flatOptions: this.flatOptions, initialItems: this.initialItems, inventory: this.#inventory, rootAstNode: this.currentAstNode.nestedNode, targetNode: this.currentAstNode, vulnCache: this.#vulnCache, }) return [...res] } linkPseudo () { return this.initialItems.filter(node => node.isLink || (node.isTop && !node.isRoot)) } missingPseudo () { return this.#inventory.reduce((res, node) => { for (const edge of node.edgesOut.values()) { if (edge.missing) { const pkg = { name: edge.name, version: edge.spec } const item = new this.#targetNode.constructor({ pkg }) item.queryContext = { missing: true, } item.edgesIn = new Set([edge]) res.push(item) } } return res }, []) } async notPseudo () { const res = await retrieveNodesFromParsedAst({ flatOptions: this.flatOptions, initialItems: this.initialItems, inventory: this.#inventory, rootAstNode: this.currentAstNode.nestedNode, targetNode: this.currentAstNode, vulnCache: this.#vulnCache, }) const internalSelector = new Set(res) return this.initialItems.filter(node => !internalSelector.has(node)) } overriddenPseudo () { return this.initialItems.filter(node => node.overridden) } pathPseudo () { return this.initialItems.filter(node => { if (!this.currentAstNode.pathValue) { return true } return minimatch( node.realpath.replace(/\\+/g, '/'), resolve(node.root.realpath, this.currentAstNode.pathValue).replace(/\\+/g, '/') ) }) } privatePseudo () { return this.initialItems.filter(node => node.package.private) } rootPseudo () { return this.initialItems.filter(node => node === this.#targetNode.root) } scopePseudo () { return this.initialItems.filter(node => node === this.#targetNode) } semverPseudo () { const { attributeMatcher, lookupProperties, semverFunc = 'infer', semverValue, } = this.currentAstNode const { qualifiedAttribute } = attributeMatcher if (!semverValue) { // DEPRECATED: remove this warning and throw an error as part of @npmcli/arborist@6 log.warn('query', 'usage of :semver() with no parameters is deprecated') return this.initialItems } if (!semver.valid(semverValue) && !semver.validRange(semverValue)) { throw Object.assign( new Error(`\`${semverValue}\` is not a valid semver version or range`), { code: 'EQUERYINVALIDSEMVER' }) } const valueIsVersion = !!semver.valid(semverValue) const nodeMatches = (node, obj) => { // if we already have an operator, the user provided some test as part of the selector // we evaluate that first because if it fails we don't want this node anyway if (attributeMatcher.operator) { if (!attributeMatch(attributeMatcher, obj)) { // if the initial operator doesn't match, we're done return false } } const attrValue = obj[qualifiedAttribute] // both valid and validRange return null for undefined, so this will skip both nodes that // do not have the attribute defined as well as those where the attribute value is invalid // and those where the value from the package.json is not a string if ((!semver.valid(attrValue) && !semver.validRange(attrValue)) || typeof attrValue !== 'string') { return false } const attrIsVersion = !!semver.valid(attrValue) let actualFunc = semverFunc // if we're asked to infer, we examine outputs to make a best guess if (actualFunc === 'infer') { if (valueIsVersion && attrIsVersion) { // two versions -> semver.eq actualFunc = 'eq' } else if (!valueIsVersion && !attrIsVersion) { // two ranges -> semver.intersects actualFunc = 'intersects' } else { // anything else -> semver.satisfies actualFunc = 'satisfies' } } if (['eq', 'neq', 'gt', 'gte', 'lt', 'lte'].includes(actualFunc)) { // both sides must be versions, but one is not if (!valueIsVersion || !attrIsVersion) { return false } return semver[actualFunc](attrValue, semverValue) } else if (['gtr', 'ltr', 'satisfies'].includes(actualFunc)) { // at least one side must be a version, but neither is if (!valueIsVersion && !attrIsVersion) { return false } return valueIsVersion ? semver[actualFunc](semverValue, attrValue) : semver[actualFunc](attrValue, semverValue) } else if (['intersects', 'subset'].includes(actualFunc)) { // these accept two ranges and since a version is also a range, anything goes return semver[actualFunc](attrValue, semverValue) } else { // user provided a function we don't know about, throw an error throw Object.assign(new Error(`\`semver.${actualFunc}\` is not a supported operator.`), { code: 'EQUERYINVALIDOPERATOR' }) } } return this.initialItems.filter((node) => { // no lookupProperties just means its a top level property, see if it matches if (!lookupProperties.length) { return nodeMatches(node, node.package) } // this code is mostly duplicated from attrPseudo to traverse into the package until we get // to our deepest requested object let objs = [node.package] for (const prop of lookupProperties) { if (prop === arrayDelimiter) { objs = objs.flat() continue } objs = objs.flatMap(obj => obj[prop] || []) const noAttr = objs.every(obj => !obj) if (noAttr) { return false } return objs.some(obj => nodeMatches(node, obj)) } }) } typePseudo () { if (!this.currentAstNode.typeValue) { return this.initialItems } return this.initialItems .flatMap(node => { const found = [] for (const edge of node.edgesIn) { if (npa(`${edge.name}@${edge.spec}`).type === this.currentAstNode.typeValue) { found.push(edge.to) } } return found }) } dedupedPseudo () { return this.initialItems.filter(node => node.target.edgesIn.size > 1) } async vulnPseudo () { if (!this.initialItems.length) { return this.initialItems } if (!this.#vulnCache) { const packages = {} // We have to map the items twice, once to get the request, and a second time to filter out the results of that request this.initialItems.map((node) => { if (node.isProjectRoot || node.package.private) { return } if (!packages[node.name]) { packages[node.name] = [] } if (!packages[node.name].includes(node.version)) { packages[node.name].push(node.version) } }) const res = await fetch('/-/npm/v1/security/advisories/bulk', { ...this.flatOptions, registry: this.flatOptions.auditRegistry || this.flatOptions.registry, method: 'POST', gzip: true, body: packages, }) this.#vulnCache = await res.json() } const advisories = this.#vulnCache const { vulns } = this.currentAstNode return this.initialItems.filter(item => { const vulnerable = advisories[item.name]?.filter(advisory => { // This could be for another version of this package elsewhere in the tree if (!semver.intersects(advisory.vulnerable_versions, item.version)) { return false } if (!vulns) { return true } // vulns are OR with each other, if any one matches we're done for (const vuln of vulns) { if (vuln.severity && !vuln.severity.includes('*')) { if (!vuln.severity.includes(advisory.severity)) { continue } } if (vuln?.cwe) { // * is special, it means "has a cwe" if (vuln.cwe.includes('*')) { if (!advisory.cwe.length) { continue } } else if (!vuln.cwe.every(cwe => advisory.cwe.includes(`CWE-${cwe}`))) { continue } } return true } }) if (vulnerable?.length) { item.queryContext = { advisories: vulnerable, } return true } return false }) } async outdatedPseudo () { const { outdatedKind = 'any' } = this.currentAstNode // filter the initialItems // NOTE: this uses a Promise.all around a map without in-line concurrency handling // since the only async action taken is retrieving the packument, which is limited // based on the max-sockets config in make-fetch-happen const initialResults = await Promise.all(this.initialItems.map(async (node) => { // the root can't be outdated, skip it if (node.isProjectRoot) { return false } // private packages can't be published, skip them if (node.package.private) { return false } // we cache the promise representing the full versions list, this helps reduce the // number of requests we send by keeping population of the cache in a single tick // making it less likely that multiple requests for the same package will be inflight if (!this.#outdatedCache.has(node.name)) { this.#outdatedCache.set(node.name, getPackageVersions(node.name, this.flatOptions)) } const availableVersions = await this.#outdatedCache.get(node.name) // we attach _all_ versions to the queryContext to allow consumers to do their own // filtering and comparisons node.queryContext.versions = availableVersions // next we further reduce the set to versions that are greater than the current one const greaterVersions = availableVersions.filter((available) => { return semver.gt(available, node.version) }) // no newer versions than the current one, drop this node from the result set if (!greaterVersions.length) { return false } // if we got here, we know that newer versions exist, if the kind is 'any' we're done if (outdatedKind === 'any') { return node } // look for newer versions that differ from current by a specific part of the semver version if (['major', 'minor', 'patch'].includes(outdatedKind)) { // filter the versions greater than our current one based on semver.diff const filteredVersions = greaterVersions.filter((version) => { return semver.diff(node.version, version) === outdatedKind }) // no available versions are of the correct diff type if (!filteredVersions.length) { return false } return node } // look for newer versions that satisfy at least one edgeIn to this node if (outdatedKind === 'in-range') { const inRangeContext = [] for (const edge of node.edgesIn) { const inRangeVersions = greaterVersions.filter((version) => { return semver.satisfies(version, edge.spec) }) // this edge has no in-range candidates, just move on if (!inRangeVersions.length) { continue } inRangeContext.push({ from: edge.from.location, versions: inRangeVersions, }) } // if we didn't find at least one match, drop this node if (!inRangeContext.length) { return false } // now add to the context each version that is in-range for each edgeIn node.queryContext.outdated = { ...node.queryContext.outdated, inRange: inRangeContext, } return node } // look for newer versions that _do not_ satisfy at least one edgeIn if (outdatedKind === 'out-of-range') { const outOfRangeContext = [] for (const edge of node.edgesIn) { const outOfRangeVersions = greaterVersions.filter((version) => { return !semver.satisfies(version, edge.spec) }) // this edge has no out-of-range candidates, skip it if (!outOfRangeVersions.length) { continue } outOfRangeContext.push({ from: edge.from.location, versions: outOfRangeVersions, }) } // if we didn't add at least one thing to the context, this node is not a match if (!outOfRangeContext.length) { return false } // attach the out-of-range context to the node node.queryContext.outdated = { ...node.queryContext.outdated, outOfRange: outOfRangeContext, } return node } // any other outdatedKind is unknown and will never match return false })) // return an array with the holes for non-matching nodes removed return initialResults.filter(Boolean) } } // operators for attribute selectors const attributeOperators = { // attribute value is equivalent '=' ({ attr, value }) { return attr === value }, // attribute value contains word '~=' ({ attr, value }) { return (attr.match(/\w+/g) || []).includes(value) }, // attribute value contains string '*=' ({ attr, value }) { return attr.includes(value) }, // attribute value is equal or starts with '|=' ({ attr, value }) { return attr.startsWith(`${value}-`) }, // attribute value starts with '^=' ({ attr, value }) { return attr.startsWith(value) }, // attribute value ends with '$=' ({ attr, value }) { return attr.endsWith(value) }, } const attributeOperator = ({ attr, value, insensitive, operator }) => { if (typeof attr === 'number') { attr = String(attr) } if (typeof attr !== 'string') { // It's an object or an array, bail return false } if (insensitive) { attr = attr.toLowerCase() } return attributeOperators[operator]({ attr, insensitive, value, }) } const attributeMatch = (matcher, obj) => { const insensitive = !!matcher.insensitive const operator = matcher.operator || '' const attribute = matcher.qualifiedAttribute let value = matcher.value || '' // return early if checking existence if (operator === '') { return Boolean(obj[attribute]) } if (insensitive) { value = value.toLowerCase() } // in case the current object is an array // then we try to match every item in the array if (Array.isArray(obj[attribute])) { return obj[attribute].find((i, index) => { const attr = obj[attribute][index] || '' return attributeOperator({ attr, value, insensitive, operator }) }) } else { const attr = obj[attribute] || '' return attributeOperator({ attr, value, insensitive, operator }) } } const edgeIsType = (node, type, seen = new Set()) => { for (const edgeIn of node.edgesIn) { // TODO Need a test with an infinite loop if (seen.has(edgeIn)) { continue } seen.add(edgeIn) if (edgeIn.type === type || edgeIn.from[type] || edgeIsType(edgeIn.from, type, seen)) { return true } } return false } const filterByType = (nodes, type) => { const found = [] for (const node of nodes) { if (node[type] || edgeIsType(node, type)) { found.push(node) } } return found } const depTypes = { // dependency '.prod' (prevResults) { const found = [] for (const node of prevResults) { if (!node.dev) { found.push(node) } } return found }, // devDependency '.dev' (prevResults) { return filterByType(prevResults, 'dev') }, // optionalDependency '.optional' (prevResults) { return filterByType(prevResults, 'optional') }, // peerDependency '.peer' (prevResults) { return filterByType(prevResults, 'peer') }, // workspace '.workspace' (prevResults) { return prevResults.filter(node => node.isWorkspace) }, // bundledDependency '.bundled' (prevResults) { return prevResults.filter(node => node.inBundle) }, } // checks if a given node has a direct parent in any of the nodes provided in // the compare nodes array const hasParent = (node, compareNodes) => { // All it takes is one so we loop and return on the first hit for (let compareNode of compareNodes) { if (compareNode.isLink) { compareNode = compareNode.target } // follows logical parent for link anscestors if (node.isTop && (node.resolveParent === compareNode)) { return true } // follows edges-in to check if they match a possible parent for (const edge of node.edgesIn) { if (edge && edge.from === compareNode) { return true } } } return false } // checks if a given node is a descendant of any of the nodes provided in the // compareNodes array const hasAscendant = (node, compareNodes, seen = new Set()) => { // TODO (future) loop over ancestry property if (hasParent(node, compareNodes)) { return true } if (node.isTop && node.resolveParent) { /* istanbul ignore if - investigate if linksIn check obviates need for this */ if (hasAscendant(node.resolveParent, compareNodes)) { return true } } for (const edge of node.edgesIn) { // TODO Need a test with an infinite loop if (seen.has(edge)) { continue } seen.add(edge) if (edge && edge.from && hasAscendant(edge.from, compareNodes, seen)) { return true } } for (const linkNode of node.linksIn) { if (hasAscendant(linkNode, compareNodes, seen)) { return true } } return false } const combinators = { // direct descendant '>' (prevResults, nextResults) { return nextResults.filter(node => hasParent(node, prevResults)) }, // any descendant ' ' (prevResults, nextResults) { return nextResults.filter(node => hasAscendant(node, prevResults)) }, // sibling '~' (prevResults, nextResults) { // Return any node in nextResults that is a sibling of (aka shares a // parent with) a node in prevResults const parentNodes = new Set() // Parents of everything in prevResults for (const node of prevResults) { for (const edge of node.edgesIn) { // edge.from always exists cause it's from another node's edgesIn parentNodes.add(edge.from) } } return nextResults.filter(node => !prevResults.includes(node) && hasParent(node, [...parentNodes]) ) }, } // get a list of available versions of a package filtered to respect --before // NOTE: this runs over each node and should not throw const getPackageVersions = async (name, opts) => { let packument try { packument = await pacote.packument(name, { ...opts, fullMetadata: false, // we only need the corgi }) } catch (err) { // if the fetch fails, log a warning and pretend there are no versions log.warn('query', `could not retrieve packument for ${name}: ${err.message}`) return [] } // start with a sorted list of all versions (lowest first) let candidates = Object.keys(packument.versions).sort(semver.compare) // if the packument has a time property, and the user passed a before flag, then // we filter this list down to only those versions that existed before the specified date if (packument.time && opts.before) { candidates = candidates.filter((version) => { // this version isn't found in the times at all, drop it if (!packument.time[version]) { return false } return Date.parse(packument.time[version]) <= opts.before }) } return candidates } const retrieveNodesFromParsedAst = async (opts) => { // when we first call this it's the parsed query. all other times it's // results.currentNode.nestedNode const rootAstNode = opts.rootAstNode if (!rootAstNode.nodes) { return new Set() } const results = new Results(opts) const astNodeQueue = new Set() // walk is sync, so we have to build up our async functions and then await them later rootAstNode.walk((nextAstNode) => { astNodeQueue.add(nextAstNode) }) for (const nextAstNode of astNodeQueue) { // This is the only place we reset currentAstNode results.currentAstNode = nextAstNode const updateFn = `${results.currentAstNode.type}Type` if (typeof results[updateFn] !== 'function') { throw Object.assign( new Error(`\`${results.currentAstNode.type}\` is not a supported selector.`), { code: 'EQUERYNOSELECTOR' } ) } await results[updateFn]() } return results.collect(rootAstNode) } const querySelectorAll = async (targetNode, query, flatOptions) => { // This never changes ever we just pass it around. But we can't scope it to // this whole file if we ever want to support concurrent calls to this // function. const inventory = [...targetNode.root.inventory.values()] // res is a Set of items returned for each parsed css ast selector const res = await retrieveNodesFromParsedAst({ initialItems: inventory, inventory, flatOptions, rootAstNode: parser(query), targetNode, }) // returns nodes ordered by realpath return [...res].sort((a, b) => localeCompare(a.location, b.location)) } module.exports = querySelectorAll PK ~\lh '@npmcli/arborist/lib/packument-cache.jsnu[const { LRUCache } = require('lru-cache') const { getHeapStatistics } = require('node:v8') const { log } = require('proc-log') // This is an in-memory cache that Pacote uses for packuments. // Packuments are usually cached on disk. This allows for rapid re-requests // of the same packument to bypass disk reads. The tradeoff here is memory // usage for disk reads. class PackumentCache extends LRUCache { static #heapLimit = Math.floor(getHeapStatistics().heap_size_limit) #sizeKey #disposed = new Set() #log (...args) { log.silly('packumentCache', ...args) } constructor ({ // How much of this.#heapLimit to take up heapFactor = 0.25, // How much of this.#maxSize we allow any one packument to take up // Anything over this is not cached maxEntryFactor = 0.5, sizeKey = '_contentLength', } = {}) { const maxSize = Math.floor(PackumentCache.#heapLimit * heapFactor) const maxEntrySize = Math.floor(maxSize * maxEntryFactor) super({ maxSize, maxEntrySize, sizeCalculation: (p) => { // Don't cache if we dont know the size // Some versions of pacote set this to `0`, newer versions set it to `null` if (!p[sizeKey]) { return maxEntrySize + 1 } if (p[sizeKey] < 10_000) { return p[sizeKey] * 2 } if (p[sizeKey] < 1_000_000) { return Math.floor(p[sizeKey] * 1.5) } // It is less beneficial to store a small amount of super large things // at the cost of all other packuments. return maxEntrySize + 1 }, dispose: (v, k) => { this.#disposed.add(k) this.#log(k, 'dispose') }, }) this.#sizeKey = sizeKey this.#log(`heap:${PackumentCache.#heapLimit} maxSize:${maxSize} maxEntrySize:${maxEntrySize}`) } set (k, v, ...args) { // we use disposed only for a logging signal if we are setting packuments that // have already been evicted from the cache previously. logging here could help // us tune this in the future. const disposed = this.#disposed.has(k) /* istanbul ignore next - this doesnt happen consistently so hard to test without resorting to unit tests */ if (disposed) { this.#disposed.delete(k) } this.#log(k, 'set', `size:${v[this.#sizeKey]} disposed:${disposed}`) return super.set(k, v, ...args) } has (k, ...args) { const has = super.has(k, ...args) this.#log(k, `cache-${has ? 'hit' : 'miss'}`) return has } } module.exports = PackumentCache PK ~\֛H H '@npmcli/arborist/lib/peer-entry-sets.jsnu[// Given a node in a tree, return all of the peer dependency sets that // it is a part of, with the entry (top or non-peer) edges into the sets // identified. // // With this information, we can determine whether it is appropriate to // replace the entire peer set with another (and remove the old one), // push the set deeper into the tree, and so on. // // Returns a Map of { edge => Set(peerNodes) }, const peerEntrySets = node => { // this is the union of all peer groups that the node is a part of // later, we identify all of the entry edges, and create a set of // 1 or more overlapping sets that this node is a part of. const unionSet = new Set([node]) for (const node of unionSet) { for (const edge of node.edgesOut.values()) { if (edge.valid && edge.peer && edge.to) { unionSet.add(edge.to) } } for (const edge of node.edgesIn) { if (edge.valid && edge.peer) { unionSet.add(edge.from) } } } const entrySets = new Map() for (const peer of unionSet) { for (const edge of peer.edgesIn) { // if not valid, it doesn't matter anyway. either it's been previously // peerConflicted, or it's the thing we're interested in replacing. if (!edge.valid) { continue } // this is the entry point into the peer set if (!edge.peer || edge.from.isTop) { // get the subset of peer brought in by this peer entry edge const sub = new Set([peer]) for (const peer of sub) { for (const edge of peer.edgesOut.values()) { if (edge.valid && edge.peer && edge.to) { sub.add(edge.to) } } } // if this subset does not include the node we are focused on, // then it is not relevant for our purposes. Example: // // a -> (b, c, d) // b -> PEER(d) b -> d -> e -> f <-> g // c -> PEER(f, h) c -> (f <-> g, h -> g) // d -> PEER(e) d -> e -> f <-> g // e -> PEER(f) // f -> PEER(g) // g -> PEER(f) // h -> PEER(g) // // The unionSet(e) will include c, but we don't actually care about // it. We only expanded to the edge of the peer nodes in order to // find the entry edges that caused the inclusion of peer sets // including (e), so we want: // Map{ // Edge(a->b) => Set(b, d, e, f, g) // Edge(a->d) => Set(d, e, f, g) // } if (sub.has(node)) { entrySets.set(edge, sub) } } } } return entrySets } module.exports = peerEntrySets PK ~\ \SGG!@npmcli/arborist/lib/from-path.jsnu[// file dependencies need their dependencies resolved based on the location // where the tarball was found, not the location where they end up getting // installed. directory (ie, symlink) deps also need to be resolved based on // their targets, but that's what realpath is const { dirname } = require('node:path') const npa = require('npm-package-arg') const fromPath = (node, edge) => { if (edge && edge.overrides && edge.overrides.name === edge.name && edge.overrides.value) { // fromPath could be called with a node that has a virtual root, if that // happens we want to make sure we get the real root node when overrides // are in use. this is to allow things like overriding a dependency with a // tarball file that's a relative path from the project root if (node.sourceReference) { return node.sourceReference.root.realpath } return node.root.realpath } if (node.resolved) { const spec = npa(node.resolved) if (spec?.type === 'file') { return dirname(spec.fetchSpec) } } return node.realpath } module.exports = fromPath PK ~\h't(@npmcli/arborist/lib/version-from-tgz.jsnu[const semver = require('semver') const { basename } = require('node:path') const { URL } = require('node:url') module.exports = (name, tgz) => { const base = basename(tgz) if (!base.endsWith('.tgz')) { return null } if (tgz.startsWith('http:/') || tgz.startsWith('https:/')) { const u = new URL(tgz) // registry url? check for most likely pattern. // either /@foo/bar/-/bar-1.2.3.tgz or // /foo/-/foo-1.2.3.tgz, and fall through to // basename checking. Note that registries can // be mounted below the root url, so /a/b/-/x/y/foo/-/foo-1.2.3.tgz // is a potential option. const tfsplit = u.pathname.slice(1).split('/-/') if (tfsplit.length > 1) { const afterTF = tfsplit.pop() if (afterTF === base) { const pre = tfsplit.pop() const preSplit = pre.split(/\/|%2f/i) const project = preSplit.pop() const scope = preSplit.pop() return versionFromBaseScopeName(base, scope, project) } } } const split = name.split(/\/|%2f/i) const project = split.pop() const scope = split.pop() return versionFromBaseScopeName(base, scope, project) } const versionFromBaseScopeName = (base, scope, name) => { if (!base.startsWith(name + '-')) { return null } const parsed = semver.parse(base.substring(name.length + 1, base.length - 4)) return parsed ? { name: scope && scope.charAt(0) === '@' ? `${scope}/${name}` : name, version: parsed.version, } : null } PK ~\E#@npmcli/arborist/lib/node.jsnu[// inventory, path, realpath, root, and parent // // node.root is a reference to the root module in the tree (ie, typically the // cwd project folder) // // node.location is the /-delimited path from the root module to the node. In // the case of link targets that may be outside of the root's package tree, // this can include some number of /../ path segments. The location of the // root module is always '.'. node.location thus never contains drive letters // or absolute paths, and is portable within a given project, suitable for // inclusion in lockfiles and metadata. // // node.path is the path to the place where this node lives on disk. It is // system-specific and absolute. // // node.realpath is the path to where the module actually resides on disk. In // the case of non-link nodes, node.realpath is equivalent to node.path. In // the case of link nodes, it is equivalent to node.target.path. // // Setting node.parent will set the node's root to the parent's root, as well // as updating edgesIn and edgesOut to reload dependency resolutions as needed, // and setting node.path to parent.path/node_modules/name. // // node.inventory is a Map of name to a Set() of all the nodes under a given // root by that name. It's empty for non-root nodes, and changing the root // reference will remove it from the old root's inventory and add it to the new // one. This map is useful for cases like `npm update foo` or `npm ls foo` // where we need to quickly find all instances of a given package name within a // tree. const semver = require('semver') const nameFromFolder = require('@npmcli/name-from-folder') const Edge = require('./edge.js') const Inventory = require('./inventory.js') const OverrideSet = require('./override-set.js') const { normalize } = require('read-package-json-fast') const { getPaths: getBinPaths } = require('bin-links') const npa = require('npm-package-arg') const debug = require('./debug.js') const gatherDepSet = require('./gather-dep-set.js') const treeCheck = require('./tree-check.js') const { walkUp } = require('walk-up-path') const { resolve, relative, dirname, basename } = require('node:path') const util = require('node:util') const _package = Symbol('_package') const _parent = Symbol('_parent') const _target = Symbol.for('_target') const _fsParent = Symbol('_fsParent') const _reloadNamedEdges = Symbol('_reloadNamedEdges') // overridden by Link class const _loadDeps = Symbol.for('Arborist.Node._loadDeps') const _refreshLocation = Symbol.for('_refreshLocation') const _changePath = Symbol.for('_changePath') // used by Link class as well const _delistFromMeta = Symbol.for('_delistFromMeta') const _explain = Symbol('_explain') const _explanation = Symbol('_explanation') const relpath = require('./relpath.js') const consistentResolve = require('./consistent-resolve.js') const printableTree = require('./printable.js') const CaseInsensitiveMap = require('./case-insensitive-map.js') const querySelectorAll = require('./query-selector-all.js') class Node { #global #meta #root #workspaces constructor (options) { // NB: path can be null if it's a link target const { root, path, realpath, parent, error, meta, fsParent, resolved, integrity, // allow setting name explicitly when we haven't set a path yet name, children, fsChildren, installLinks = false, legacyPeerDeps = false, linksIn, isInStore = false, hasShrinkwrap, overrides, loadOverrides = false, extraneous = true, dev = true, optional = true, devOptional = true, peer = true, global = false, dummy = false, sourceReference = null, } = options // this object gives querySelectorAll somewhere to stash context about a node // while processing a query this.queryContext = {} // true if part of a global install this.#global = global this.#workspaces = null this.errors = error ? [error] : [] this.isInStore = isInStore // this will usually be null, except when modeling a // package's dependencies in a virtual root. this.sourceReference = sourceReference // TODO if this came from pacote.manifest we don't have to do this, // we can be told to skip this step const pkg = sourceReference ? sourceReference.package : normalize(options.pkg || {}) this.name = name || nameFromFolder(path || pkg.name || realpath) || pkg.name || null // should be equal if not a link this.path = path ? resolve(path) : null if (!this.name && (!this.path || this.path !== dirname(this.path))) { throw new TypeError('could not detect node name from path or package') } this.realpath = !this.isLink ? this.path : resolve(realpath) this.resolved = resolved || null if (!this.resolved) { // note: this *only* works for non-file: deps, so we avoid even // trying here. // file: deps are tracked in package.json will _resolved set to the // full path to the tarball or link target. However, if the package // is checked into git or moved to another location, that's 100% not // portable at all! The _where and _location don't provide much help, // since _location is just where the module ended up in the tree, // and _where can be different than the actual root if it's a // meta-dep deeper in the dependency graph. // // If we don't have the other oldest indicators of legacy npm, then it's // probably what we're getting from pacote, which IS trustworthy. // // Otherwise, hopefully a shrinkwrap will help us out. const resolved = consistentResolve(pkg._resolved) if (resolved && !(/^file:/.test(resolved) && pkg._where)) { this.resolved = resolved } } this.integrity = integrity || pkg._integrity || null this.hasShrinkwrap = hasShrinkwrap || pkg._hasShrinkwrap || false this.installLinks = installLinks this.legacyPeerDeps = legacyPeerDeps this.children = new CaseInsensitiveMap() this.fsChildren = new Set() this.inventory = new Inventory() this.tops = new Set() this.linksIn = new Set(linksIn || []) // these three are set by an Arborist taking a catalog // after the tree is built. We don't get this along the way, // because they have a tendency to change as new children are // added, especially when they're deduped. Eg, a dev dep may be // a 3-levels-deep dependency of a non-dev dep. If we calc the // flags along the way, then they'll tend to be invalid by the // time we need to look at them. if (!dummy) { this.dev = dev this.optional = optional this.devOptional = devOptional this.peer = peer this.extraneous = extraneous this.dummy = false } else { // true if this is a placeholder for the purpose of serving as a // fsParent to link targets that get their deps resolved outside // the root tree folder. this.dummy = true this.dev = false this.optional = false this.devOptional = false this.peer = false this.extraneous = false } this.edgesIn = new Set() this.edgesOut = new CaseInsensitiveMap() // have to set the internal package ref before assigning the parent, // because this.package is read when adding to inventory this[_package] = pkg && typeof pkg === 'object' ? pkg : {} if (overrides) { this.overrides = overrides } else if (loadOverrides) { const overrides = this[_package].overrides || {} if (Object.keys(overrides).length > 0) { this.overrides = new OverrideSet({ overrides: this[_package].overrides, }) } } // only relevant for the root and top nodes this.meta = meta // Note: this is _slightly_ less efficient for the initial tree // building than it could be, but in exchange, it's a much simpler // algorithm. // If this node has a bunch of children, and those children satisfy // its various deps, then we're going to _first_ create all the // edges, and _then_ assign the children into place, re-resolving // them all in _reloadNamedEdges. // A more efficient, but more complicated, approach would be to // flag this node as being a part of a tree build, so it could // hold off on resolving its deps until its children are in place. // call the parent setter // Must be set prior to calling _loadDeps, because top-ness is relevant // will also assign root if present on the parent this[_parent] = null this.parent = parent || null this[_fsParent] = null this.fsParent = fsParent || null // see parent/root setters below. // root is set to parent's root if we have a parent, otherwise if it's // null, then it's set to the node itself. if (!parent && !fsParent) { this.root = root || null } // mostly a convenience for testing, but also a way to create // trees in a more declarative way than setting parent on each if (children) { for (const c of children) { new Node({ ...c, parent: this }) } } if (fsChildren) { for (const c of fsChildren) { new Node({ ...c, fsParent: this }) } } // now load all the dep edges this[_loadDeps]() } get meta () { return this.#meta } set meta (meta) { this.#meta = meta if (meta) { meta.add(this) } } get global () { if (this.#root === this) { return this.#global } return this.#root.global } // true for packages installed directly in the global node_modules folder get globalTop () { return this.global && this.parent && this.parent.isProjectRoot } get workspaces () { return this.#workspaces } set workspaces (workspaces) { // deletes edges if they already exists if (this.#workspaces) { for (const name of this.#workspaces.keys()) { if (!workspaces.has(name)) { this.edgesOut.get(name).detach() } } } this.#workspaces = workspaces this.#loadWorkspaces() this[_loadDeps]() } get binPaths () { if (!this.parent) { return [] } return getBinPaths({ pkg: this[_package], path: this.path, global: this.global, top: this.globalTop, }) } get hasInstallScript () { const { hasInstallScript, scripts } = this.package const { install, preinstall, postinstall } = scripts || {} return !!(hasInstallScript || install || preinstall || postinstall) } get version () { return this[_package].version || '' } get packageName () { return this[_package].name || null } get pkgid () { const { name = '', version = '' } = this.package // root package will prefer package name over folder name, // and never be called an alias. const { isProjectRoot } = this const myname = isProjectRoot ? name || this.name : this.name const alias = !isProjectRoot && name && myname !== name ? `npm:${name}@` : '' return `${myname}@${alias}${version}` } get overridden () { return !!(this.overrides && this.overrides.value && this.overrides.name === this.name) } get package () { return this[_package] } set package (pkg) { // just detach them all. we could make this _slightly_ more efficient // by only detaching the ones that changed, but we'd still have to walk // them all, and the comparison logic gets a bit tricky. we generally // only do this more than once at the root level, so the resolve() calls // are only one level deep, and there's not much to be saved, anyway. // simpler to just toss them all out. for (const edge of this.edgesOut.values()) { edge.detach() } this[_explanation] = null /* istanbul ignore next - should be impossible */ if (!pkg || typeof pkg !== 'object') { debug(() => { throw new Error('setting Node.package to non-object') }) pkg = {} } this[_package] = pkg this.#loadWorkspaces() this[_loadDeps]() // do a hard reload, since the dependents may now be valid or invalid // as a result of the package change. this.edgesIn.forEach(edge => edge.reload(true)) } // node.explain(nodes seen already, edge we're trying to satisfy // if edge is not specified, it lists every edge into the node. explain (edge = null, seen = []) { if (this[_explanation]) { return this[_explanation] } return this[_explanation] = this[_explain](edge, seen) } [_explain] (edge, seen) { if (this.isProjectRoot && !this.sourceReference) { return { location: this.path, } } const why = { name: this.isProjectRoot || this.isTop ? this.packageName : this.name, version: this.package.version, } if (this.errors.length || !this.packageName || !this.package.version) { why.errors = this.errors.length ? this.errors : [ new Error('invalid package: lacks name and/or version'), ] why.package = this.package } if (this.root.sourceReference) { const { name, version } = this.root.package why.whileInstalling = { name, version, path: this.root.sourceReference.path, } } if (this.sourceReference) { return this.sourceReference.explain(edge, seen) } if (seen.includes(this)) { return why } why.location = this.location why.isWorkspace = this.isWorkspace // make a new list each time. we can revisit, but not loop. seen = seen.concat(this) why.dependents = [] if (edge) { why.dependents.push(edge.explain(seen)) } else { // ignore invalid edges, since those aren't satisfied by this thing, // and are not keeping it held in this spot anyway. const edges = [] for (const edge of this.edgesIn) { if (!edge.valid && !edge.from.isProjectRoot) { continue } edges.push(edge) } for (const edge of edges) { why.dependents.push(edge.explain(seen)) } } if (this.linksIn.size) { why.linksIn = [...this.linksIn].map(link => link[_explain](edge, seen)) } return why } isDescendantOf (node) { for (let p = this; p; p = p.resolveParent) { if (p === node) { return true } } return false } getBundler (path = []) { // made a cycle, definitely not bundled! if (path.includes(this)) { return null } path.push(this) const parent = this[_parent] if (!parent) { return null } const pBundler = parent.getBundler(path) if (pBundler) { return pBundler } const ppkg = parent.package const bd = ppkg && ppkg.bundleDependencies // explicit bundling if (Array.isArray(bd) && bd.includes(this.name)) { return parent } // deps that are deduped up to the bundling level are bundled. // however, if they get their dep met further up than that, // then they are not bundled. Ie, installing a package with // unmet bundled deps will not cause your deps to be bundled. for (const edge of this.edgesIn) { const eBundler = edge.from.getBundler(path) if (!eBundler) { continue } if (eBundler === parent) { return eBundler } } return null } get inBundle () { return !!this.getBundler() } // when reifying, if a package is technically in a bundleDependencies list, // but that list is the root project, we still have to install it. This // getter returns true if it's in a dependency's bundle list, not the root's. get inDepBundle () { const bundler = this.getBundler() return !!bundler && bundler !== this.root } get isWorkspace () { if (this.isProjectRoot) { return false } const { root } = this const { type, to } = root.edgesOut.get(this.packageName) || {} return type === 'workspace' && to && (to.target === this || to === this) } get isRoot () { return this === this.root } get isProjectRoot () { // only treat as project root if it's the actual link that is the root, // or the target of the root link, but NOT if it's another link to the // same root that happens to be somewhere else. return this === this.root || this === this.root.target } get isRegistryDependency () { if (this.edgesIn.size === 0) { return false } for (const edge of this.edgesIn) { if (!npa(edge.spec).registry) { return false } } return true } * ancestry () { for (let anc = this; anc; anc = anc.resolveParent) { yield anc } } set root (root) { // setting to null means this is the new root // should only ever be one step while (root && root.root !== root) { root = root.root } root = root || this // delete from current root inventory this[_delistFromMeta]() // can't set the root (yet) if there's no way to determine location // this allows us to do new Node({...}) and then set the root later. // just make the assignment so we don't lose it, and move on. if (!this.path || !root.realpath || !root.path) { this.#root = root return } // temporarily become a root node this.#root = this // break all linksIn, we're going to re-set them if needed later for (const link of this.linksIn) { link[_target] = null this.linksIn.delete(link) } // temporarily break this link as well, we'll re-set if possible later const { target } = this if (this.isLink) { if (target) { target.linksIn.delete(this) if (target.root === this) { target[_delistFromMeta]() } } this[_target] = null } // if this is part of a cascading root set, then don't do this bit // but if the parent/fsParent is in a different set, we have to break // that reference before proceeding if (this.parent && this.parent.root !== root) { this.parent.children.delete(this.name) this[_parent] = null } if (this.fsParent && this.fsParent.root !== root) { this.fsParent.fsChildren.delete(this) this[_fsParent] = null } if (root === this) { this[_refreshLocation]() } else { // setting to some different node. const loc = relpath(root.realpath, this.path) const current = root.inventory.get(loc) // clobber whatever is there now if (current) { current.root = null } this.#root = root // set this.location and add to inventory this[_refreshLocation]() // try to find our parent/fsParent in the new root inventory for (const p of walkUp(dirname(this.path))) { if (p === this.path) { continue } const ploc = relpath(root.realpath, p) const parent = root.inventory.get(ploc) if (parent) { /* istanbul ignore next - impossible */ if (parent.isLink) { debug(() => { throw Object.assign(new Error('assigning parentage to link'), { path: this.path, parent: parent.path, parentReal: parent.realpath, }) }) continue } const childLoc = `${ploc}${ploc ? '/' : ''}node_modules/${this.name}` const isParent = this.location === childLoc if (isParent) { const oldChild = parent.children.get(this.name) if (oldChild && oldChild !== this) { oldChild.root = null } if (this.parent) { this.parent.children.delete(this.name) this.parent[_reloadNamedEdges](this.name) } parent.children.set(this.name, this) this[_parent] = parent // don't do it for links, because they don't have a target yet // we'll hit them up a bit later on. if (!this.isLink) { parent[_reloadNamedEdges](this.name) } } else { /* istanbul ignore if - should be impossible, since we break * all fsParent/child relationships when moving? */ if (this.fsParent) { this.fsParent.fsChildren.delete(this) } parent.fsChildren.add(this) this[_fsParent] = parent } break } } // if it doesn't have a parent, it's a top node if (!this.parent) { root.tops.add(this) } else { root.tops.delete(this) } // assign parentage for any nodes that need to have this as a parent // this can happen when we have a node at nm/a/nm/b added *before* // the node at nm/a, which might have the root node as a fsParent. // we can't rely on the public setter here, because it calls into // this function to set up these references! // check dirname so that /foo isn't treated as the fsparent of /foo-bar const nmloc = `${this.location}${this.location ? '/' : ''}node_modules/` // only walk top nodes, since anything else already has a parent. for (const child of root.tops) { const isChild = child.location === nmloc + child.name const isFsChild = dirname(child.path).startsWith(this.path) && child !== this && !child.parent && ( !child.fsParent || child.fsParent === this || dirname(this.path).startsWith(child.fsParent.path) ) if (!isChild && !isFsChild) { continue } // set up the internal parentage links if (this.isLink) { child.root = null } else { // can't possibly have a parent, because it's in tops if (child.fsParent) { child.fsParent.fsChildren.delete(child) } child[_fsParent] = null if (isChild) { this.children.set(child.name, child) child[_parent] = this root.tops.delete(child) } else { this.fsChildren.add(child) child[_fsParent] = this } } } // look for any nodes with the same realpath. either they're links // to that realpath, or a thing at that realpath if we're adding a link // (if we're adding a regular node, we already deleted the old one) for (const node of root.inventory.query('realpath', this.realpath)) { if (node === this) { continue } /* istanbul ignore next - should be impossible */ debug(() => { if (node.root !== root) { throw new Error('inventory contains node from other root') } }) if (this.isLink) { const target = node.target this[_target] = target this[_package] = target.package target.linksIn.add(this) // reload edges here, because now we have a target if (this.parent) { this.parent[_reloadNamedEdges](this.name) } break } else { /* istanbul ignore else - should be impossible */ if (node.isLink) { node[_target] = this node[_package] = this.package this.linksIn.add(node) if (node.parent) { node.parent[_reloadNamedEdges](node.name) } } else { debug(() => { throw Object.assign(new Error('duplicate node in root setter'), { path: this.path, realpath: this.realpath, root: root.realpath, }) }) } } } } // reload all edgesIn where the root doesn't match, so we don't have // cross-tree dependency graphs for (const edge of this.edgesIn) { if (edge.from.root !== root) { edge.reload() } } // reload all edgesOut where root doens't match, or is missing, since // it might not be missing in the new tree for (const edge of this.edgesOut.values()) { if (!edge.to || edge.to.root !== root) { edge.reload() } } // now make sure our family comes along for the ride! const family = new Set([ ...this.fsChildren, ...this.children.values(), ...this.inventory.values(), ].filter(n => n !== this)) for (const child of family) { if (child.root !== root) { child[_delistFromMeta]() child[_parent] = null this.children.delete(child.name) child[_fsParent] = null this.fsChildren.delete(child) for (const l of child.linksIn) { l[_target] = null child.linksIn.delete(l) } } } for (const child of family) { if (child.root !== root) { child.root = root } } // if we had a target, and didn't find one in the new root, then bring // it over as well, but only if we're setting the link into a new root, // as we don't want to lose the target any time we remove a link. if (this.isLink && target && !this.target && root !== this) { target.root = root } if (!this.overrides && this.parent && this.parent.overrides) { this.overrides = this.parent.overrides.getNodeRule(this) } // tree should always be valid upon root setter completion. treeCheck(this) if (this !== root) { treeCheck(root) } } get root () { return this.#root || this } #loadWorkspaces () { if (!this.#workspaces) { return } for (const [name, path] of this.#workspaces.entries()) { new Edge({ from: this, name, spec: `file:${path.replace(/#/g, '%23')}`, type: 'workspace' }) } } [_loadDeps] () { // Caveat! Order is relevant! // Packages in optionalDependencies are optional. // Packages in both deps and devDeps are required. // Note the subtle breaking change from v6: it is no longer possible // to have a different spec for a devDep than production dep. // Linked targets that are disconnected from the tree are tops, // but don't have a 'path' field, only a 'realpath', because we // don't know their canonical location. We don't need their devDeps. const pd = this.package.peerDependencies const ad = this.package.acceptDependencies || {} if (pd && typeof pd === 'object' && !this.legacyPeerDeps) { const pm = this.package.peerDependenciesMeta || {} const peerDependencies = {} const peerOptional = {} for (const [name, dep] of Object.entries(pd)) { if (pm[name]?.optional) { peerOptional[name] = dep } else { peerDependencies[name] = dep } } this.#loadDepType(peerDependencies, 'peer', ad) this.#loadDepType(peerOptional, 'peerOptional', ad) } this.#loadDepType(this.package.dependencies, 'prod', ad) this.#loadDepType(this.package.optionalDependencies, 'optional', ad) const { globalTop, isTop, path, sourceReference } = this const { globalTop: srcGlobalTop, isTop: srcTop, path: srcPath, } = sourceReference || {} const thisDev = isTop && !globalTop && path const srcDev = !sourceReference || srcTop && !srcGlobalTop && srcPath if (thisDev && srcDev) { this.#loadDepType(this.package.devDependencies, 'dev', ad) } } #loadDepType (deps, type, ad) { // Because of the order in which _loadDeps runs, we always want to // prioritize a new edge over an existing one for (const [name, spec] of Object.entries(deps || {})) { const current = this.edgesOut.get(name) if (!current || current.type !== 'workspace') { new Edge({ from: this, name, spec, accept: ad[name], type }) } } } get fsParent () { // in debug setter prevents fsParent from being this return this[_fsParent] } set fsParent (fsParent) { if (!fsParent) { if (this[_fsParent]) { this.root = null } return } debug(() => { if (fsParent === this) { throw new Error('setting node to its own fsParent') } if (fsParent.realpath === this.realpath) { throw new Error('setting fsParent to same path') } // the initial set MUST be an actual walk-up from the realpath // subsequent sets will re-root on the new fsParent's path. if (!this[_fsParent] && this.realpath.indexOf(fsParent.realpath) !== 0) { throw Object.assign(new Error('setting fsParent improperly'), { path: this.path, realpath: this.realpath, fsParent: { path: fsParent.path, realpath: fsParent.realpath, }, }) } }) if (fsParent.isLink) { fsParent = fsParent.target } // setting a thing to its own fsParent is not normal, but no-op for safety if (this === fsParent || fsParent.realpath === this.realpath) { return } // nothing to do if (this[_fsParent] === fsParent) { return } const oldFsParent = this[_fsParent] const newPath = !oldFsParent ? this.path : resolve(fsParent.path, relative(oldFsParent.path, this.path)) const nmPath = resolve(fsParent.path, 'node_modules', this.name) // this is actually the parent, set that instead if (newPath === nmPath) { this.parent = fsParent return } const pathChange = newPath !== this.path // remove from old parent/fsParent const oldParent = this.parent const oldName = this.name if (this.parent) { this.parent.children.delete(this.name) this[_parent] = null } if (this.fsParent) { this.fsParent.fsChildren.delete(this) this[_fsParent] = null } // update this.path/realpath for this and all children/fsChildren if (pathChange) { this[_changePath](newPath) } if (oldParent) { oldParent[_reloadNamedEdges](oldName) } // clobbers anything at that path, resets all appropriate references this.root = fsParent.root } // is it safe to replace one node with another? check the edges to // make sure no one will get upset. Note that the node might end up // having its own unmet dependencies, if the new node has new deps. // Note that there are cases where Arborist will opt to insert a node // into the tree even though this function returns false! This is // necessary when a root dependency is added or updated, or when a // root dependency brings peer deps along with it. In that case, we // will go ahead and create the invalid state, and then try to resolve // it with more tree construction, because it's a user request. canReplaceWith (node, ignorePeers) { if (node.name !== this.name) { return false } if (node.packageName !== this.packageName) { return false } // XXX need to check for two root nodes? if (node.overrides !== this.overrides) { return false } ignorePeers = new Set(ignorePeers) // gather up all the deps of this node and that are only depended // upon by deps of this node. those ones don't count, since // they'll be replaced if this node is replaced anyway. const depSet = gatherDepSet([this], e => e.to !== this && e.valid) for (const edge of this.edgesIn) { // when replacing peer sets, we need to be able to replace the entire // peer group, which means we ignore incoming edges from other peers // within the replacement set. if (!this.isTop && edge.from.parent === this.parent && edge.peer && ignorePeers.has(edge.from.name)) { continue } // only care about edges that don't originate from this node if (!depSet.has(edge.from) && !edge.satisfiedBy(node)) { return false } } return true } canReplace (node, ignorePeers) { return node.canReplaceWith(this, ignorePeers) } // return true if it's safe to remove this node, because anything that // is depending on it would be fine with the thing that they would resolve // to if it was removed, or nothing is depending on it in the first place. canDedupe (preferDedupe = false) { // not allowed to mess with shrinkwraps or bundles if (this.inDepBundle || this.inShrinkwrap) { return false } // it's a top level pkg, or a dep of one if (!this.resolveParent || !this.resolveParent.resolveParent) { return false } // no one wants it, remove it if (this.edgesIn.size === 0) { return true } const other = this.resolveParent.resolveParent.resolve(this.name) // nothing else, need this one if (!other) { return false } // if it's the same thing, then always fine to remove if (other.matches(this)) { return true } // if the other thing can't replace this, then skip it if (!other.canReplace(this)) { return false } // if we prefer dedupe, or if the version is greater/equal, take the other if (preferDedupe || semver.gte(other.version, this.version)) { return true } return false } satisfies (requested) { if (requested instanceof Edge) { return this.name === requested.name && requested.satisfiedBy(this) } const parsed = npa(requested) const { name = this.name, rawSpec: spec } = parsed return this.name === name && this.satisfies(new Edge({ from: new Node({ path: this.root.realpath }), type: 'prod', name, spec, })) } matches (node) { // if the nodes are literally the same object, obviously a match. if (node === this) { return true } // if the names don't match, they're different things, even if // the package contents are identical. if (node.name !== this.name) { return false } // if they're links, they match if the targets match if (this.isLink) { return node.isLink && this.target.matches(node.target) } // if they're two project root nodes, they're different if the paths differ if (this.isProjectRoot && node.isProjectRoot) { return this.path === node.path } // if the integrity matches, then they're the same. if (this.integrity && node.integrity) { return this.integrity === node.integrity } // if no integrity, check resolved if (this.resolved && node.resolved) { return this.resolved === node.resolved } // if no resolved, check both package name and version // otherwise, conclude that they are different things return this.packageName && node.packageName && this.packageName === node.packageName && this.version && node.version && this.version === node.version } // replace this node with the supplied argument // Useful when mutating an ideal tree, so we can avoid having to call // the parent/root setters more than necessary. replaceWith (node) { node.replace(this) } replace (node) { this[_delistFromMeta]() // if the name matches, but is not identical, we are intending to clobber // something case-insensitively, so merely setting name and path won't // have the desired effect. just set the path so it'll collide in the // parent's children map, and leave it at that. if (node.parent?.children.get(this.name) === node) { this.path = resolve(node.parent.path, 'node_modules', this.name) } else { this.path = node.path this.name = node.name } if (!this.isLink) { this.realpath = this.path } this[_refreshLocation]() // keep children when a node replaces another if (!this.isLink) { for (const kid of node.children.values()) { kid.parent = this } if (node.isLink && node.target) { node.target.root = null } } if (!node.isRoot) { this.root = node.root } treeCheck(this) } get inShrinkwrap () { return this.parent && (this.parent.hasShrinkwrap || this.parent.inShrinkwrap) } get parent () { // setter prevents _parent from being this return this[_parent] } // This setter keeps everything in order when we move a node from // one point in a logical tree to another. Edges get reloaded, // metadata updated, etc. It's also called when we *replace* a node // with another by the same name (eg, to update or dedupe). // This does a couple of walks out on the node_modules tree, recursing // into child nodes. However, as setting the parent is typically done // with nodes that don't have have many children, and (deduped) package // trees tend to be broad rather than deep, it's not that bad. // The only walk that starts from the parent rather than this node is // limited by edge name. set parent (parent) { // when setting to null, just remove it from the tree entirely if (!parent) { // but only delete it if we actually had a parent in the first place // otherwise it's just setting to null when it's already null if (this[_parent]) { this.root = null } return } if (parent.isLink) { parent = parent.target } // setting a thing to its own parent is not normal, but no-op for safety if (this === parent) { return } const oldParent = this[_parent] // nothing to do if (oldParent === parent) { return } // ok now we know something is actually changing, and parent is not a link const newPath = resolve(parent.path, 'node_modules', this.name) const pathChange = newPath !== this.path // remove from old parent/fsParent if (oldParent) { oldParent.children.delete(this.name) this[_parent] = null } if (this.fsParent) { this.fsParent.fsChildren.delete(this) this[_fsParent] = null } // update this.path/realpath for this and all children/fsChildren if (pathChange) { this[_changePath](newPath) } if (parent.overrides) { this.overrides = parent.overrides.getNodeRule(this) } // clobbers anything at that path, resets all appropriate references this.root = parent.root } // Call this before changing path or updating the _root reference. // Removes the node from its root the metadata and inventory. [_delistFromMeta] () { const root = this.root if (!root.realpath || !this.path) { return } root.inventory.delete(this) root.tops.delete(this) if (root.meta) { root.meta.delete(this.path) } /* istanbul ignore next - should be impossible */ debug(() => { if ([...root.inventory.values()].includes(this)) { throw new Error('failed to delist') } }) } // update this.path/realpath and the paths of all children/fsChildren [_changePath] (newPath) { // have to de-list before changing paths this[_delistFromMeta]() const oldPath = this.path this.path = newPath const namePattern = /(?:^|\/|\\)node_modules[\\/](@[^/\\]+[\\/][^\\/]+|[^\\/]+)$/ const nameChange = newPath.match(namePattern) if (nameChange && this.name !== nameChange[1]) { this.name = nameChange[1].replace(/\\/g, '/') } // if we move a link target, update link realpaths if (!this.isLink) { this.realpath = newPath for (const link of this.linksIn) { link[_delistFromMeta]() link.realpath = newPath link[_refreshLocation]() } } // if we move /x to /y, then a module at /x/a/b becomes /y/a/b for (const child of this.fsChildren) { child[_changePath](resolve(newPath, relative(oldPath, child.path))) } for (const [name, child] of this.children.entries()) { child[_changePath](resolve(newPath, 'node_modules', name)) } this[_refreshLocation]() } // Called whenever the root/parent is changed. // NB: need to remove from former root's meta/inventory and then update // this.path BEFORE calling this method! [_refreshLocation] () { const root = this.root const loc = relpath(root.realpath, this.path) this.location = loc root.inventory.add(this) if (root.meta) { root.meta.add(this) } } assertRootOverrides () { if (!this.isProjectRoot || !this.overrides) { return } for (const edge of this.edgesOut.values()) { // if these differ an override has been applied, those are not allowed // for top level dependencies so throw an error if (edge.spec !== edge.rawSpec && !edge.spec.startsWith('$')) { throw Object.assign(new Error(`Override for ${edge.name}@${edge.rawSpec} conflicts with direct dependency`), { code: 'EOVERRIDE' }) } } } addEdgeOut (edge) { if (this.overrides) { edge.overrides = this.overrides.getEdgeRule(edge) } this.edgesOut.set(edge.name, edge) } addEdgeIn (edge) { if (edge.overrides) { this.overrides = edge.overrides } this.edgesIn.add(edge) // try to get metadata from the yarn.lock file if (this.root.meta) { this.root.meta.addEdge(edge) } } [_reloadNamedEdges] (name, rootLoc = this.location) { const edge = this.edgesOut.get(name) // if we don't have an edge, do nothing, but keep descending const rootLocResolved = edge && edge.to && edge.to.location === `${rootLoc}/node_modules/${edge.name}` const sameResolved = edge && this.resolve(name) === edge.to const recheck = rootLocResolved || !sameResolved if (edge && recheck) { edge.reload(true) } for (const c of this.children.values()) { c[_reloadNamedEdges](name, rootLoc) } for (const c of this.fsChildren) { c[_reloadNamedEdges](name, rootLoc) } } get isLink () { return false } get target () { return this } set target (n) { debug(() => { throw Object.assign(new Error('cannot set target on non-Link Nodes'), { path: this.path, }) }) } get depth () { if (this.isTop) { return 0 } return this.parent.depth + 1 } get isTop () { return !this.parent || this.globalTop } get top () { if (this.isTop) { return this } return this.parent.top } get isFsTop () { return !this.fsParent } get fsTop () { if (this.isFsTop) { return this } return this.fsParent.fsTop } get resolveParent () { return this.parent || this.fsParent } resolve (name) { /* istanbul ignore next - should be impossible, * but I keep doing this mistake in tests */ debug(() => { if (typeof name !== 'string' || !name) { throw new Error('non-string passed to Node.resolve') } }) const mine = this.children.get(name) if (mine) { return mine } const resolveParent = this.resolveParent if (resolveParent) { return resolveParent.resolve(name) } return null } inNodeModules () { const rp = this.realpath const name = this.name const scoped = name.charAt(0) === '@' const d = dirname(rp) const nm = scoped ? dirname(d) : d const dir = dirname(nm) const base = scoped ? `${basename(d)}/${basename(rp)}` : basename(rp) return base === name && basename(nm) === 'node_modules' ? dir : false } // maybe accept both string value or array of strings // seems to be what dom API does querySelectorAll (query, opts) { return querySelectorAll(this, query, opts) } toJSON () { return printableTree(this) } [util.inspect.custom] () { return this.toJSON() } } module.exports = Node PK ~\|&@npmcli/arborist/lib/gather-dep-set.jsnu[// Given a set of nodes in a tree, and a filter function to test // incoming edges to the dep set that should be ignored otherwise. // // find the set of deps that are only depended upon by nodes in the set, or // their dependencies, or edges that are ignored. // // Used when figuring out what to prune when replacing a node with a newer // version, or when an optional dep fails to install. const gatherDepSet = (set, edgeFilter) => { const deps = new Set(set) // add the full set of dependencies. note that this loop will continue // as the deps set increases in size. for (const node of deps) { for (const edge of node.edgesOut.values()) { if (edge.to && edgeFilter(edge)) { deps.add(edge.to) } } } // now remove all nodes in the set that have a dependant outside the set // if any change is made, then re-check // continue until no changes made, or deps set evaporates fully. let changed = true while (changed === true && deps.size > 0) { changed = false for (const dep of deps) { for (const edge of dep.edgesIn) { if (!deps.has(edge.from) && edgeFilter(edge)) { changed = true deps.delete(dep) break } } } } return deps } module.exports = gatherDepSet PK ~\}?77%@npmcli/arborist/lib/can-place-dep.jsnu[// Internal methods used by buildIdealTree. // Answer the question: "can I put this dep here?" // // IMPORTANT: *nothing* in this class should *ever* modify or mutate the tree // at all. The contract here is strictly limited to read operations. We call // this in the process of walking through the ideal tree checking many // different potential placement targets for a given node. If a change is made // to the tree along the way, that can cause serious problems! // // In order to enforce this restriction, in debug mode, canPlaceDep() will // snapshot the tree at the start of the process, and then at the end, will // verify that it still matches the snapshot, and throw an error if any changes // occurred. // // The algorithm is roughly like this: // - check the node itself: // - if there is no version present, and no conflicting edges from target, // OK, provided all peers can be placed at or above the target. // - if the current version matches, KEEP // - if there is an older version present, which can be replaced, then // - if satisfying and preferDedupe? KEEP // - else: REPLACE // - if there is a newer version present, and preferDedupe, REPLACE // - if the version present satisfies the edge, KEEP // - else: CONFLICT // - if the node is not in conflict, check each of its peers: // - if the peer can be placed in the target, continue // - else if the peer can be placed in a parent, and there is no other // conflicting version shadowing it, continue // - else CONFLICT // - If the peers are not in conflict, return the original node's value // // An exception to this logic is that if the target is the deepest location // that a node can be placed, and the conflicting node can be placed deeper, // then we will return REPLACE rather than CONFLICT, and Arborist will queue // the replaced node for resolution elsewhere. const localeCompare = require('@isaacs/string-locale-compare')('en') const semver = require('semver') const debug = require('./debug.js') const peerEntrySets = require('./peer-entry-sets.js') const deepestNestingTarget = require('./deepest-nesting-target.js') const CONFLICT = Symbol('CONFLICT') const OK = Symbol('OK') const REPLACE = Symbol('REPLACE') const KEEP = Symbol('KEEP') class CanPlaceDep { // dep is a dep that we're trying to place. it should already live in // a virtual tree where its peer set is loaded as children of the root. // target is the actual place where we're trying to place this dep // in a node_modules folder. // edge is the edge that we're trying to satisfy with this placement. // parent is the CanPlaceDep object of the entry node when placing a peer. constructor (options) { const { dep, target, edge, preferDedupe, parent = null, peerPath = [], explicitRequest = false, } = options debug(() => { if (!dep) { throw new Error('no dep provided to CanPlaceDep') } if (!target) { throw new Error('no target provided to CanPlaceDep') } if (!edge) { throw new Error('no edge provided to CanPlaceDep') } this._treeSnapshot = JSON.stringify([...target.root.inventory.entries()] .map(([loc, { packageName, version, resolved }]) => { return [loc, packageName, version, resolved] }).sort(([a], [b]) => localeCompare(a, b))) }) // the result of whether we can place it or not this.canPlace = null // if peers conflict, but this one doesn't, then that is useful info this.canPlaceSelf = null this.dep = dep this.target = target this.edge = edge this.explicitRequest = explicitRequest // preventing cycles when we check peer sets this.peerPath = peerPath // we always prefer to dedupe peers, because they are trying // a bit harder to be singletons. this.preferDedupe = !!preferDedupe || edge.peer this.parent = parent this.children = [] this.isSource = target === this.peerSetSource this.name = edge.name this.current = target.children.get(this.name) this.targetEdge = target.edgesOut.get(this.name) this.conflicts = new Map() // check if this dep was already subject to a peerDep override while // building the peerSet. this.edgeOverride = !dep.satisfies(edge) this.canPlace = this.checkCanPlace() if (!this.canPlaceSelf) { this.canPlaceSelf = this.canPlace } debug(() => { const treeSnapshot = JSON.stringify([...target.root.inventory.entries()] .map(([loc, { packageName, version, resolved }]) => { return [loc, packageName, version, resolved] }).sort(([a], [b]) => localeCompare(a, b))) /* istanbul ignore if */ if (this._treeSnapshot !== treeSnapshot) { throw Object.assign(new Error('tree changed in CanPlaceDep'), { expect: this._treeSnapshot, actual: treeSnapshot, }) } }) } checkCanPlace () { const { target, targetEdge, current, dep } = this // if the dep failed to load, we're going to fail the build or // prune it out anyway, so just move forward placing/replacing it. if (dep.errors.length) { return current ? REPLACE : OK } // cannot place peers inside their dependents, except for tops if (targetEdge && targetEdge.peer && !target.isTop) { return CONFLICT } // skip this test if there's a current node, because we might be able // to dedupe against it anyway if (!current && targetEdge && !dep.satisfies(targetEdge) && targetEdge !== this.edge) { return CONFLICT } return current ? this.checkCanPlaceCurrent() : this.checkCanPlaceNoCurrent() } // we know that the target has a dep by this name in its node_modules // already. Can return KEEP, REPLACE, or CONFLICT. checkCanPlaceCurrent () { const { preferDedupe, explicitRequest, current, target, edge, dep } = this if (dep.matches(current)) { if (current.satisfies(edge) || this.edgeOverride) { return explicitRequest ? REPLACE : KEEP } } const { version: curVer } = current const { version: newVer } = dep const tryReplace = curVer && newVer && semver.gte(newVer, curVer) if (tryReplace && dep.canReplace(current)) { // It's extremely rare that a replaceable node would be a conflict, if // the current one wasn't a conflict, but it is theoretically possible // if peer deps are pinned. In that case we treat it like any other // conflict, and keep trying. const cpp = this.canPlacePeers(REPLACE) if (cpp !== CONFLICT) { return cpp } } // ok, can't replace the current with new one, but maybe current is ok? if (current.satisfies(edge) && (!explicitRequest || preferDedupe)) { return KEEP } // if we prefer deduping, then try replacing newer with older if (preferDedupe && !tryReplace && dep.canReplace(current)) { const cpp = this.canPlacePeers(REPLACE) if (cpp !== CONFLICT) { return cpp } } // Check for interesting cases! // First, is this the deepest place that this thing can go, and NOT the // deepest place where the conflicting dep can go? If so, replace it, // and let it re-resolve deeper in the tree. const myDeepest = this.deepestNestingTarget // ok, i COULD be placed deeper, so leave the current one alone. if (target !== myDeepest) { return CONFLICT } // if we are not checking a peerDep, then we MUST place it here, in the // target that has a non-peer dep on it. if (!edge.peer && target === edge.from) { return this.canPlacePeers(REPLACE) } // if we aren't placing a peer in a set, then we're done here. // This is ignored because it SHOULD be redundant, as far as I can tell, // with the deepest target and target===edge.from tests. But until we // can prove that isn't possible, this condition is here for safety. /* istanbul ignore if - allegedly impossible */ if (!this.parent && !edge.peer) { return CONFLICT } // check the deps in the peer group for each edge into that peer group // if ALL of them can be pushed deeper, or if it's ok to replace its // members with the contents of the new peer group, then we're good. let canReplace = true for (const [entryEdge, currentPeers] of peerEntrySets(current)) { if (entryEdge === this.edge || entryEdge === this.peerEntryEdge) { continue } // First, see if it's ok to just replace the peerSet entirely. // we do this by walking out from the entryEdge, because in a case like // this: // // v -> PEER(a@1||2) // a@1 -> PEER(b@1) // a@2 -> PEER(b@2) // b@1 -> PEER(a@1) // b@2 -> PEER(a@2) // // root // +-- v // +-- a@2 // +-- b@2 // // Trying to place a peer group of (a@1, b@1) would fail to note that // they can be replaced, if we did it by looping 1 by 1. If we are // replacing something, we don't have to check its peer deps, because // the peerDeps in the placed peerSet will presumably satisfy. const entryNode = entryEdge.to const entryRep = dep.parent.children.get(entryNode.name) if (entryRep) { if (entryRep.canReplace(entryNode, dep.parent.children.keys())) { continue } } let canClobber = !entryRep if (!entryRep) { const peerReplacementWalk = new Set([entryNode]) OUTER: for (const currentPeer of peerReplacementWalk) { for (const edge of currentPeer.edgesOut.values()) { if (!edge.peer || !edge.valid) { continue } const rep = dep.parent.children.get(edge.name) if (!rep) { if (edge.to) { peerReplacementWalk.add(edge.to) } continue } if (!rep.satisfies(edge)) { canClobber = false break OUTER } } } } if (canClobber) { continue } // ok, we can't replace, but maybe we can nest the current set deeper? let canNestCurrent = true for (const currentPeer of currentPeers) { if (!canNestCurrent) { break } // still possible to nest this peerSet const curDeep = deepestNestingTarget(entryEdge.from, currentPeer.name) if (curDeep === target || target.isDescendantOf(curDeep)) { canNestCurrent = false canReplace = false } if (canNestCurrent) { continue } } } // if we can nest or replace all the current peer groups, we can replace. if (canReplace) { return this.canPlacePeers(REPLACE) } return CONFLICT } checkCanPlaceNoCurrent () { const { target, peerEntryEdge, dep, name } = this // check to see what that name resolves to here, and who may depend on // being able to reach it by crawling up past the parent. we know // that it's not the target's direct child node, and if it was a direct // dep of the target, we would have conflicted earlier. const current = target !== peerEntryEdge.from && target.resolve(name) if (current) { for (const edge of current.edgesIn.values()) { if (edge.from.isDescendantOf(target) && edge.valid) { if (!dep.satisfies(edge)) { return CONFLICT } } } } // no objections, so this is fine as long as peers are ok here. return this.canPlacePeers(OK) } get deepestNestingTarget () { const start = this.parent ? this.parent.deepestNestingTarget : this.edge.from return deepestNestingTarget(start, this.name) } get conflictChildren () { return this.allChildren.filter(c => c.canPlace === CONFLICT) } get allChildren () { const set = new Set(this.children) for (const child of set) { for (const grandchild of child.children) { set.add(grandchild) } } return [...set] } get top () { return this.parent ? this.parent.top : this } // check if peers can go here. returns state or CONFLICT canPlacePeers (state) { this.canPlaceSelf = state if (this._canPlacePeers) { return this._canPlacePeers } // TODO: represent peerPath in ERESOLVE error somehow? const peerPath = [...this.peerPath, this.dep] let sawConflict = false for (const peerEdge of this.dep.edgesOut.values()) { if (!peerEdge.peer || !peerEdge.to || peerPath.includes(peerEdge.to)) { continue } const peer = peerEdge.to // it may be the case that the *initial* dep can be nested, but a peer // of that dep needs to be placed shallower, because the target has // a peer dep on the peer as well. const target = deepestNestingTarget(this.target, peer.name) const cpp = new CanPlaceDep({ dep: peer, target, parent: this, edge: peerEdge, peerPath, // always place peers in preferDedupe mode preferDedupe: true, }) /* istanbul ignore next */ debug(() => { if (this.children.some(c => c.dep === cpp.dep)) { throw new Error('checking same dep repeatedly') } }) this.children.push(cpp) if (cpp.canPlace === CONFLICT) { sawConflict = true } } this._canPlacePeers = sawConflict ? CONFLICT : state return this._canPlacePeers } // what is the node that is causing this peerSet to be placed? get peerSetSource () { return this.parent ? this.parent.peerSetSource : this.edge.from } get peerEntryEdge () { return this.top.edge } static get CONFLICT () { return CONFLICT } static get OK () { return OK } static get REPLACE () { return REPLACE } static get KEEP () { return KEEP } get description () { const { canPlace } = this return canPlace && canPlace.description || /* istanbul ignore next - old node affordance */ canPlace } } module.exports = CanPlaceDep PK ~\SK&K&@npmcli/arborist/lib/diff.jsnu[// a tree representing the difference between two trees // A Diff node's parent is not necessarily the parent of // the node location it refers to, but rather the highest level // node that needs to be either changed or removed. // Thus, the root Diff node is the shallowest change required // for a given branch of the tree being mutated. const { depth } = require('treeverse') const { existsSync } = require('node:fs') const ssri = require('ssri') class Diff { constructor ({ actual, ideal, filterSet, shrinkwrapInflated }) { this.filterSet = filterSet this.shrinkwrapInflated = shrinkwrapInflated this.children = [] this.actual = actual this.ideal = ideal if (this.ideal) { this.resolved = this.ideal.resolved this.integrity = this.ideal.integrity } this.action = getAction(this) this.parent = null // the set of leaf nodes that we rake up to the top level this.leaves = [] // the set of nodes that don't change in this branch of the tree this.unchanged = [] // the set of nodes that will be removed in this branch of the tree this.removed = [] } static calculate ({ actual, ideal, filterNodes = [], shrinkwrapInflated = new Set(), }) { // if there's a filterNode, then: // - get the path from the root to the filterNode. The root or // root.target should have an edge either to the filterNode or // a link to the filterNode. If not, abort. Add the path to the // filterSet. // - Add set of Nodes depended on by the filterNode to filterSet. // - Anything outside of that set should be ignored by getChildren const filterSet = new Set() const extraneous = new Set() for (const filterNode of filterNodes) { const { root } = filterNode if (root !== ideal && root !== actual) { throw new Error('invalid filterNode: outside idealTree/actualTree') } const rootTarget = root.target const edge = [...rootTarget.edgesOut.values()].filter(e => { return e.to && (e.to === filterNode || e.to.target === filterNode) })[0] filterSet.add(root) filterSet.add(rootTarget) filterSet.add(ideal) filterSet.add(actual) if (edge && edge.to) { filterSet.add(edge.to) filterSet.add(edge.to.target) } filterSet.add(filterNode) depth({ tree: filterNode, visit: node => filterSet.add(node), getChildren: node => { node = node.target const loc = node.location const idealNode = ideal.inventory.get(loc) const ideals = !idealNode ? [] : [...idealNode.edgesOut.values()].filter(e => e.to).map(e => e.to) const actualNode = actual.inventory.get(loc) const actuals = !actualNode ? [] : [...actualNode.edgesOut.values()].filter(e => e.to).map(e => e.to) if (actualNode) { for (const child of actualNode.children.values()) { if (child.extraneous) { extraneous.add(child) } } } return ideals.concat(actuals) }, }) } for (const extra of extraneous) { filterSet.add(extra) } return depth({ tree: new Diff({ actual, ideal, filterSet, shrinkwrapInflated }), getChildren, leave, }) } } const getAction = ({ actual, ideal }) => { if (!ideal) { return 'REMOVE' } // bundled meta-deps are copied over to the ideal tree when we visit it, // so they'll appear to be missing here. There's no need to handle them // in the diff, though, because they'll be replaced at reify time anyway // Otherwise, add the missing node. if (!actual) { return ideal.inDepBundle ? null : 'ADD' } // always ignore the root node if (ideal.isRoot && actual.isRoot) { return null } // if the versions don't match, it's a change no matter what if (ideal.version !== actual.version) { return 'CHANGE' } const binsExist = ideal.binPaths.every((path) => existsSync(path)) // top nodes, links, and git deps won't have integrity, but do have resolved // if neither node has integrity, the bins exist, and either (a) neither // node has a resolved value or (b) they both do and match, then we can // leave this one alone since we already know the versions match due to // the condition above. The "neither has resolved" case (a) cannot be // treated as a 'mark CHANGE and refetch', because shrinkwraps, bundles, // and link deps may lack this information, and we don't want to try to // go to the registry for something that isn't there. const noIntegrity = !ideal.integrity && !actual.integrity const noResolved = !ideal.resolved && !actual.resolved const resolvedMatch = ideal.resolved && ideal.resolved === actual.resolved if (noIntegrity && binsExist && (resolvedMatch || noResolved)) { return null } // otherwise, verify that it's the same bits // note that if ideal has integrity, and resolved doesn't, we treat // that as a 'change', so that it gets re-fetched and locked down. const integrityMismatch = !ideal.integrity || !actual.integrity || !ssri.parse(ideal.integrity).match(actual.integrity) if (integrityMismatch || !binsExist) { return 'CHANGE' } return null } const allChildren = node => { if (!node) { return new Map() } // if the node is root, and also a link, then what we really // want is to traverse the target's children if (node.isRoot && node.isLink) { return allChildren(node.target) } const kids = new Map() for (const n of [node, ...node.fsChildren]) { for (const kid of n.children.values()) { kids.set(kid.path, kid) } } return kids } // functions for the walk options when we traverse the trees // to create the diff tree const getChildren = diff => { const children = [] const { actual, ideal, unchanged, removed, filterSet, shrinkwrapInflated, } = diff // Note: we DON'T diff fsChildren themselves, because they are either // included in the package contents, or part of some other project, and // will never appear in legacy shrinkwraps anyway. but we _do_ include the // child nodes of fsChildren, because those are nodes that we are typically // responsible for installing. const actualKids = allChildren(actual) const idealKids = allChildren(ideal) if (ideal && ideal.hasShrinkwrap && !shrinkwrapInflated.has(ideal)) { // Guaranteed to get a diff.leaves here, because we always // be called with a proper Diff object when ideal has a shrinkwrap // that has not been inflated. diff.leaves.push(diff) return children } const paths = new Set([...actualKids.keys(), ...idealKids.keys()]) for (const path of paths) { const actual = actualKids.get(path) const ideal = idealKids.get(path) diffNode({ actual, ideal, children, unchanged, removed, filterSet, shrinkwrapInflated, }) } if (diff.leaves && !children.length) { diff.leaves.push(diff) } return children } const diffNode = ({ actual, ideal, children, unchanged, removed, filterSet, shrinkwrapInflated, }) => { if (filterSet.size && !(filterSet.has(ideal) || filterSet.has(actual))) { return } const action = getAction({ actual, ideal }) // if it's a match, then get its children // otherwise, this is the child diff node if (action || (!shrinkwrapInflated.has(ideal) && ideal.hasShrinkwrap)) { if (action === 'REMOVE') { removed.push(actual) } children.push(new Diff({ actual, ideal, filterSet, shrinkwrapInflated })) } else { unchanged.push(ideal) // !*! Weird dirty hack warning !*! // // Bundled deps aren't loaded in the ideal tree, because we don't know // what they are going to be without unpacking. Swap them over now if // the bundling node isn't changing, so we don't prune them later. // // It's a little bit dirty to be doing this here, since it means that // diffing trees can mutate them, but otherwise we have to walk over // all unchanging bundlers and correct the diff later, so it's more // efficient to just fix it while we're passing through already. // // Note that moving over a bundled dep will break the links to other // deps under this parent, which may have been transitively bundled. // Breaking those links means that we'll no longer see the transitive // dependency, meaning that it won't appear as bundled any longer! // In order to not end up dropping transitively bundled deps, we have // to get the list of nodes to move, then move them all at once, rather // than moving them one at a time in the first loop. const bd = ideal.package.bundleDependencies if (actual && bd && bd.length) { const bundledChildren = [] for (const node of actual.children.values()) { if (node.inBundle) { bundledChildren.push(node) } } for (const node of bundledChildren) { node.parent = ideal } } children.push(...getChildren({ actual, ideal, unchanged, removed, filterSet, shrinkwrapInflated, })) } } // set the parentage in the leave step so that we aren't attaching // child nodes only to remove them later. also bubble up the unchanged // nodes so that we can move them out of staging in the reification step. const leave = (diff, children) => { children.forEach(kid => { kid.parent = diff diff.leaves.push(...kid.leaves) diff.unchanged.push(...kid.unchanged) diff.removed.push(...kid.removed) }) diff.children = children return diff } module.exports = Diff PK ~\RF'@npmcli/arborist/lib/signal-handling.jsnu[const signals = require('./signals.js') // for testing, expose the process being used module.exports = Object.assign(fn => setup(fn), { process }) // do all of this in a setup function so that we can call it // multiple times for multiple reifies that might be going on. // Otherwise, Arborist.reify() is a global action, which is a // new constraint we'd be adding with this behavior. const setup = fn => { const { process } = module.exports const sigListeners = { loaded: false } const unload = () => { if (!sigListeners.loaded) { return } for (const sig of signals) { try { process.removeListener(sig, sigListeners[sig]) } catch { // ignore errors } } process.removeListener('beforeExit', onBeforeExit) sigListeners.loaded = false } const onBeforeExit = () => { // this trick ensures that we exit with the same signal we caught // Ie, if you press ^C and npm gets a SIGINT, we'll do the rollback // and then exit with a SIGINT signal once we've removed the handler. // The timeout is there because signals are asynchronous, so we need // the process to NOT exit on its own, which means we have to have // something keeping the event loop looping. Hence this hack. unload() process.kill(process.pid, signalReceived) setTimeout(() => {}, 500) } let signalReceived = null const listener = (sig, fn) => () => { signalReceived = sig // if we exit normally, but caught a signal which would have been fatal, // then re-send it once we're done with whatever cleanup we have to do. unload() if (process.listeners(sig).length < 1) { process.once('beforeExit', onBeforeExit) } fn({ signal: sig }) } // do the actual loading here for (const sig of signals) { sigListeners[sig] = listener(sig, fn) const max = process.getMaxListeners() try { // if we call this a bunch of times, avoid triggering the warning const { length } = process.listeners(sig) if (length >= max) { process.setMaxListeners(length + 1) } process.on(sig, sigListeners[sig]) } catch { // ignore errors } } sigListeners.loaded = true return unload } PK ~\~ll@npmcli/arborist/bin/virtual.jsnu[const Arborist = require('../') const printTree = require('./lib/print-tree.js') module.exports = (options, time) => new Arborist(options) .loadVirtual() .then(time) .then(async ({ timing, result: tree }) => { printTree(tree) if (options.save) { await tree.meta.save() } return `read ${tree.inventory.size} deps in ${timing.ms}` }) PK ~\t#@npmcli/arborist/bin/lib/logging.jsnu[const { log } = require('proc-log') const fs = require('node:fs') const { dirname } = require('node:path') const os = require('node:os') const { inspect, format } = require('node:util') const { bin: options } = require('./options.js') // add a meta method to proc-log for passing optional // metadata through to log handlers const META = Symbol('meta') const parseArgs = (...args) => { const { [META]: isMeta } = args[args.length - 1] || {} return isMeta ? [args[args.length - 1], ...args.slice(0, args.length - 1)] : [{}, ...args] } log.meta = (meta = {}) => ({ [META]: true, ...meta }) const levels = new Map([ 'silly', 'verbose', 'info', 'http', 'notice', 'warn', 'error', 'silent', ].map((level, index) => [level, index])) const addLogListener = (write, { eol = os.EOL, loglevel = 'silly', colors = false } = {}) => { const levelIndex = levels.get(loglevel) const magenta = m => colors ? `\x1B[35m${m}\x1B[39m` : m const dim = m => colors ? `\x1B[2m${m}\x1B[22m` : m const red = m => colors ? `\x1B[31m${m}\x1B[39m` : m const formatter = (level, ...args) => { const depth = level === 'error' && args[0] && args[0].code === 'ERESOLVE' ? Infinity : 10 if (level === 'info' && args[0] === 'timeEnd') { args[1] = dim(args[1]) } else if (level === 'error' && args[0] === 'timeError') { args[1] = red(args[1]) } const messages = args.map(a => typeof a === 'string' ? a : inspect(a, { depth, colors })) const pref = `${process.pid} ${magenta(level)} ` return pref + format(...messages).trim().split('\n').join(`${eol}${pref}`) + eol } process.on('log', (...args) => { const [meta, level, ...logArgs] = parseArgs(...args) if (levelIndex <= levels.get(level) || meta.force) { write(formatter(level, ...logArgs)) } }) } if (options.loglevel !== 'silent') { addLogListener((v) => process.stderr.write(v), { eol: '\n', colors: options.colors, loglevel: options.loglevel, }) } if (options.logfile) { log.silly('logfile', options.logfile) fs.mkdirSync(dirname(options.logfile), { recursive: true }) const fd = fs.openSync(options.logfile, 'a') addLogListener((str) => fs.writeSync(fd, str)) } module.exports = log PK ~\{ʝ&@npmcli/arborist/bin/lib/print-tree.jsnu[const { inspect } = require('node:util') const log = require('./logging.js') module.exports = tree => log.info(inspect(tree.toJSON(), { depth: Infinity })) PK ~\="@npmcli/arborist/bin/lib/timers.jsnu[const { bin: options } = require('./options.js') const log = require('./logging.js') const timers = new Map() const finished = new Map() process.on('time', (level, name) => { if (level === 'start') { if (timers.has(name)) { throw new Error('conflicting timer! ' + name) } timers.set(name, process.hrtime.bigint()) } else if (level === 'end') { if (!timers.has(name)) { throw new Error('timer not started! ' + name) } const elapsed = Number(process.hrtime.bigint() - timers.get(name)) timers.delete(name) finished.set(name, elapsed) if (options.timing) { log.info('timeEnd', `${name} ${elapsed / 1e9}s`, log.meta({ force: options.timing === 'always' })) } } }) process.on('exit', () => { for (const name of timers.keys()) { log.error('timeError', 'Dangling timer:', name) process.exitCode = 1 } }) module.exports = finished PK ~\ _ #@npmcli/arborist/bin/lib/options.jsnu[const nopt = require('nopt') const path = require('node:path') const has = (o, k) => Object.prototype.hasOwnProperty.call(o, k) const cleanPath = (val) => { const k = Symbol('key') const data = {} nopt.typeDefs.path.validate(data, k, val) return data[k] } const parse = (...noptArgs) => { const binOnlyOpts = { command: String, loglevel: String, colors: Boolean, timing: ['always', Boolean], logfile: String, } const arbOpts = { add: Array, rm: Array, omit: Array, update: Array, workspaces: Array, global: Boolean, force: Boolean, 'global-style': Boolean, 'prefer-dedupe': Boolean, 'legacy-peer-deps': Boolean, 'update-all': Boolean, before: Date, path: path, cache: path, ...binOnlyOpts, } const short = { quiet: ['--loglevel', 'warn'], logs: ['--logfile', 'true'], w: '--workspaces', g: '--global', f: '--force', } const defaults = { // key order is important for command and path // since they shift positional args // command is 1st, path is 2nd command: (o) => o.argv.remain.shift(), path: (o) => cleanPath(o.argv.remain.shift() || '.'), colors: has(process.env, 'NO_COLOR') ? false : !!process.stderr.isTTY, loglevel: 'silly', timing: (o) => o.loglevel === 'silly', cache: `${process.env.HOME}/.npm/_cacache`, } const derived = [ // making update either `all` or an array of names but not both ({ updateAll: all, update: names, ...o }) => { if (all || names) { o.update = all != null ? { all } : { names } } return o }, ({ logfile, ...o }) => { // logfile is parsed as a string so if its true or set but empty // then set the default logfile if (logfile === 'true' || logfile === '') { logfile = `arb-log-${new Date().toISOString().replace(/[.:]/g, '_')}.log` } // then parse it the same as nopt parses other paths if (logfile) { o.logfile = cleanPath(logfile) } return o }, ] const transforms = [ // Camelcase all top level keys (o) => { const entries = Object.entries(o).map(([k, v]) => [ k.replace(/-./g, s => s[1].toUpperCase()), v, ]) return Object.fromEntries(entries) }, // Set defaults on unset keys (o) => { for (const [k, v] of Object.entries(defaults)) { if (!has(o, k)) { o[k] = typeof v === 'function' ? v(o) : v } } return o }, // Set/unset derived values ...derived.map((derive) => (o) => derive(o) || o), // Separate bin and arborist options ({ argv: { remain: _ }, ...o }) => { const bin = { _ } for (const k of Object.keys(binOnlyOpts)) { if (has(o, k)) { bin[k] = o[k] delete o[k] } } return { bin, arb: o } }, ] let options = nopt(arbOpts, short, ...noptArgs) for (const t of transforms) { options = t(options) } return options } module.exports = parse() PK ~\|[vv@npmcli/arborist/bin/funding.jsnu[const Arborist = require('../') const log = require('./lib/logging.js') module.exports = (options, time) => { const query = options._.shift() const a = new Arborist(options) return a .loadVirtual() .then(tree => { // only load the actual tree if the virtual one doesn't have modern metadata if (!tree.meta || !(tree.meta.originalLockfileVersion >= 2)) { log.error('old metadata, load actual') throw 'load actual' } else { log.error('meta ok, return virtual tree') return tree } }) .catch(() => a.loadActual()) .then(time) .then(({ timing, result: tree }) => { if (!query) { for (const node of tree.inventory.values()) { if (node.package.funding) { log.info(node.name, node.location, node.package.funding) } } } else { for (const node of tree.inventory.query('name', query)) { if (node.package.funding) { log.info(node.name, node.location, node.package.funding) } } } return `read ${tree.inventory.size} deps in ${timing.ms}` }) } PK ~\no  @npmcli/arborist/bin/index.jsnu[#!/usr/bin/env node const fs = require('node:fs') const path = require('node:path') const { time } = require('proc-log') const { bin, arb: options } = require('./lib/options') const version = require('../package.json').version const usage = (message = '') => `Arborist - the npm tree doctor Version: ${version} ${message && '\n' + message + '\n'} # USAGE arborist [path] [options...] # COMMANDS * reify: reify ideal tree to node_modules (install, update, rm, ...) * prune: prune the ideal tree and reify (like npm prune) * ideal: generate and print the ideal tree * actual: read and print the actual tree in node_modules * virtual: read and print the virtual tree in the local shrinkwrap file * shrinkwrap: load a local shrinkwrap and print its data * audit: perform a security audit on project dependencies * funding: query funding information in the local package tree. A second positional argument after the path name can limit to a package name. * license: query license information in the local package tree. A second positional argument after the path name can limit to a license type. * help: print this text * version: print the version # OPTIONS Most npm options are supported, but in camelCase rather than css-case. For example, instead of '--dry-run', use '--dryRun'. Additionally: * --loglevel=warn|--quiet will supppress the printing of package trees * --logfile will output logs to a file * --timing will show timing information * Instead of 'npm install ', use 'arborist reify --add='. The '--add=' option can be specified multiple times. * Instead of 'npm rm ', use 'arborist reify --rm='. The '--rm=' option can be specified multiple times. * Instead of 'npm update', use 'arborist reify --update-all'. * 'npm audit fix' is 'arborist audit --fix' ` const commands = { version: () => console.log(version), help: () => console.log(usage()), exit: () => { process.exitCode = 1 console.error( usage(`Error: command '${bin.command}' does not exist.`) ) }, } const commandFiles = fs.readdirSync(__dirname).filter((f) => path.extname(f) === '.js' && f !== __filename) for (const file of commandFiles) { const command = require(`./${file}`) const name = path.basename(file, '.js') const totalTime = `bin:${name}:init` const scriptTime = `bin:${name}:script` commands[name] = () => { const timers = require('./lib/timers') const log = require('./lib/logging') log.info(name, options) const timeEnd = time.start(totalTime) const scriptEnd = time.start(scriptTime) return command(options, (result) => { scriptEnd() return { result, timing: { seconds: `${timers.get(scriptTime) / 1e9}s`, ms: `${timers.get(scriptTime) / 1e6}ms`, }, } }) .then((result) => { log.info(result) return result }) .catch((err) => { process.exitCode = 1 log.error(err) return err }) .then((r) => { timeEnd() if (bin.loglevel !== 'silent') { console[process.exitCode ? 'error' : 'log'](r) } return r }) } } if (commands[bin.command]) { commands[bin.command]() } else { commands.exit() } PK ~\w'ww@npmcli/arborist/bin/audit.jsnu[const Arborist = require('../') const printTree = require('./lib/print-tree.js') const log = require('./lib/logging.js') const Vuln = require('../lib/vuln.js') const printReport = report => { for (const vuln of report.values()) { log.info(printVuln(vuln)) } if (report.topVulns.size) { log.info('\n# top-level vulnerabilities') for (const vuln of report.topVulns.values()) { log.info(printVuln(vuln)) } } } const printVuln = vuln => { return { __proto__: { constructor: Vuln }, name: vuln.name, issues: [...vuln.advisories].map(a => printAdvisory(a)), range: vuln.simpleRange, nodes: [...vuln.nodes].map(node => `${node.name} ${node.location || '#ROOT'}`), ...(vuln.topNodes.size === 0 ? {} : { topNodes: [...vuln.topNodes].map(node => `${node.location || '#ROOT'}`), }), } } const printAdvisory = a => `${a.title}${a.url ? ' ' + a.url : ''}` module.exports = (options, time) => { const arb = new Arborist(options) return arb .audit(options) .then(time) .then(async ({ timing, result: tree }) => { if (options.fix) { printTree(tree) } printReport(arb.auditReport) if (tree.meta && options.save) { await tree.meta.save() } return options.fix ? `resolved ${tree.inventory.size} deps in ${timing.seconds}` : `done in ${timing.seconds}` }) } PK ~\4N\N||@npmcli/arborist/bin/prune.jsnu[const Arborist = require('../') const printTree = require('./lib/print-tree.js') const log = require('./lib/logging.js') const printDiff = diff => { const { depth } = require('treeverse') depth({ tree: diff, visit: d => { if (d.location === '') { return } switch (d.action) { case 'REMOVE': log.info('REMOVE', d.actual.location) break case 'ADD': log.info('ADD', d.ideal.location, d.ideal.resolved) break case 'CHANGE': log.info('CHANGE', d.actual.location, { from: d.actual.resolved, to: d.ideal.resolved, }) break } }, getChildren: d => d.children, }) } module.exports = (options, time) => { const arb = new Arborist(options) return arb .prune(options) .then(time) .then(async ({ timing, result: tree }) => { printTree(tree) if (options.dryRun) { printDiff(arb.diff) } if (tree.meta && options.save) { await tree.meta.save() } return `resolved ${tree.inventory.size} deps in ${timing.seconds}` }) } PK ~\n# ||@npmcli/arborist/bin/reify.jsnu[const Arborist = require('../') const printTree = require('./lib/print-tree.js') const log = require('./lib/logging.js') const printDiff = diff => { const { depth } = require('treeverse') depth({ tree: diff, visit: d => { if (d.location === '') { return } switch (d.action) { case 'REMOVE': log.info('REMOVE', d.actual.location) break case 'ADD': log.info('ADD', d.ideal.location, d.ideal.resolved) break case 'CHANGE': log.info('CHANGE', d.actual.location, { from: d.actual.resolved, to: d.ideal.resolved, }) break } }, getChildren: d => d.children, }) } module.exports = (options, time) => { const arb = new Arborist(options) return arb .reify(options) .then(time) .then(async ({ timing, result: tree }) => { printTree(tree) if (options.dryRun) { printDiff(arb.diff) } if (tree.meta && options.save) { await tree.meta.save() } return `resolved ${tree.inventory.size} deps in ${timing.seconds}` }) } PK ~\р@npmcli/arborist/bin/license.jsnu[const localeCompare = require('@isaacs/string-locale-compare')('en') const Arborist = require('../') const log = require('./lib/logging.js') module.exports = (options, time) => { const query = options._.shift() const a = new Arborist(options) return a .loadVirtual() .then(tree => { // only load the actual tree if the virtual one doesn't have modern metadata if (!tree.meta || !(tree.meta.originalLockfileVersion >= 2)) { throw 'load actual' } else { return tree } }).catch((er) => { log.error('loading actual tree', er) return a.loadActual() }) .then(time) .then(({ result: tree }) => { const output = [] if (!query) { const set = [] for (const license of tree.inventory.query('license')) { set.push([tree.inventory.query('license', license).size, license]) } for (const [count, license] of set.sort((a, b) => a[1] && b[1] ? b[0] - a[0] || localeCompare(a[1], b[1]) : a[1] ? -1 : b[1] ? 1 : 0)) { output.push(`${count} ${license}`) log.info(count, license) } } else { for (const node of tree.inventory.query('license', query === 'undefined' ? undefined : query)) { const msg = `${node.name} ${node.location} ${node.package.description || ''}` output.push(msg) log.info(msg) } } return output.join('\n') }) } PK ~\3"@npmcli/arborist/bin/shrinkwrap.jsnu[const Shrinkwrap = require('../lib/shrinkwrap.js') module.exports = (options, time) => Shrinkwrap .load(options) .then((s) => s.commit()) .then(time) .then(({ result: s }) => JSON.stringify(s, 0, 2)) PK ~\K&&@npmcli/arborist/bin/actual.jsnu[const Arborist = require('../') const printTree = require('./lib/print-tree.js') module.exports = (options, time) => new Arborist(options) .loadActual(options) .then(time) .then(async ({ timing, result: tree }) => { printTree(tree) if (options.save) { await tree.meta.save() } if (options.saveHidden) { tree.meta.hiddenLockfile = true tree.meta.filename = options.path + '/node_modules/.package-lock.json' await tree.meta.save() } return `read ${tree.inventory.size} deps in ${timing.ms}` }) PK ~\`6fq@npmcli/arborist/bin/ideal.jsnu[const Arborist = require('../') const printTree = require('./lib/print-tree.js') module.exports = (options, time) => new Arborist(options) .buildIdealTree(options) .then(time) .then(async ({ timing, result: tree }) => { printTree(tree) if (tree.meta && options.save) { await tree.meta.save() } return `resolved ${tree.inventory.size} deps in ${timing.seconds}` }) PK ~\d7EE@npmcli/arborist/README.mdnu[# @npmcli/arborist [![npm version](https://img.shields.io/npm/v/@npmcli/arborist.svg)](https://npm.im/@npmcli/arborist) [![license](https://img.shields.io/npm/l/@npmcli/arborist.svg)](https://npm.im/@npmcli/arborist) [![CI - @npmcli/arborist](https://github.com/npm/cli/actions/workflows/ci-npmcli-arborist.yml/badge.svg)](https://github.com/npm/cli/actions/workflows/ci-npmcli-arborist.yml) Inspect and manage `node_modules` trees. ![a tree with the word ARBORIST superimposed on it](https://raw.githubusercontent.com/npm/arborist/main/docs/logo.svg?sanitize=true) There's more documentation [in the docs folder](https://github.com/npm/cli/tree/latest/workspaces/arborist/docs). ## USAGE ```js const Arborist = require('@npmcli/arborist') const arb = new Arborist({ // options object // where we're doing stuff. defaults to cwd. path: '/path/to/package/root', // url to the default registry. defaults to npm's default registry registry: 'https://registry.npmjs.org', // scopes can be mapped to a different registry '@foo:registry': 'https://registry.foo.com/', // Auth can be provided in a couple of different ways. If none are // provided, then requests are anonymous, and private packages will 404. // Arborist doesn't do anything with these, it just passes them down // the chain to pacote and npm-registry-fetch. // Safest: a bearer token provided by a registry: // 1. an npm auth token, used with the default registry token: 'deadbeefcafebad', // 2. an alias for the same thing: _authToken: 'deadbeefcafebad', // insecure options: // 3. basic auth, username:password, base64 encoded auth: 'aXNhYWNzOm5vdCBteSByZWFsIHBhc3N3b3Jk', // 4. username and base64 encoded password username: 'isaacs', password: 'bm90IG15IHJlYWwgcGFzc3dvcmQ=', // auth configs can also be scoped to a given registry with this // rather unusual pattern: '//registry.foo.com:token': 'blahblahblah', '//basic.auth.only.foo.com:_auth': 'aXNhYWNzOm5vdCBteSByZWFsIHBhc3N3b3Jk', '//registry.foo.com:always-auth': true, }) // READING // returns a promise. reads the actual contents of node_modules arb.loadActual().then(tree => { // tree is also stored at arb.virtualTree }) // read just what the package-lock.json/npm-shrinkwrap says // This *also* loads the yarn.lock file, but that's only relevant // when building the ideal tree. arb.loadVirtual().then(tree => { // tree is also stored at arb.virtualTree // now arb.virtualTree is loaded // this fails if there's no package-lock.json or package.json in the folder // note that loading this way should only be done if there's no // node_modules folder }) // OPTIMIZING AND DESIGNING // build an ideal tree from the package.json and various lockfiles. arb.buildIdealTree(options).then(() => { // next step is to reify that ideal tree onto disk. // options can be: // rm: array of package names to remove at top level // add: Array of package specifiers to add at the top level. Each of // these will be resolved with pacote.manifest if the name can't be // determined from the spec. (Eg, `github:foo/bar` vs `foo@somespec`.) // The dep will be saved in the location where it already exists, // (or pkg.dependencies) unless a different saveType is specified. // saveType: Save added packages in a specific dependency set. // - null (default) Wherever they exist already, or 'dependencies' // - prod: definitely in 'dependencies' // - optional: in 'optionalDependencies' // - dev: devDependencies // - peer: save in peerDependencies, and remove any optional flag from // peerDependenciesMeta if one exists // - peerOptional: save in peerDependencies, and add a // peerDepsMeta[name].optional flag // saveBundle: add newly added deps to the bundleDependencies list // update: Either `true` to just go ahead and update everything, or an // object with any or all of the following fields: // - all: boolean. set to true to just update everything // - names: names of packages update (like `npm update foo`) // prune: boolean, default true. Prune extraneous nodes from the tree. // preferDedupe: prefer to deduplicate packages if possible, rather than // choosing a newer version of a dependency. Defaults to false, ie, // always try to get the latest and greatest deps. // legacyBundling: Nest every dep under the node requiring it, npm v2 style. // No unnecessary deduplication. Default false. // At the end of this process, arb.idealTree is set. }) // WRITING // Make the idealTree be the thing that's on disk arb.reify({ // write the lockfile(s) back to disk, and package.json with any updates // defaults to 'true' save: true, }).then(() => { // node modules has been written to match the idealTree }) ``` ## DATA STRUCTURES A `node_modules` tree is a logical graph of dependencies overlaid on a physical tree of folders. A `Node` represents a package folder on disk, either at the root of the package, or within a `node_modules` folder. The physical structure of the folder tree is represented by the `node.parent` reference to the containing folder, and `node.children` map of nodes within its `node_modules` folder, where the key in the map is the name of the folder in `node_modules`, and the value is the child node. A node without a parent is a top of tree. A `Link` represents a symbolic link to a package on disk. This can be a symbolic link to a package folder within the current tree, or elsewhere on disk. The `link.target` is a reference to the actual node. Links differ from Nodes in that dependencies are resolved from the _target_ location, rather than from the link location. An `Edge` represents a dependency relationship. Each node has an `edgesIn` set, and an `edgesOut` map. Each edge has a `type` which specifies what kind of dependency it represents: `'prod'` for regular dependencies, `'peer'` for peerDependencies, `'dev'` for devDependencies, and `'optional'` for optionalDependencies. `edge.from` is a reference to the node that has the dependency, and `edge.to` is a reference to the node that requires the dependency. As nodes are moved around in the tree, the graph edges are automatically updated to point at the new module resolution targets. In other words, `edge.from`, `edge.name`, and `edge.spec` are immutable; `edge.to` is updated automatically when a node's parent changes. ### class Node All arborist trees are `Node` objects. A `Node` refers to a package folder, which may have children in `node_modules`. * `node.name` The name of this node's folder in `node_modules`. * `node.parent` Physical parent node in the tree. The package in whose `node_modules` folder this package lives. Null if node is top of tree. Setting `node.parent` will automatically update `node.location` and all graph edges affected by the move. * `node.meta` A `Shrinkwrap` object which looks up `resolved` and `integrity` values for all modules in this tree. Only relevant on `root` nodes. * `node.children` Map of packages located in the node's `node_modules` folder. * `node.package` The contents of this node's `package.json` file. * `node.path` File path to this package. If the node is a link, then this is the path to the link, not to the link target. If the node is _not_ a link, then this matches `node.realpath`. * `node.realpath` The full real filepath on disk where this node lives. * `node.location` A slash-normalized relative path from the root node to this node's path. * `node.isLink` Whether this represents a symlink. Always `false` for Node objects, always `true` for Link objects. * `node.isRoot` True if this node is a root node. (Ie, if `node.root === node`.) * `node.root` The root node where we are working. If not assigned to some other value, resolves to the node itself. (Ie, the root node's `root` property refers to itself.) * `node.isTop` True if this node is the top of its tree (ie, has no `parent`, false otherwise). * `node.top` The top node in this node's tree. This will be equal to `node.root` for simple trees, but link targets will frequently be outside of (or nested somewhere within) a `node_modules` hierarchy, and so will have a different `top`. * `node.dev`, `node.optional`, `node.devOptional`, `node.peer`, Indicators as to whether this node is a dev, optional, and/or peer dependency. These flags are relevant when pruning dependencies out of the tree or deciding what to reify. See **Package Dependency Flags** below for explanations. * `node.edgesOut` Edges in the dependency graph indicating nodes that this node depends on, which resolve its dependencies. * `node.edgesIn` Edges in the dependency graph indicating nodes that depend on this node. * `extraneous` True if this package is not required by any other for any reason. False for top of tree. * `node.resolve(name)` Identify the node that will be returned when code in this package runs `require(name)` * `node.errors` Array of errors encountered while parsing package.json or version specifiers. ### class Link Link objects represent a symbolic link within the `node_modules` folder. They have most of the same properties and methods as `Node` objects, with a few differences. * `link.target` A Node object representing the package that the link references. If this is a Node already present within the tree, then it will be the same object. If it's outside of the tree, then it will be treated as the top of its own tree. * `link.isLink` Always true. * `link.children` This is always an empty map, since links don't have their own children directly. ### class Edge Edge objects represent a dependency relationship a package node to the point in the tree where the dependency will be loaded. As nodes are moved within the tree, Edges automatically update to point to the appropriate location. * `new Edge({ from, type, name, spec })` Creates a new edge with the specified fields. After instantiation, none of the fields can be changed directly. * `edge.from` The node that has the dependency. * `edge.type` The type of dependency. One of `'prod'`, `'dev'`, `'peer'`, or `'optional'`. * `edge.name` The name of the dependency. Ie, the key in the relevant `package.json` dependencies object. * `edge.spec` The specifier that is required. This can be a version, range, tag name, git url, or tarball URL. Any specifier allowed by npm is supported. * `edge.to` Automatically set to the node in the tree that matches the `name` field. * `edge.valid` True if `edge.to` satisfies the specifier. * `edge.error` A string indicating the type of error if there is a problem, or `null` if it's valid. Values, in order of precedence: * `DETACHED` Indicates that the edge has been detached from its `edge.from` node, typically because a new edge was created when a dependency specifier was modified. * `MISSING` Indicates that the dependency is unmet. Note that this is _not_ set for unmet dependencies of the `optional` type. * `PEER LOCAL` Indicates that a `peerDependency` is found in the node's local `node_modules` folder, and the node is not the top of the tree. This violates the `peerDependency` contract, because it means that the dependency is not a peer. * `INVALID` Indicates that the dependency does not satisfy `edge.spec`. * `edge.reload()` Re-resolve to find the appropriate value for `edge.to`. Called automatically from the `Node` class when the tree is mutated. ### Package Dependency Flags The dependency type of a node can be determined efficiently by looking at the `dev`, `optional`, and `devOptional` flags on the node object. These are updated by arborist when necessary whenever the tree is modified in such a way that the dependency graph can change, and are relevant when pruning nodes from the tree. ``` | extraneous | peer | dev | optional | devOptional | meaning | prune? | |------------+------+-----+----------+-------------+---------------------+-------------------| | | | | | | production dep | never | |------------+------+-----+----------+-------------+---------------------+-------------------| | X | N/A | N/A | N/A | N/A | nothing depends on | always | | | | | | | this, it is trash | | |------------+------+-----+----------+-------------+---------------------+-------------------| | | | X | | X | devDependency, or | if pruning dev | | | | | | not in lock | only depended upon | | | | | | | | by devDependencies | | |------------+------+-----+----------+-------------+---------------------+-------------------| | | | | X | X | optionalDependency, | if pruning | | | | | | not in lock | or only depended on | optional | | | | | | | by optionalDeps | | |------------+------+-----+----------+-------------+---------------------+-------------------| | | | X | X | X | Optional dependency | if pruning EITHER | | | | | | not in lock | of dep(s) in the | dev OR optional | | | | | | | dev hierarchy | | |------------+------+-----+----------+-------------+---------------------+-------------------| | | | | | X | BOTH a non-optional | if pruning BOTH | | | | | | in lock | dep within the dev | dev AND optional | | | | | | | hierarchy, AND a | | | | | | | | dep within the | | | | | | | | optional hierarchy | | |------------+------+-----+----------+-------------+---------------------+-------------------| | | X | | | | peer dependency, or | if pruning peers | | | | | | | only depended on by | | | | | | | | peer dependencies | | |------------+------+-----+----------+-------------+---------------------+-------------------| | | X | X | | X | peer dependency of | if pruning peer | | | | | | not in lock | dev node hierarchy | OR dev deps | |------------+------+-----+----------+-------------+---------------------+-------------------| | | X | | X | X | peer dependency of | if pruning peer | | | | | | not in lock | optional nodes, or | OR optional deps | | | | | | | peerOptional dep | | |------------+------+-----+----------+-------------+---------------------+-------------------| | | X | X | X | X | peer optional deps | if pruning peer | | | | | | not in lock | of the dev dep | OR optional OR | | | | | | | hierarchy | dev | |------------+------+-----+----------+-------------+---------------------+-------------------| | | X | | | X | BOTH a non-optional | if pruning peers | | | | | | in lock | peer dep within the | OR: | | | | | | | dev hierarchy, AND | BOTH optional | | | | | | | a peer optional dep | AND dev deps | +------------+------+-----+----------+-------------+---------------------+-------------------+ ``` * If none of these flags are set, then the node is required by the dependency and/or peerDependency hierarchy. It should not be pruned. * If _both_ `node.dev` and `node.optional` are set, then the node is an optional dependency of one of the packages in the devDependency hierarchy. It should be pruned if _either_ dev or optional deps are being removed. * If `node.dev` is set, but `node.optional` is not, then the node is required in the devDependency hierarchy. It should be pruned if dev dependencies are being removed. * If `node.optional` is set, but `node.dev` is not, then the node is required in the optionalDependency hierarchy. It should be pruned if optional dependencies are being removed. * If `node.devOptional` is set, then the node is a (non-optional) dependency within the devDependency hierarchy, _and_ a dependency within the `optionalDependency` hierarchy. It should be pruned if _both_ dev and optional dependencies are being removed. * If `node.peer` is set, then all the same semantics apply as above, except that the dep is brought in by a peer dep at some point, rather than a normal non-peer dependency. Note: `devOptional` is only set in the shrinkwrap/package-lock file if _neither_ `dev` nor `optional` are set, as it would be redundant. ## BIN Arborist ships with a cli that can be used to run arborist specific commands outside of the context of the npm CLI. This script is currently not part of the public API and is subject to breaking changes outside of major version bumps. To see the usage run: ``` npx @npmcli/arborist --help ``` PK ~\r@npmcli/arborist/LICENSE.mdnu[ ISC License Copyright npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND NPM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NPM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\Q~ﮝ@npmcli/agent/package.jsonnu[{ "_id": "@npmcli/agent@2.2.2", "_inBundle": true, "_location": "/npm/@npmcli/agent", "_phantomChildren": {}, "_requiredBy": [ "/npm/make-fetch-happen" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/agent/issues" }, "dependencies": { "agent-base": "^7.1.0", "http-proxy-agent": "^7.0.0", "https-proxy-agent": "^7.0.1", "lru-cache": "^10.0.1", "socks-proxy-agent": "^8.0.3" }, "description": "the http/https agent used by the npm cli", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.21.3", "minipass-fetch": "^3.0.3", "nock": "^13.2.7", "semver": "^7.5.4", "simple-socks": "^3.1.0", "tap": "^16.3.0" }, "engines": { "node": "^16.14.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/agent#readme", "license": "ISC", "main": "lib/index.js", "name": "@npmcli/agent", "repository": { "type": "git", "url": "git+https://github.com/npm/agent.git" }, "scripts": { "gencerts": "bash scripts/create-cert.sh", "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.21.3", "publish": "true" }, "version": "2.2.2" } PK ~\c@npmcli/agent/lib/proxy.jsnu['use strict' const { HttpProxyAgent } = require('http-proxy-agent') const { HttpsProxyAgent } = require('https-proxy-agent') const { SocksProxyAgent } = require('socks-proxy-agent') const { LRUCache } = require('lru-cache') const { InvalidProxyProtocolError } = require('./errors.js') const PROXY_CACHE = new LRUCache({ max: 20 }) const SOCKS_PROTOCOLS = new Set(SocksProxyAgent.protocols) const PROXY_ENV_KEYS = new Set(['https_proxy', 'http_proxy', 'proxy', 'no_proxy']) const PROXY_ENV = Object.entries(process.env).reduce((acc, [key, value]) => { key = key.toLowerCase() if (PROXY_ENV_KEYS.has(key)) { acc[key] = value } return acc }, {}) const getProxyAgent = (url) => { url = new URL(url) const protocol = url.protocol.slice(0, -1) if (SOCKS_PROTOCOLS.has(protocol)) { return SocksProxyAgent } if (protocol === 'https' || protocol === 'http') { return [HttpProxyAgent, HttpsProxyAgent] } throw new InvalidProxyProtocolError(url) } const isNoProxy = (url, noProxy) => { if (typeof noProxy === 'string') { noProxy = noProxy.split(',').map((p) => p.trim()).filter(Boolean) } if (!noProxy || !noProxy.length) { return false } const hostSegments = url.hostname.split('.').reverse() return noProxy.some((no) => { const noSegments = no.split('.').filter(Boolean).reverse() if (!noSegments.length) { return false } for (let i = 0; i < noSegments.length; i++) { if (hostSegments[i] !== noSegments[i]) { return false } } return true }) } const getProxy = (url, { proxy, noProxy }) => { url = new URL(url) if (!proxy) { proxy = url.protocol === 'https:' ? PROXY_ENV.https_proxy : PROXY_ENV.https_proxy || PROXY_ENV.http_proxy || PROXY_ENV.proxy } if (!noProxy) { noProxy = PROXY_ENV.no_proxy } if (!proxy || isNoProxy(url, noProxy)) { return null } return new URL(proxy) } module.exports = { getProxyAgent, getProxy, proxyCache: PROXY_CACHE, } PK ~\0**@npmcli/agent/lib/agents.jsnu['use strict' const net = require('net') const tls = require('tls') const { once } = require('events') const timers = require('timers/promises') const { normalizeOptions, cacheOptions } = require('./options') const { getProxy, getProxyAgent, proxyCache } = require('./proxy.js') const Errors = require('./errors.js') const { Agent: AgentBase } = require('agent-base') module.exports = class Agent extends AgentBase { #options #timeouts #proxy #noProxy #ProxyAgent constructor (options = {}) { const { timeouts, proxy, noProxy, ...normalizedOptions } = normalizeOptions(options) super(normalizedOptions) this.#options = normalizedOptions this.#timeouts = timeouts if (proxy) { this.#proxy = new URL(proxy) this.#noProxy = noProxy this.#ProxyAgent = getProxyAgent(proxy) } } get proxy () { return this.#proxy ? { url: this.#proxy } : {} } #getProxy (options) { if (!this.#proxy) { return } const proxy = getProxy(`${options.protocol}//${options.host}:${options.port}`, { proxy: this.#proxy, noProxy: this.#noProxy, }) if (!proxy) { return } const cacheKey = cacheOptions({ ...options, ...this.#options, timeouts: this.#timeouts, proxy, }) if (proxyCache.has(cacheKey)) { return proxyCache.get(cacheKey) } let ProxyAgent = this.#ProxyAgent if (Array.isArray(ProxyAgent)) { ProxyAgent = this.isSecureEndpoint(options) ? ProxyAgent[1] : ProxyAgent[0] } const proxyAgent = new ProxyAgent(proxy, { ...this.#options, socketOptions: { family: this.#options.family }, }) proxyCache.set(cacheKey, proxyAgent) return proxyAgent } // takes an array of promises and races them against the connection timeout // which will throw the necessary error if it is hit. This will return the // result of the promise race. async #timeoutConnection ({ promises, options, timeout }, ac = new AbortController()) { if (timeout) { const connectionTimeout = timers.setTimeout(timeout, null, { signal: ac.signal }) .then(() => { throw new Errors.ConnectionTimeoutError(`${options.host}:${options.port}`) }).catch((err) => { if (err.name === 'AbortError') { return } throw err }) promises.push(connectionTimeout) } let result try { result = await Promise.race(promises) ac.abort() } catch (err) { ac.abort() throw err } return result } async connect (request, options) { // if the connection does not have its own lookup function // set, then use the one from our options options.lookup ??= this.#options.lookup let socket let timeout = this.#timeouts.connection const isSecureEndpoint = this.isSecureEndpoint(options) const proxy = this.#getProxy(options) if (proxy) { // some of the proxies will wait for the socket to fully connect before // returning so we have to await this while also racing it against the // connection timeout. const start = Date.now() socket = await this.#timeoutConnection({ options, timeout, promises: [proxy.connect(request, options)], }) // see how much time proxy.connect took and subtract it from // the timeout if (timeout) { timeout = timeout - (Date.now() - start) } } else { socket = (isSecureEndpoint ? tls : net).connect(options) } socket.setKeepAlive(this.keepAlive, this.keepAliveMsecs) socket.setNoDelay(this.keepAlive) const abortController = new AbortController() const { signal } = abortController const connectPromise = socket[isSecureEndpoint ? 'secureConnecting' : 'connecting'] ? once(socket, isSecureEndpoint ? 'secureConnect' : 'connect', { signal }) : Promise.resolve() await this.#timeoutConnection({ options, timeout, promises: [ connectPromise, once(socket, 'error', { signal }).then((err) => { throw err[0] }), ], }, abortController) if (this.#timeouts.idle) { socket.setTimeout(this.#timeouts.idle, () => { socket.destroy(new Errors.IdleTimeoutError(`${options.host}:${options.port}`)) }) } return socket } addRequest (request, options) { const proxy = this.#getProxy(options) // it would be better to call proxy.addRequest here but this causes the // http-proxy-agent to call its super.addRequest which causes the request // to be added to the agent twice. since we only support 3 agents // currently (see the required agents in proxy.js) we have manually // checked that the only public methods we need to call are called in the // next block. this could change in the future and presumably we would get // failing tests until we have properly called the necessary methods on // each of our proxy agents if (proxy?.setRequestProps) { proxy.setRequestProps(request, options) } request.setHeader('connection', this.keepAlive ? 'keep-alive' : 'close') if (this.#timeouts.response) { let responseTimeout request.once('finish', () => { setTimeout(() => { request.destroy(new Errors.ResponseTimeoutError(request, this.#proxy)) }, this.#timeouts.response) }) request.once('response', () => { clearTimeout(responseTimeout) }) } if (this.#timeouts.transfer) { let transferTimeout request.once('response', (res) => { setTimeout(() => { res.destroy(new Errors.TransferTimeoutError(request, this.#proxy)) }, this.#timeouts.transfer) res.once('close', () => { clearTimeout(transferTimeout) }) }) } return super.addRequest(request, options) } } PK ~\X@npmcli/agent/lib/dns.jsnu['use strict' const { LRUCache } = require('lru-cache') const dns = require('dns') // this is a factory so that each request can have its own opts (i.e. ttl) // while still sharing the cache across all requests const cache = new LRUCache({ max: 50 }) const getOptions = ({ family = 0, hints = dns.ADDRCONFIG, all = false, verbatim = undefined, ttl = 5 * 60 * 1000, lookup = dns.lookup, }) => ({ // hints and lookup are returned since both are top level properties to (net|tls).connect hints, lookup: (hostname, ...args) => { const callback = args.pop() // callback is always last arg const lookupOptions = args[0] ?? {} const options = { family, hints, all, verbatim, ...(typeof lookupOptions === 'number' ? { family: lookupOptions } : lookupOptions), } const key = JSON.stringify({ hostname, ...options }) if (cache.has(key)) { const cached = cache.get(key) return process.nextTick(callback, null, ...cached) } lookup(hostname, options, (err, ...result) => { if (err) { return callback(err) } cache.set(key, result, { ttl }) return callback(null, ...result) }) }, }) module.exports = { cache, getOptions, } PK ~\7e@npmcli/agent/lib/index.jsnu['use strict' const { LRUCache } = require('lru-cache') const { normalizeOptions, cacheOptions } = require('./options') const { getProxy, proxyCache } = require('./proxy.js') const dns = require('./dns.js') const Agent = require('./agents.js') const agentCache = new LRUCache({ max: 20 }) const getAgent = (url, { agent, proxy, noProxy, ...options } = {}) => { // false has meaning so this can't be a simple truthiness check if (agent != null) { return agent } url = new URL(url) const proxyForUrl = getProxy(url, { proxy, noProxy }) const normalizedOptions = { ...normalizeOptions(options), proxy: proxyForUrl, } const cacheKey = cacheOptions({ ...normalizedOptions, secureEndpoint: url.protocol === 'https:', }) if (agentCache.has(cacheKey)) { return agentCache.get(cacheKey) } const newAgent = new Agent(normalizedOptions) agentCache.set(cacheKey, newAgent) return newAgent } module.exports = { getAgent, Agent, // these are exported for backwards compatability HttpAgent: Agent, HttpsAgent: Agent, cache: { proxy: proxyCache, agent: agentCache, dns: dns.cache, clear: () => { proxyCache.clear() agentCache.clear() dns.cache.clear() }, }, } PK ~\!\rr@npmcli/agent/lib/errors.jsnu['use strict' class InvalidProxyProtocolError extends Error { constructor (url) { super(`Invalid protocol \`${url.protocol}\` connecting to proxy \`${url.host}\``) this.code = 'EINVALIDPROXY' this.proxy = url } } class ConnectionTimeoutError extends Error { constructor (host) { super(`Timeout connecting to host \`${host}\``) this.code = 'ECONNECTIONTIMEOUT' this.host = host } } class IdleTimeoutError extends Error { constructor (host) { super(`Idle timeout reached for host \`${host}\``) this.code = 'EIDLETIMEOUT' this.host = host } } class ResponseTimeoutError extends Error { constructor (request, proxy) { let msg = 'Response timeout ' if (proxy) { msg += `from proxy \`${proxy.host}\` ` } msg += `connecting to host \`${request.host}\`` super(msg) this.code = 'ERESPONSETIMEOUT' this.proxy = proxy this.request = request } } class TransferTimeoutError extends Error { constructor (request, proxy) { let msg = 'Transfer timeout ' if (proxy) { msg += `from proxy \`${proxy.host}\` ` } msg += `for \`${request.host}\`` super(msg) this.code = 'ETRANSFERTIMEOUT' this.proxy = proxy this.request = request } } module.exports = { InvalidProxyProtocolError, ConnectionTimeoutError, IdleTimeoutError, ResponseTimeoutError, TransferTimeoutError, } PK ~\x @npmcli/agent/lib/options.jsnu['use strict' const dns = require('./dns') const normalizeOptions = (opts) => { const family = parseInt(opts.family ?? '0', 10) const keepAlive = opts.keepAlive ?? true const normalized = { // nodejs http agent options. these are all the defaults // but kept here to increase the likelihood of cache hits // https://nodejs.org/api/http.html#new-agentoptions keepAliveMsecs: keepAlive ? 1000 : undefined, maxSockets: opts.maxSockets ?? 15, maxTotalSockets: Infinity, maxFreeSockets: keepAlive ? 256 : undefined, scheduling: 'fifo', // then spread the rest of the options ...opts, // we already set these to their defaults that we want family, keepAlive, // our custom timeout options timeouts: { // the standard timeout option is mapped to our idle timeout // and then deleted below idle: opts.timeout ?? 0, connection: 0, response: 0, transfer: 0, ...opts.timeouts, }, // get the dns options that go at the top level of socket connection ...dns.getOptions({ family, ...opts.dns }), } // remove timeout since we already used it to set our own idle timeout delete normalized.timeout return normalized } const createKey = (obj) => { let key = '' const sorted = Object.entries(obj).sort((a, b) => a[0] - b[0]) for (let [k, v] of sorted) { if (v == null) { v = 'null' } else if (v instanceof URL) { v = v.toString() } else if (typeof v === 'object') { v = createKey(v) } key += `${k}:${v}:` } return key } const cacheOptions = ({ secureEndpoint, ...options }) => createKey({ secureEndpoint: !!secureEndpoint, // socket connect options family: options.family, hints: options.hints, localAddress: options.localAddress, // tls specific connect options strictSsl: secureEndpoint ? !!options.rejectUnauthorized : false, ca: secureEndpoint ? options.ca : null, cert: secureEndpoint ? options.cert : null, key: secureEndpoint ? options.key : null, // http agent options keepAlive: options.keepAlive, keepAliveMsecs: options.keepAliveMsecs, maxSockets: options.maxSockets, maxTotalSockets: options.maxTotalSockets, maxFreeSockets: options.maxFreeSockets, scheduling: options.scheduling, // timeout options timeouts: options.timeouts, // proxy proxy: options.proxy, }) module.exports = { normalizeOptions, cacheOptions, } PK ~\&@@"@npmcli/promise-spawn/package.jsonnu[{ "_id": "@npmcli/promise-spawn@7.0.2", "_inBundle": true, "_location": "/npm/@npmcli/promise-spawn", "_phantomChildren": {}, "_requiredBy": [ "/npm", "/npm/@npmcli/git", "/npm/@npmcli/run-script", "/npm/pacote" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/promise-spawn/issues" }, "dependencies": { "which": "^4.0.0" }, "description": "spawn processes the way the npm cli likes to do", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.22.0", "spawk": "^1.7.1", "tap": "^16.0.1" }, "engines": { "node": "^16.14.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/promise-spawn#readme", "license": "ISC", "main": "./lib/index.js", "name": "@npmcli/promise-spawn", "repository": { "type": "git", "url": "git+https://github.com/npm/promise-spawn.git" }, "scripts": { "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "postsnap": "npm run lintfix --", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "check-coverage": true, "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.22.0", "publish": true }, "version": "7.0.2" } PK ~\>#@npmcli/promise-spawn/lib/escape.jsnu['use strict' // eslint-disable-next-line max-len // this code adapted from: https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/ const cmd = (input, doubleEscape) => { if (!input.length) { return '""' } let result if (!/[ \t\n\v"]/.test(input)) { result = input } else { result = '"' for (let i = 0; i <= input.length; ++i) { let slashCount = 0 while (input[i] === '\\') { ++i ++slashCount } if (i === input.length) { result += '\\'.repeat(slashCount * 2) break } if (input[i] === '"') { result += '\\'.repeat(slashCount * 2 + 1) result += input[i] } else { result += '\\'.repeat(slashCount) result += input[i] } } result += '"' } // and finally, prefix shell meta chars with a ^ result = result.replace(/[ !%^&()<>|"]/g, '^$&') if (doubleEscape) { result = result.replace(/[ !%^&()<>|"]/g, '^$&') } return result } const sh = (input) => { if (!input.length) { return `''` } if (!/[\t\n\r "#$&'()*;<>?\\`|~]/.test(input)) { return input } // replace single quotes with '\'' and wrap the whole result in a fresh set of quotes const result = `'${input.replace(/'/g, `'\\''`)}'` // if the input string already had single quotes around it, clean those up .replace(/^(?:'')+(?!$)/, '') .replace(/\\'''/g, `\\'`) return result } module.exports = { cmd, sh, } PK ~\A*"@npmcli/promise-spawn/lib/index.jsnu['use strict' const { spawn } = require('child_process') const os = require('os') const which = require('which') const escape = require('./escape.js') // 'extra' object is for decorating the error a bit more const promiseSpawn = (cmd, args, opts = {}, extra = {}) => { if (opts.shell) { return spawnWithShell(cmd, args, opts, extra) } let resolve, reject const promise = new Promise((_resolve, _reject) => { resolve = _resolve reject = _reject }) // Create error here so we have a more useful stack trace when rejecting const closeError = new Error('command failed') const stdout = [] const stderr = [] const getResult = (result) => ({ cmd, args, ...result, ...stdioResult(stdout, stderr, opts), ...extra, }) const rejectWithOpts = (er, erOpts) => { const resultError = getResult(erOpts) reject(Object.assign(er, resultError)) } const proc = spawn(cmd, args, opts) promise.stdin = proc.stdin promise.process = proc proc.on('error', rejectWithOpts) if (proc.stdout) { proc.stdout.on('data', c => stdout.push(c)) proc.stdout.on('error', rejectWithOpts) } if (proc.stderr) { proc.stderr.on('data', c => stderr.push(c)) proc.stderr.on('error', rejectWithOpts) } proc.on('close', (code, signal) => { if (code || signal) { rejectWithOpts(closeError, { code, signal }) } else { resolve(getResult({ code, signal })) } }) return promise } const spawnWithShell = (cmd, args, opts, extra) => { let command = opts.shell // if shell is set to true, we use a platform default. we can't let the core // spawn method decide this for us because we need to know what shell is in use // ahead of time so that we can escape arguments properly. we don't need coverage here. if (command === true) { // istanbul ignore next command = process.platform === 'win32' ? process.env.ComSpec : 'sh' } const options = { ...opts, shell: false } const realArgs = [] let script = cmd // first, determine if we're in windows because if we are we need to know if we're // running an .exe or a .cmd/.bat since the latter requires extra escaping const isCmd = /(?:^|\\)cmd(?:\.exe)?$/i.test(command) if (isCmd) { let doubleEscape = false // find the actual command we're running let initialCmd = '' let insideQuotes = false for (let i = 0; i < cmd.length; ++i) { const char = cmd.charAt(i) if (char === ' ' && !insideQuotes) { break } initialCmd += char if (char === '"' || char === "'") { insideQuotes = !insideQuotes } } let pathToInitial try { pathToInitial = which.sync(initialCmd, { path: (options.env && findInObject(options.env, 'PATH')) || process.env.PATH, pathext: (options.env && findInObject(options.env, 'PATHEXT')) || process.env.PATHEXT, }).toLowerCase() } catch (err) { pathToInitial = initialCmd.toLowerCase() } doubleEscape = pathToInitial.endsWith('.cmd') || pathToInitial.endsWith('.bat') for (const arg of args) { script += ` ${escape.cmd(arg, doubleEscape)}` } realArgs.push('/d', '/s', '/c', script) options.windowsVerbatimArguments = true } else { for (const arg of args) { script += ` ${escape.sh(arg)}` } realArgs.push('-c', script) } return promiseSpawn(command, realArgs, options, extra) } // open a file with the default application as defined by the user's OS const open = (_args, opts = {}, extra = {}) => { const options = { ...opts, shell: true } const args = [].concat(_args) let platform = process.platform // process.platform === 'linux' may actually indicate WSL, if that's the case // we want to treat things as win32 anyway so the host can open the argument if (platform === 'linux' && os.release().toLowerCase().includes('microsoft')) { platform = 'win32' } let command = options.command if (!command) { if (platform === 'win32') { // spawnWithShell does not do the additional os.release() check, so we // have to force the shell here to make sure we treat WSL as windows. options.shell = process.env.ComSpec // also, the start command accepts a title so to make sure that we don't // accidentally interpret the first arg as the title, we stick an empty // string immediately after the start command command = 'start ""' } else if (platform === 'darwin') { command = 'open' } else { command = 'xdg-open' } } return spawnWithShell(command, args, options, extra) } promiseSpawn.open = open const isPipe = (stdio = 'pipe', fd) => { if (stdio === 'pipe' || stdio === null) { return true } if (Array.isArray(stdio)) { return isPipe(stdio[fd], fd) } return false } const stdioResult = (stdout, stderr, { stdioString = true, stdio }) => { const result = { stdout: null, stderr: null, } // stdio is [stdin, stdout, stderr] if (isPipe(stdio, 1)) { result.stdout = Buffer.concat(stdout) if (stdioString) { result.stdout = result.stdout.toString().trim() } } if (isPipe(stdio, 2)) { result.stderr = Buffer.concat(stderr) if (stdioString) { result.stderr = result.stderr.toString().trim() } } return result } // case insensitive lookup in an object const findInObject = (obj, key) => { key = key.toLowerCase() for (const objKey of Object.keys(obj).sort()) { if (objKey.toLowerCase() === key) { return obj[objKey] } } } module.exports = promiseSpawn PK ~\|q@npmcli/promise-spawn/LICENSEnu[The ISC License Copyright (c) npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE NPM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE NPM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\.  #@npmcli/map-workspaces/package.jsonnu[{ "_id": "@npmcli/map-workspaces@3.0.6", "_inBundle": true, "_location": "/npm/@npmcli/map-workspaces", "_phantomChildren": {}, "_requiredBy": [ "/npm", "/npm/@npmcli/arborist", "/npm/@npmcli/config" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/map-workspaces/issues" }, "dependencies": { "@npmcli/name-from-folder": "^2.0.0", "glob": "^10.2.2", "minimatch": "^9.0.0", "read-package-json-fast": "^3.0.0" }, "description": "Retrieves a name:pathname Map for a given workspaces config", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.21.3", "tap": "^16.0.1" }, "engines": { "node": "^14.17.0 || ^16.13.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/map-workspaces#readme", "keywords": [ "npm", "npmcli", "libnpm", "cli", "workspaces", "map-workspaces" ], "license": "ISC", "main": "lib/index.js", "name": "@npmcli/map-workspaces", "repository": { "type": "git", "url": "git+https://github.com/npm/map-workspaces.git" }, "scripts": { "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "pretest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "check-coverage": true, "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.21.3", "publish": "true" }, "version": "3.0.6" } PK ~\=.#@npmcli/map-workspaces/lib/index.jsnu[const path = require('path') const getName = require('@npmcli/name-from-folder') const { minimatch } = require('minimatch') const rpj = require('read-package-json-fast') const { glob } = require('glob') function appendNegatedPatterns (allPatterns) { const patterns = [] const negatedPatterns = [] for (let pattern of allPatterns) { const excl = pattern.match(/^!+/) if (excl) { pattern = pattern.slice(excl[0].length) } // strip off any / or ./ from the start of the pattern. /foo => foo pattern = pattern.replace(/^\.?\/+/, '') // an odd number of ! means a negated pattern. !!foo ==> foo const negate = excl && excl[0].length % 2 === 1 if (negate) { negatedPatterns.push(pattern) } else { // remove negated patterns that appeared before this pattern to avoid // ignoring paths that were matched afterwards // e.g: ['packages/**', '!packages/b/**', 'packages/b/a'] // in the above list, the last pattern overrides the negated pattern // right before it. In effect, the above list would become: // ['packages/**', 'packages/b/a'] // The order matters here which is why we must do it inside the loop // as opposed to doing it all together at the end. for (let i = 0; i < negatedPatterns.length; ++i) { const negatedPattern = negatedPatterns[i] if (minimatch(pattern, negatedPattern)) { negatedPatterns.splice(i, 1) } } patterns.push(pattern) } } // use the negated patterns to eagerly remove all the patterns that // can be removed to avoid unnecessary crawling for (const negated of negatedPatterns) { for (const pattern of minimatch.match(patterns, negated)) { patterns.splice(patterns.indexOf(pattern), 1) } } return { patterns, negatedPatterns } } function getPatterns (workspaces) { const workspacesDeclaration = Array.isArray(workspaces.packages) ? workspaces.packages : workspaces if (!Array.isArray(workspacesDeclaration)) { throw getError({ message: 'workspaces config expects an Array', code: 'EWORKSPACESCONFIG', }) } return appendNegatedPatterns(workspacesDeclaration) } function getPackageName (pkg, pathname) { const { name } = pkg return name || getName(pathname) } function pkgPathmame (opts) { return (...args) => { const cwd = opts.cwd ? opts.cwd : process.cwd() return path.join.apply(null, [cwd, ...args]) } } // make sure glob pattern only matches folders function getGlobPattern (pattern) { pattern = pattern.replace(/\\/g, '/') return pattern.endsWith('/') ? pattern : `${pattern}/` } function getError ({ Type = TypeError, message, code }) { return Object.assign(new Type(message), { code }) } function reverseResultMap (map) { return new Map(Array.from(map, item => item.reverse())) } async function mapWorkspaces (opts = {}) { if (!opts || !opts.pkg) { throw getError({ message: 'mapWorkspaces missing pkg info', code: 'EMAPWORKSPACESPKG', }) } const { workspaces = [] } = opts.pkg const { patterns, negatedPatterns } = getPatterns(workspaces) const results = new Map() const seen = new Map() if (!patterns.length && !negatedPatterns.length) { return results } const getGlobOpts = () => ({ ...opts, ignore: [ ...opts.ignore || [], '**/node_modules/**', // just ignore the negated patterns to avoid unnecessary crawling ...negatedPatterns, ], }) const getPackagePathname = pkgPathmame(opts) let matches = await glob(patterns.map((p) => getGlobPattern(p)), getGlobOpts()) // preserves glob@8 behavior matches = matches.sort((a, b) => a.localeCompare(b, 'en')) // we must preserve the order of results according to the given list of // workspace patterns const orderedMatches = [] for (const pattern of patterns) { orderedMatches.push(...matches.filter((m) => { return minimatch(m, pattern, { partial: true, windowsPathsNoEscape: true }) })) } for (const match of orderedMatches) { let pkg const packageJsonPathname = getPackagePathname(match, 'package.json') try { pkg = await rpj(packageJsonPathname) } catch (err) { if (err.code === 'ENOENT') { continue } else { throw err } } const packagePathname = path.dirname(packageJsonPathname) const name = getPackageName(pkg, packagePathname) let seenPackagePathnames = seen.get(name) if (!seenPackagePathnames) { seenPackagePathnames = new Set() seen.set(name, seenPackagePathnames) } seenPackagePathnames.add(packagePathname) } const errorMessageArray = ['must not have multiple workspaces with the same name'] for (const [packageName, seenPackagePathnames] of seen) { if (seenPackagePathnames.size > 1) { addDuplicateErrorMessages(errorMessageArray, packageName, seenPackagePathnames) } else { results.set(packageName, seenPackagePathnames.values().next().value) } } if (errorMessageArray.length > 1) { throw getError({ Type: Error, message: errorMessageArray.join('\n'), code: 'EDUPLICATEWORKSPACE', }) } return results } function addDuplicateErrorMessages (messageArray, packageName, packagePathnames) { messageArray.push( `package '${packageName}' has conflicts in the following paths:` ) for (const packagePathname of packagePathnames) { messageArray.push( ' ' + packagePathname ) } } mapWorkspaces.virtual = function (opts = {}) { if (!opts || !opts.lockfile) { throw getError({ message: 'mapWorkspaces.virtual missing lockfile info', code: 'EMAPWORKSPACESLOCKFILE', }) } const { packages = {} } = opts.lockfile const { workspaces = [] } = packages[''] || {} // uses a pathname-keyed map in order to negate the exact items const results = new Map() const { patterns, negatedPatterns } = getPatterns(workspaces) if (!patterns.length && !negatedPatterns.length) { return results } negatedPatterns.push('**/node_modules/**') const packageKeys = Object.keys(packages) for (const pattern of negatedPatterns) { for (const packageKey of minimatch.match(packageKeys, pattern)) { packageKeys.splice(packageKeys.indexOf(packageKey), 1) } } const getPackagePathname = pkgPathmame(opts) for (const pattern of patterns) { for (const packageKey of minimatch.match(packageKeys, pattern)) { const packagePathname = getPackagePathname(packageKey) const name = getPackageName(packages[packageKey], packagePathname) results.set(packagePathname, name) } } // Invert pathname-keyed to a proper name-to-pathnames Map return reverseResultMap(results) } module.exports = mapWorkspaces PK ~\r!@npmcli/map-workspaces/LICENSE.mdnu[ ISC License Copyright npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND NPM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NPM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\ %@npmcli/name-from-folder/package.jsonnu[{ "_id": "@npmcli/name-from-folder@2.0.0", "_inBundle": true, "_location": "/npm/@npmcli/name-from-folder", "_phantomChildren": {}, "_requiredBy": [ "/npm/@npmcli/arborist", "/npm/@npmcli/map-workspaces" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/name-from-folder/issues" }, "description": "Get the package name from a folder path", "devDependencies": { "@npmcli/eslint-config": "^4.0.1", "@npmcli/template-oss": "4.11.0", "tap": "^16.3.2" }, "engines": { "node": "^14.17.0 || ^16.13.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/name-from-folder#readme", "license": "ISC", "main": "lib/index.js", "name": "@npmcli/name-from-folder", "repository": { "type": "git", "url": "git+https://github.com/npm/name-from-folder.git" }, "scripts": { "lint": "eslint \"**/*.js\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.11.0" }, "version": "2.0.0" } PK ~\^(O%@npmcli/name-from-folder/lib/index.jsnu[const { basename, dirname } = require('path') const getName = (parent, base) => parent.charAt(0) === '@' ? `${parent}/${base}` : base module.exports = dir => dir ? getName(basename(dirname(dir)), basename(dir)) : false PK ~\ @npmcli/name-from-folder/LICENSEnu[The ISC License Copyright npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND NPM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NPM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\Mz@npmcli/redact/package.jsonnu[{ "_id": "@npmcli/redact@2.0.0", "_inBundle": true, "_location": "/npm/@npmcli/redact", "_phantomChildren": {}, "_requiredBy": [ "/npm", "/npm/@npmcli/arborist", "/npm/npm-registry-fetch" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/redact/issues" }, "description": "Redact sensitive npm information from output", "devDependencies": { "@npmcli/eslint-config": "^4.0.2", "@npmcli/template-oss": "4.21.3", "tap": "^16.3.10" }, "engines": { "node": "^16.14.0 || >=18.0.0" }, "exports": { ".": "./lib/index.js", "./server": "./lib/server.js", "./package.json": "./package.json" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/redact#readme", "keywords": [], "license": "ISC", "main": "lib/index.js", "name": "@npmcli/redact", "repository": { "type": "git", "url": "git+https://github.com/npm/redact.git" }, "scripts": { "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ], "timeout": 120 }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.21.3", "publish": true }, "version": "2.0.0" } PK ~\2pp@npmcli/redact/lib/utils.jsnu[const { URL_MATCHER, TYPE_URL, TYPE_REGEX, TYPE_PATH, } = require('./matchers') /** * creates a string of asterisks, * this forces a minimum asterisk for security purposes */ const asterisk = (length = 0) => { length = typeof length === 'string' ? length.length : length if (length < 8) { return '*'.repeat(8) } return '*'.repeat(length) } /** * escapes all special regex chars * @see https://stackoverflow.com/a/9310752 * @see https://github.com/tc39/proposal-regex-escaping */ const escapeRegExp = (text) => { return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, `\\$&`) } /** * provieds a regex "or" of the url versions of a string */ const urlEncodeRegexGroup = (value) => { const decoded = decodeURIComponent(value) const encoded = encodeURIComponent(value) const union = [...new Set([encoded, decoded, value])].map(escapeRegExp).join('|') return union } /** * a tagged template literal that returns a regex ensures all variables are excaped */ const urlEncodeRegexTag = (strings, ...values) => { let pattern = '' for (let i = 0; i < values.length; i++) { pattern += strings[i] + `(${urlEncodeRegexGroup(values[i])})` } pattern += strings[strings.length - 1] return new RegExp(pattern) } /** * creates a matcher for redacting url hostname */ const redactUrlHostnameMatcher = ({ hostname, replacement } = {}) => ({ type: TYPE_URL, predicate: ({ url }) => url.hostname === hostname, pattern: ({ url }) => { return urlEncodeRegexTag`(^${url.protocol}//${url.username}:.+@)?${url.hostname}` }, replacement: `$1${replacement || asterisk()}`, }) /** * creates a matcher for redacting url search / query parameter values */ const redactUrlSearchParamsMatcher = ({ param, replacement } = {}) => ({ type: TYPE_URL, predicate: ({ url }) => url.searchParams.has(param), pattern: ({ url }) => urlEncodeRegexTag`(${param}=)${url.searchParams.get(param)}`, replacement: `$1${replacement || asterisk()}`, }) /** creates a matcher for redacting the url password */ const redactUrlPasswordMatcher = ({ replacement } = {}) => ({ type: TYPE_URL, predicate: ({ url }) => url.password, pattern: ({ url }) => urlEncodeRegexTag`(^${url.protocol}//${url.username}:)${url.password}`, replacement: `$1${replacement || asterisk()}`, }) const redactUrlReplacement = (...matchers) => (subValue) => { try { const url = new URL(subValue) return redactMatchers(...matchers)(subValue, { url }) } catch (err) { return subValue } } /** * creates a matcher / submatcher for urls, this function allows you to first * collect all urls within a larger string and then pass those urls to a * submatcher * * @example * console.log("this will first match all urls, then pass those urls to the password patcher") * redactMatchers(redactUrlMatcher(redactUrlPasswordMatcher())) * * @example * console.log( * "this will assume you are passing in a string that is a url, and will redact the password" * ) * redactMatchers(redactUrlPasswordMatcher()) * */ const redactUrlMatcher = (...matchers) => { return { ...URL_MATCHER, replacement: redactUrlReplacement(...matchers), } } const matcherFunctions = { [TYPE_REGEX]: (matcher) => (value) => { if (typeof value === 'string') { value = value.replace(matcher.pattern, matcher.replacement) } return value }, [TYPE_URL]: (matcher) => (value, ctx) => { if (typeof value === 'string') { try { const url = ctx?.url || new URL(value) const { predicate, pattern } = matcher const predicateValue = predicate({ url }) if (predicateValue) { value = value.replace(pattern({ url }), matcher.replacement) } } catch (_e) { return value } } return value }, [TYPE_PATH]: (matcher) => (value, ctx) => { const rawPath = ctx?.path const path = rawPath.join('.').toLowerCase() const { predicate, replacement } = matcher const replace = typeof replacement === 'function' ? replacement : () => replacement const shouldRun = predicate({ rawPath, path }) if (shouldRun) { value = replace(value, { rawPath, path }) } return value }, } /** converts a matcher to a function */ const redactMatcher = (matcher) => { return matcherFunctions[matcher.type](matcher) } /** converts a series of matchers to a function */ const redactMatchers = (...matchers) => (value, ctx) => { const flatMatchers = matchers.flat() return flatMatchers.reduce((result, matcher) => { const fn = (typeof matcher === 'function') ? matcher : redactMatcher(matcher) return fn(result, ctx) }, value) } /** * replacement handler, keeping $1 (if it exists) and replacing the * rest of the string with asterisks, maintaining string length */ const redactDynamicReplacement = () => (value, start) => { if (typeof start === 'number') { return asterisk(value) } return start + asterisk(value.substring(start.length).length) } /** * replacement handler, keeping $1 (if it exists) and replacing the * rest of the string with a fixed number of asterisks */ const redactFixedReplacement = (length) => (_value, start) => { if (typeof start === 'number') { return asterisk(length) } return start + asterisk(length) } const redactUrlPassword = (value, replacement) => { return redactMatchers(redactUrlPasswordMatcher({ replacement }))(value) } module.exports = { asterisk, escapeRegExp, urlEncodeRegexGroup, urlEncodeRegexTag, redactUrlHostnameMatcher, redactUrlSearchParamsMatcher, redactUrlPasswordMatcher, redactUrlMatcher, redactUrlReplacement, redactDynamicReplacement, redactFixedReplacement, redactMatchers, redactUrlPassword, } PK ~\7EE@npmcli/redact/lib/index.jsnu[const matchers = require('./matchers') const { redactUrlPassword } = require('./utils') const REPLACE = '***' const redact = (value) => { if (typeof value !== 'string' || !value) { return value } return redactUrlPassword(value, REPLACE) .replace(matchers.NPM_SECRET.pattern, `npm_${REPLACE}`) .replace(matchers.UUID.pattern, REPLACE) } // split on \s|= similar to how nopt parses options const splitAndRedact = (str) => { // stateful regex, don't move out of this scope const splitChars = /[\s=]/g let match = null let result = '' let index = 0 while (match = splitChars.exec(str)) { result += redact(str.slice(index, match.index)) + match[0] index = splitChars.lastIndex } return result + redact(str.slice(index)) } // replaces auth info in an array of arguments or in a strings const redactLog = (arg) => { if (typeof arg === 'string') { return splitAndRedact(arg) } else if (Array.isArray(arg)) { return arg.map((a) => typeof a === 'string' ? splitAndRedact(a) : a) } return arg } module.exports = { redact, redactLog, } PK ~\.@npmcli/redact/lib/server.jsnu[const { AUTH_HEADER, JSON_WEB_TOKEN, NPM_SECRET, DEEP_HEADER_AUTHORIZATION, DEEP_HEADER_SET_COOKIE, REWRITE_REQUEST, REWRITE_RESPONSE, } = require('./matchers') const { redactUrlMatcher, redactUrlPasswordMatcher, redactMatchers, } = require('./utils') const { deepMap } = require('./deep-map') const _redact = redactMatchers( NPM_SECRET, AUTH_HEADER, JSON_WEB_TOKEN, DEEP_HEADER_AUTHORIZATION, DEEP_HEADER_SET_COOKIE, REWRITE_REQUEST, REWRITE_RESPONSE, redactUrlMatcher( redactUrlPasswordMatcher() ) ) const redact = (input) => deepMap(input, (value, path) => _redact(value, { path })) module.exports = { redact } PK ~\F䖮  @npmcli/redact/lib/deep-map.jsnu[const deepMap = (input, handler = v => v, path = ['$'], seen = new Set([input])) => { if (Array.isArray(input)) { const result = [] for (let i = 0; i < input.length; i++) { const element = input[i] const elementPath = [...path, i] if (element instanceof Object) { if (!seen.has(element)) { // avoid getting stuck in circular reference seen.add(element) result.push(deepMap(handler(element, elementPath), handler, elementPath, seen)) } } else { result.push(handler(element, elementPath)) } } return result } if (input === null) { return null } else if (typeof input === 'object' || typeof input === 'function') { const result = {} if (input instanceof Error) { // `name` property is not included in `Object.getOwnPropertyNames(error)` result.errorType = input.name } for (const propertyName of Object.getOwnPropertyNames(input)) { // skip logging internal properties if (propertyName.startsWith('_')) { continue } try { const property = input[propertyName] const propertyPath = [...path, propertyName] if (property instanceof Object) { if (!seen.has(property)) { // avoid getting stuck in circular reference seen.add(property) result[propertyName] = deepMap( handler(property, propertyPath), handler, propertyPath, seen ) } } else { result[propertyName] = handler(property, propertyPath) } } catch (err) { // a getter may throw an error result[propertyName] = `[error getting value: ${err.message}]` } } return result } return handler(input, path) } module.exports = { deepMap } PK ~\))@npmcli/redact/lib/matchers.jsnu[const TYPE_REGEX = 'regex' const TYPE_URL = 'url' const TYPE_PATH = 'path' const NPM_SECRET = { type: TYPE_REGEX, pattern: /\b(npms?_)[a-zA-Z0-9]{36,48}\b/gi, replacement: `[REDACTED_NPM_SECRET]`, } const AUTH_HEADER = { type: TYPE_REGEX, pattern: /\b(Basic\s+|Bearer\s+)[\w+=\-.]+\b/gi, replacement: `[REDACTED_AUTH_HEADER]`, } const JSON_WEB_TOKEN = { type: TYPE_REGEX, pattern: /\b[A-Za-z0-9-_]{10,}(?!\.\d+\.)\.[A-Za-z0-9-_]{3,}\.[A-Za-z0-9-_]{20,}\b/gi, replacement: `[REDACTED_JSON_WEB_TOKEN]`, } const UUID = { type: TYPE_REGEX, pattern: /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi, replacement: `[REDACTED_UUID]`, } const URL_MATCHER = { type: TYPE_REGEX, pattern: /(?:https?|ftp):\/\/[^\s/"$.?#].[^\s"]*/gi, replacement: '[REDACTED_URL]', } const DEEP_HEADER_AUTHORIZATION = { type: TYPE_PATH, predicate: ({ path }) => path.endsWith('.headers.authorization'), replacement: '[REDACTED_HEADER_AUTHORIZATION]', } const DEEP_HEADER_SET_COOKIE = { type: TYPE_PATH, predicate: ({ path }) => path.endsWith('.headers.set-cookie'), replacement: '[REDACTED_HEADER_SET_COOKIE]', } const REWRITE_REQUEST = { type: TYPE_PATH, predicate: ({ path }) => path.endsWith('.request'), replacement: (input) => ({ method: input?.method, path: input?.path, headers: input?.headers, url: input?.url, }), } const REWRITE_RESPONSE = { type: TYPE_PATH, predicate: ({ path }) => path.endsWith('.response'), replacement: (input) => ({ data: input?.data, status: input?.status, headers: input?.headers, }), } module.exports = { TYPE_REGEX, TYPE_URL, TYPE_PATH, NPM_SECRET, AUTH_HEADER, JSON_WEB_TOKEN, UUID, URL_MATCHER, DEEP_HEADER_AUTHORIZATION, DEEP_HEADER_SET_COOKIE, REWRITE_REQUEST, REWRITE_RESPONSE, } PK ~\%$$@npmcli/redact/LICENSEnu[MIT License Copyright (c) 2024 npm Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\xI/@npmcli/installed-package-contents/package.jsonnu[{ "_id": "@npmcli/installed-package-contents@2.1.0", "_inBundle": true, "_location": "/npm/@npmcli/installed-package-contents", "_phantomChildren": {}, "_requiredBy": [ "/npm/@npmcli/arborist", "/npm/libnpmdiff", "/npm/pacote" ], "author": { "name": "GitHub Inc." }, "bin": { "installed-package-contents": "bin/index.js" }, "bugs": { "url": "https://github.com/npm/installed-package-contents/issues" }, "dependencies": { "npm-bundled": "^3.0.0", "npm-normalize-package-bin": "^3.0.0" }, "description": "Get the list of files installed in a package in node_modules, including bundled dependencies", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.21.4", "tap": "^16.3.0" }, "engines": { "node": "^14.17.0 || ^16.13.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/installed-package-contents#readme", "license": "ISC", "main": "lib/index.js", "name": "@npmcli/installed-package-contents", "repository": { "type": "git", "url": "git+https://github.com/npm/installed-package-contents.git" }, "scripts": { "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.21.4", "publish": true }, "version": "2.1.0" } PK ~\. ss/@npmcli/installed-package-contents/lib/index.jsnu[// to GET CONTENTS for folder at PATH (which may be a PACKAGE): // - if PACKAGE, read path/package.json // - if bins in ../node_modules/.bin, add those to result // - if depth >= maxDepth, add PATH to result, and finish // - readdir(PATH, with file types) // - add all FILEs in PATH to result // - if PARENT: // - if depth < maxDepth, add GET CONTENTS of all DIRs in PATH // - else, add all DIRs in PATH // - if no parent // - if no bundled deps, // - if depth < maxDepth, add GET CONTENTS of DIRs in path except // node_modules // - else, add all DIRs in path other than node_modules // - if has bundled deps, // - get list of bundled deps // - add GET CONTENTS of bundled deps, PACKAGE=true, depth + 1 const bundled = require('npm-bundled') const { readFile, readdir, stat } = require('fs/promises') const { resolve, basename, dirname } = require('path') const normalizePackageBin = require('npm-normalize-package-bin') const readPackage = ({ path, packageJsonCache }) => packageJsonCache.has(path) ? Promise.resolve(packageJsonCache.get(path)) : readFile(path).then(json => { const pkg = normalizePackageBin(JSON.parse(json)) packageJsonCache.set(path, pkg) return pkg }).catch(() => null) // just normalize bundle deps and bin, that's all we care about here. const normalized = Symbol('package data has been normalized') const rpj = ({ path, packageJsonCache }) => readPackage({ path, packageJsonCache }) .then(pkg => { if (!pkg || pkg[normalized]) { return pkg } if (pkg.bundledDependencies && !pkg.bundleDependencies) { pkg.bundleDependencies = pkg.bundledDependencies delete pkg.bundledDependencies } const bd = pkg.bundleDependencies if (bd === true) { pkg.bundleDependencies = [ ...Object.keys(pkg.dependencies || {}), ...Object.keys(pkg.optionalDependencies || {}), ] } if (typeof bd === 'object' && !Array.isArray(bd)) { pkg.bundleDependencies = Object.keys(bd) } pkg[normalized] = true return pkg }) const pkgContents = async ({ path, depth = 1, currentDepth = 0, pkg = null, result = null, packageJsonCache = null, }) => { if (!result) { result = new Set() } if (!packageJsonCache) { packageJsonCache = new Map() } if (pkg === true) { return rpj({ path: path + '/package.json', packageJsonCache }) .then(p => pkgContents({ path, depth, currentDepth, pkg: p, result, packageJsonCache, })) } if (pkg) { // add all bins to result if they exist if (pkg.bin) { const dir = dirname(path) const scope = basename(dir) const nm = /^@.+/.test(scope) ? dirname(dir) : dir const binFiles = [] Object.keys(pkg.bin).forEach(b => { const base = resolve(nm, '.bin', b) binFiles.push(base, base + '.cmd', base + '.ps1') }) const bins = await Promise.all( binFiles.map(b => stat(b).then(() => b).catch(() => null)) ) bins.filter(b => b).forEach(b => result.add(b)) } } if (currentDepth >= depth) { result.add(path) return result } // we'll need bundle list later, so get that now in parallel const [dirEntries, bundleDeps] = await Promise.all([ readdir(path, { withFileTypes: true }), currentDepth === 0 && pkg && pkg.bundleDependencies ? bundled({ path, packageJsonCache }) : null, ]).catch(() => []) // not a thing, probably a missing folder if (!dirEntries) { return result } // empty folder, just add the folder itself to the result if (!dirEntries.length && !bundleDeps && currentDepth !== 0) { result.add(path) return result } const recursePromises = [] for (const entry of dirEntries) { const p = resolve(path, entry.name) if (entry.isDirectory() === false) { result.add(p) continue } if (currentDepth !== 0 || entry.name !== 'node_modules') { if (currentDepth < depth - 1) { recursePromises.push(pkgContents({ path: p, packageJsonCache, depth, currentDepth: currentDepth + 1, result, })) } else { result.add(p) } continue } } if (bundleDeps) { // bundle deps are all folders // we always recurse to get pkg bins, but if currentDepth is too high, // it'll return early before walking their contents. recursePromises.push(...bundleDeps.map(dep => { const p = resolve(path, 'node_modules', dep) return pkgContents({ path: p, packageJsonCache, pkg: true, depth, currentDepth: currentDepth + 1, result, }) })) } if (recursePromises.length) { await Promise.all(recursePromises) } return result } module.exports = ({ path, ...opts }) => pkgContents({ path: resolve(path), ...opts, pkg: true, }).then(results => [...results]) PK ~\.9*@npmcli/installed-package-contents/LICENSEnu[The ISC License Copyright (c) npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\?UU/@npmcli/installed-package-contents/bin/index.jsnu[#! /usr/bin/env node const { relative } = require('path') const pkgContents = require('../') const usage = `Usage: installed-package-contents [-d --depth=] Lists the files installed for a package specified by . Options: -d --depth= Provide a numeric value ("Infinity" is allowed) to specify how deep in the file tree to traverse. Default=1 -h --help Show this usage information` const options = {} process.argv.slice(2).forEach(arg => { let match if ((match = arg.match(/^(?:--depth=|-d)([0-9]+|Infinity)/))) { options.depth = +match[1] } else if (arg === '-h' || arg === '--help') { console.log(usage) process.exit(0) } else { options.path = arg } }) if (!options.path) { console.error('ERROR: no path provided') console.error(usage) process.exit(1) } const cwd = process.cwd() pkgContents(options) .then(list => list.sort().forEach(p => console.log(relative(cwd, p)))) .catch(/* istanbul ignore next - pretty unusual */ er => { console.error(er) process.exit(1) }) PK ~\^^,@npmcli/installed-package-contents/README.mdnu[# @npmcli/installed-package-contents Get the list of files installed in a package in node_modules, including bundled dependencies. This is useful if you want to remove a package node from the tree _without_ removing its child nodes, for example to extract a new version of the dependency into place safely. It's sort of the reflection of [npm-packlist](http://npm.im/npm-packlist), but for listing out the _installed_ files rather than the files that _will_ be installed. This is of course a much simpler operation, because we don't have to handle ignore files or package.json `files` lists. ## USAGE ```js // programmatic usage const pkgContents = require('@npmcli/installed-package-contents') pkgContents({ path: 'node_modules/foo', depth: 1 }).then(files => { // files is an array of items that need to be passed to // rimraf or moved out of the way to make the folder empty // if foo bundled dependencies, those will be included. // It will not traverse into child directories, because we set // depth:1 in the options. // If the folder doesn't exist, this returns an empty array. }) pkgContents({ path: 'node_modules/foo', depth: Infinity }).then(files => { // setting depth:Infinity tells it to keep walking forever // until it hits something that isn't a directory, so we'll // just get the list of all files, but not their containing // directories. }) ``` As a CLI: ```bash $ installed-package-contents node_modules/bundle-some -d1 node_modules/.bin/some node_modules/bundle-some/package.json node_modules/bundle-some/node_modules/@scope/baz node_modules/bundle-some/node_modules/.bin/foo node_modules/bundle-some/node_modules/foo ``` CLI options: ``` Usage: installed-package-contents [-d --depth=] Lists the files installed for a package specified by . Options: -d --depth= Provide a numeric value ("Infinity" is allowed) to specify how deep in the file tree to traverse. Default=1 -h --help Show this usage information ``` ## OPTIONS * `depth` Number, default `1`. How deep to traverse through folders to get contents. Typically you'd want to set this to either `1` (to get the surface files and folders) or `Infinity` (to get all files), but any other positive number is supported as well. If set to `0` or a negative number, returns the path provided and (if it is a package) its set of linked bins. * `path` Required. Path to the package in `node_modules` where traversal should begin. ## RETURN VALUE A Promise that resolves to an array of fully-resolved files and folders matching the criteria. This includes all bundled dependencies in `node_modules`, and any linked executables in `node_modules/.bin` that the package caused to be installed. An empty or missing package folder will return an empty array. Empty directories _within_ package contents are listed, even if the `depth` argument would cause them to be traversed into. ## CAVEAT If using this module to generate a list of files that should be recursively removed to clear away the package, note that this will leave empty directories behind in certain cases: - If all child packages are bundled dependencies, then the `node_modules` folder will remain. - If all child packages within a given scope were bundled dependencies, then the `node_modules/@scope` folder will remain. - If all linked bin scripts were removed, then an empty `node_modules/.bin` folder will remain. In the interest of speed and algorithmic complexity, this module does _not_ do a subsequent readdir to see if it would remove all directory entries, though it would be easier to look at if it returned `node_modules` or `.bin` in that case rather than the contents. However, if the intent is to pass these arguments to `rimraf`, it hardly makes sense to do _two_ `readdir` calls just so that we can have the luxury of having to make a third. Since the primary use case is to delete a package's contents so that they can be re-filled with a new version of that package, this caveat does not pose a problem. Empty directories are already ignored by both npm and git. PK ~\ J@npmcli/node-gyp/package.jsonnu[{ "_id": "@npmcli/node-gyp@3.0.0", "_inBundle": true, "_location": "/npm/@npmcli/node-gyp", "_phantomChildren": {}, "_requiredBy": [ "/npm/@npmcli/arborist", "/npm/@npmcli/run-script" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/node-gyp/issues" }, "description": "Tools for dealing with node-gyp packages", "devDependencies": { "@npmcli/eslint-config": "^3.0.1", "@npmcli/template-oss": "4.5.1", "tap": "^16.0.1" }, "engines": { "node": "^14.17.0 || ^16.13.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/node-gyp#readme", "keywords": [ "npm", "cli", "node-gyp" ], "license": "ISC", "main": "lib/index.js", "name": "@npmcli/node-gyp", "repository": { "type": "git", "url": "git+https://github.com/npm/node-gyp.git" }, "scripts": { "lint": "eslint \"**/*.js\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.5.1" }, "version": "3.0.0" } PK ~\~!]]@npmcli/node-gyp/lib/index.jsnu[const util = require('util') const fs = require('fs') const { stat } = fs.promises || { stat: util.promisify(fs.stat) } async function isNodeGypPackage (path) { return await stat(`${path}/binding.gyp`) .then(st => st.isFile()) .catch(() => false) } module.exports = { isNodeGypPackage, defaultGypInstallScript: 'node-gyp rebuild', } PK ~\nr@npmcli/fs/package.jsonnu[{ "_id": "@npmcli/fs@3.1.1", "_inBundle": true, "_location": "/npm/@npmcli/fs", "_phantomChildren": {}, "_requiredBy": [ "/npm", "/npm/@npmcli/arborist", "/npm/cacache" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/fs/issues" }, "dependencies": { "semver": "^7.3.5" }, "description": "filesystem utilities for the npm cli", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.22.0", "tap": "^16.0.1" }, "engines": { "node": "^14.17.0 || ^16.13.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/fs#readme", "keywords": [ "npm", "oss" ], "license": "ISC", "main": "lib/index.js", "name": "@npmcli/fs", "repository": { "type": "git", "url": "git+https://github.com/npm/fs.git" }, "scripts": { "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "npmclilint": "npmcli-lint", "postlint": "template-oss-check", "postsnap": "npm run lintfix --", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.22.0" }, "version": "3.1.1" } PK ~\sY@npmcli/fs/lib/move-file.jsnu[const { dirname, join, resolve, relative, isAbsolute } = require('path') const fs = require('fs/promises') const pathExists = async path => { try { await fs.access(path) return true } catch (er) { return er.code !== 'ENOENT' } } const moveFile = async (source, destination, options = {}, root = true, symlinks = []) => { if (!source || !destination) { throw new TypeError('`source` and `destination` file required') } options = { overwrite: true, ...options, } if (!options.overwrite && await pathExists(destination)) { throw new Error(`The destination file exists: ${destination}`) } await fs.mkdir(dirname(destination), { recursive: true }) try { await fs.rename(source, destination) } catch (error) { if (error.code === 'EXDEV' || error.code === 'EPERM') { const sourceStat = await fs.lstat(source) if (sourceStat.isDirectory()) { const files = await fs.readdir(source) await Promise.all(files.map((file) => moveFile(join(source, file), join(destination, file), options, false, symlinks) )) } else if (sourceStat.isSymbolicLink()) { symlinks.push({ source, destination }) } else { await fs.copyFile(source, destination) } } else { throw error } } if (root) { await Promise.all(symlinks.map(async ({ source: symSource, destination: symDestination }) => { let target = await fs.readlink(symSource) // junction symlinks in windows will be absolute paths, so we need to // make sure they point to the symlink destination if (isAbsolute(target)) { target = resolve(symDestination, relative(symSource, target)) } // try to determine what the actual file is so we can create the correct // type of symlink in windows let targetStat = 'file' try { targetStat = await fs.stat(resolve(dirname(symSource), target)) if (targetStat.isDirectory()) { targetStat = 'junction' } } catch { // targetStat remains 'file' } await fs.symlink( target, symDestination, targetStat ) })) await fs.rm(source, { recursive: true, force: true }) } } module.exports = moveFile PK ~\R]Sm//@npmcli/fs/lib/cp/polyfill.jsnu[// this file is a modified version of the code in node 17.2.0 // which is, in turn, a modified version of the fs-extra module on npm // node core changes: // - Use of the assert module has been replaced with core's error system. // - All code related to the glob dependency has been removed. // - Bring your own custom fs module is not currently supported. // - Some basic code cleanup. // changes here: // - remove all callback related code // - drop sync support // - change assertions back to non-internal methods (see options.js) // - throws ENOTDIR when rmdir gets an ENOENT for a path that exists in Windows 'use strict' const { ERR_FS_CP_DIR_TO_NON_DIR, ERR_FS_CP_EEXIST, ERR_FS_CP_EINVAL, ERR_FS_CP_FIFO_PIPE, ERR_FS_CP_NON_DIR_TO_DIR, ERR_FS_CP_SOCKET, ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY, ERR_FS_CP_UNKNOWN, ERR_FS_EISDIR, ERR_INVALID_ARG_TYPE, } = require('./errors.js') const { constants: { errno: { EEXIST, EISDIR, EINVAL, ENOTDIR, }, }, } = require('os') const { chmod, copyFile, lstat, mkdir, readdir, readlink, stat, symlink, unlink, utimes, } = require('fs/promises') const { dirname, isAbsolute, join, parse, resolve, sep, toNamespacedPath, } = require('path') const { fileURLToPath } = require('url') const defaultOptions = { dereference: false, errorOnExist: false, filter: undefined, force: true, preserveTimestamps: false, recursive: false, } async function cp (src, dest, opts) { if (opts != null && typeof opts !== 'object') { throw new ERR_INVALID_ARG_TYPE('options', ['Object'], opts) } return cpFn( toNamespacedPath(getValidatedPath(src)), toNamespacedPath(getValidatedPath(dest)), { ...defaultOptions, ...opts }) } function getValidatedPath (fileURLOrPath) { const path = fileURLOrPath != null && fileURLOrPath.href && fileURLOrPath.origin ? fileURLToPath(fileURLOrPath) : fileURLOrPath return path } async function cpFn (src, dest, opts) { // Warn about using preserveTimestamps on 32-bit node // istanbul ignore next if (opts.preserveTimestamps && process.arch === 'ia32') { const warning = 'Using the preserveTimestamps option in 32-bit ' + 'node is not recommended' process.emitWarning(warning, 'TimestampPrecisionWarning') } const stats = await checkPaths(src, dest, opts) const { srcStat, destStat } = stats await checkParentPaths(src, srcStat, dest) if (opts.filter) { return handleFilter(checkParentDir, destStat, src, dest, opts) } return checkParentDir(destStat, src, dest, opts) } async function checkPaths (src, dest, opts) { const { 0: srcStat, 1: destStat } = await getStats(src, dest, opts) if (destStat) { if (areIdentical(srcStat, destStat)) { throw new ERR_FS_CP_EINVAL({ message: 'src and dest cannot be the same', path: dest, syscall: 'cp', errno: EINVAL, }) } if (srcStat.isDirectory() && !destStat.isDirectory()) { throw new ERR_FS_CP_DIR_TO_NON_DIR({ message: `cannot overwrite directory ${src} ` + `with non-directory ${dest}`, path: dest, syscall: 'cp', errno: EISDIR, }) } if (!srcStat.isDirectory() && destStat.isDirectory()) { throw new ERR_FS_CP_NON_DIR_TO_DIR({ message: `cannot overwrite non-directory ${src} ` + `with directory ${dest}`, path: dest, syscall: 'cp', errno: ENOTDIR, }) } } if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { throw new ERR_FS_CP_EINVAL({ message: `cannot copy ${src} to a subdirectory of self ${dest}`, path: dest, syscall: 'cp', errno: EINVAL, }) } return { srcStat, destStat } } function areIdentical (srcStat, destStat) { return destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev } function getStats (src, dest, opts) { const statFunc = opts.dereference ? (file) => stat(file, { bigint: true }) : (file) => lstat(file, { bigint: true }) return Promise.all([ statFunc(src), statFunc(dest).catch((err) => { // istanbul ignore next: unsure how to cover. if (err.code === 'ENOENT') { return null } // istanbul ignore next: unsure how to cover. throw err }), ]) } async function checkParentDir (destStat, src, dest, opts) { const destParent = dirname(dest) const dirExists = await pathExists(destParent) if (dirExists) { return getStatsForCopy(destStat, src, dest, opts) } await mkdir(destParent, { recursive: true }) return getStatsForCopy(destStat, src, dest, opts) } function pathExists (dest) { return stat(dest).then( () => true, // istanbul ignore next: not sure when this would occur (err) => (err.code === 'ENOENT' ? false : Promise.reject(err))) } // Recursively check if dest parent is a subdirectory of src. // It works for all file types including symlinks since it // checks the src and dest inodes. It starts from the deepest // parent and stops once it reaches the src parent or the root path. async function checkParentPaths (src, srcStat, dest) { const srcParent = resolve(dirname(src)) const destParent = resolve(dirname(dest)) if (destParent === srcParent || destParent === parse(destParent).root) { return } let destStat try { destStat = await stat(destParent, { bigint: true }) } catch (err) { // istanbul ignore else: not sure when this would occur if (err.code === 'ENOENT') { return } // istanbul ignore next: not sure when this would occur throw err } if (areIdentical(srcStat, destStat)) { throw new ERR_FS_CP_EINVAL({ message: `cannot copy ${src} to a subdirectory of self ${dest}`, path: dest, syscall: 'cp', errno: EINVAL, }) } return checkParentPaths(src, srcStat, destParent) } const normalizePathToArray = (path) => resolve(path).split(sep).filter(Boolean) // Return true if dest is a subdir of src, otherwise false. // It only checks the path strings. function isSrcSubdir (src, dest) { const srcArr = normalizePathToArray(src) const destArr = normalizePathToArray(dest) return srcArr.every((cur, i) => destArr[i] === cur) } async function handleFilter (onInclude, destStat, src, dest, opts, cb) { const include = await opts.filter(src, dest) if (include) { return onInclude(destStat, src, dest, opts, cb) } } function startCopy (destStat, src, dest, opts) { if (opts.filter) { return handleFilter(getStatsForCopy, destStat, src, dest, opts) } return getStatsForCopy(destStat, src, dest, opts) } async function getStatsForCopy (destStat, src, dest, opts) { const statFn = opts.dereference ? stat : lstat const srcStat = await statFn(src) // istanbul ignore else: can't portably test FIFO if (srcStat.isDirectory() && opts.recursive) { return onDir(srcStat, destStat, src, dest, opts) } else if (srcStat.isDirectory()) { throw new ERR_FS_EISDIR({ message: `${src} is a directory (not copied)`, path: src, syscall: 'cp', errno: EINVAL, }) } else if (srcStat.isFile() || srcStat.isCharacterDevice() || srcStat.isBlockDevice()) { return onFile(srcStat, destStat, src, dest, opts) } else if (srcStat.isSymbolicLink()) { return onLink(destStat, src, dest) } else if (srcStat.isSocket()) { throw new ERR_FS_CP_SOCKET({ message: `cannot copy a socket file: ${dest}`, path: dest, syscall: 'cp', errno: EINVAL, }) } else if (srcStat.isFIFO()) { throw new ERR_FS_CP_FIFO_PIPE({ message: `cannot copy a FIFO pipe: ${dest}`, path: dest, syscall: 'cp', errno: EINVAL, }) } // istanbul ignore next: should be unreachable throw new ERR_FS_CP_UNKNOWN({ message: `cannot copy an unknown file type: ${dest}`, path: dest, syscall: 'cp', errno: EINVAL, }) } function onFile (srcStat, destStat, src, dest, opts) { if (!destStat) { return _copyFile(srcStat, src, dest, opts) } return mayCopyFile(srcStat, src, dest, opts) } async function mayCopyFile (srcStat, src, dest, opts) { if (opts.force) { await unlink(dest) return _copyFile(srcStat, src, dest, opts) } else if (opts.errorOnExist) { throw new ERR_FS_CP_EEXIST({ message: `${dest} already exists`, path: dest, syscall: 'cp', errno: EEXIST, }) } } async function _copyFile (srcStat, src, dest, opts) { await copyFile(src, dest) if (opts.preserveTimestamps) { return handleTimestampsAndMode(srcStat.mode, src, dest) } return setDestMode(dest, srcStat.mode) } async function handleTimestampsAndMode (srcMode, src, dest) { // Make sure the file is writable before setting the timestamp // otherwise open fails with EPERM when invoked with 'r+' // (through utimes call) if (fileIsNotWritable(srcMode)) { await makeFileWritable(dest, srcMode) return setDestTimestampsAndMode(srcMode, src, dest) } return setDestTimestampsAndMode(srcMode, src, dest) } function fileIsNotWritable (srcMode) { return (srcMode & 0o200) === 0 } function makeFileWritable (dest, srcMode) { return setDestMode(dest, srcMode | 0o200) } async function setDestTimestampsAndMode (srcMode, src, dest) { await setDestTimestamps(src, dest) return setDestMode(dest, srcMode) } function setDestMode (dest, srcMode) { return chmod(dest, srcMode) } async function setDestTimestamps (src, dest) { // The initial srcStat.atime cannot be trusted // because it is modified by the read(2) system call // (See https://nodejs.org/api/fs.html#fs_stat_time_values) const updatedSrcStat = await stat(src) return utimes(dest, updatedSrcStat.atime, updatedSrcStat.mtime) } function onDir (srcStat, destStat, src, dest, opts) { if (!destStat) { return mkDirAndCopy(srcStat.mode, src, dest, opts) } return copyDir(src, dest, opts) } async function mkDirAndCopy (srcMode, src, dest, opts) { await mkdir(dest) await copyDir(src, dest, opts) return setDestMode(dest, srcMode) } async function copyDir (src, dest, opts) { const dir = await readdir(src) for (let i = 0; i < dir.length; i++) { const item = dir[i] const srcItem = join(src, item) const destItem = join(dest, item) const { destStat } = await checkPaths(srcItem, destItem, opts) await startCopy(destStat, srcItem, destItem, opts) } } async function onLink (destStat, src, dest) { let resolvedSrc = await readlink(src) if (!isAbsolute(resolvedSrc)) { resolvedSrc = resolve(dirname(src), resolvedSrc) } if (!destStat) { return symlink(resolvedSrc, dest) } let resolvedDest try { resolvedDest = await readlink(dest) } catch (err) { // Dest exists and is a regular file or directory, // Windows may throw UNKNOWN error. If dest already exists, // fs throws error anyway, so no need to guard against it here. // istanbul ignore next: can only test on windows if (err.code === 'EINVAL' || err.code === 'UNKNOWN') { return symlink(resolvedSrc, dest) } // istanbul ignore next: should not be possible throw err } if (!isAbsolute(resolvedDest)) { resolvedDest = resolve(dirname(dest), resolvedDest) } if (isSrcSubdir(resolvedSrc, resolvedDest)) { throw new ERR_FS_CP_EINVAL({ message: `cannot copy ${resolvedSrc} to a subdirectory of self ` + `${resolvedDest}`, path: dest, syscall: 'cp', errno: EINVAL, }) } // Do not copy if src is a subdir of dest since unlinking // dest in this case would result in removing src contents // and therefore a broken symlink would be created. const srcStat = await stat(src) if (srcStat.isDirectory() && isSrcSubdir(resolvedDest, resolvedSrc)) { throw new ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY({ message: `cannot overwrite ${resolvedDest} with ${resolvedSrc}`, path: dest, syscall: 'cp', errno: EINVAL, }) } return copyLink(resolvedSrc, dest) } async function copyLink (resolvedSrc, dest) { await unlink(dest) return symlink(resolvedSrc, dest) } module.exports = cp PK ~\<<@npmcli/fs/lib/cp/LICENSEnu[(The MIT License) Copyright (c) 2011-2017 JP Richardson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\?@npmcli/fs/lib/cp/index.jsnu[const fs = require('fs/promises') const getOptions = require('../common/get-options.js') const node = require('../common/node.js') const polyfill = require('./polyfill.js') // node 16.7.0 added fs.cp const useNative = node.satisfies('>=16.7.0') const cp = async (src, dest, opts) => { const options = getOptions(opts, { copy: ['dereference', 'errorOnExist', 'filter', 'force', 'preserveTimestamps', 'recursive'], }) // the polyfill is tested separately from this module, no need to hack // process.version to try to trigger it just for coverage // istanbul ignore next return useNative ? fs.cp(src, dest, options) : polyfill(src, dest, options) } module.exports = cp PK ~\`mXD D @npmcli/fs/lib/cp/errors.jsnu['use strict' const { inspect } = require('util') // adapted from node's internal/errors // https://github.com/nodejs/node/blob/c8a04049/lib/internal/errors.js // close copy of node's internal SystemError class. class SystemError { constructor (code, prefix, context) { // XXX context.code is undefined in all constructors used in cp/polyfill // that may be a bug copied from node, maybe the constructor should use // `code` not `errno`? nodejs/node#41104 let message = `${prefix}: ${context.syscall} returned ` + `${context.code} (${context.message})` if (context.path !== undefined) { message += ` ${context.path}` } if (context.dest !== undefined) { message += ` => ${context.dest}` } this.code = code Object.defineProperties(this, { name: { value: 'SystemError', enumerable: false, writable: true, configurable: true, }, message: { value: message, enumerable: false, writable: true, configurable: true, }, info: { value: context, enumerable: true, configurable: true, writable: false, }, errno: { get () { return context.errno }, set (value) { context.errno = value }, enumerable: true, configurable: true, }, syscall: { get () { return context.syscall }, set (value) { context.syscall = value }, enumerable: true, configurable: true, }, }) if (context.path !== undefined) { Object.defineProperty(this, 'path', { get () { return context.path }, set (value) { context.path = value }, enumerable: true, configurable: true, }) } if (context.dest !== undefined) { Object.defineProperty(this, 'dest', { get () { return context.dest }, set (value) { context.dest = value }, enumerable: true, configurable: true, }) } } toString () { return `${this.name} [${this.code}]: ${this.message}` } [Symbol.for('nodejs.util.inspect.custom')] (_recurseTimes, ctx) { return inspect(this, { ...ctx, getters: true, customInspect: false, }) } } function E (code, message) { module.exports[code] = class NodeError extends SystemError { constructor (ctx) { super(code, message, ctx) } } } E('ERR_FS_CP_DIR_TO_NON_DIR', 'Cannot overwrite directory with non-directory') E('ERR_FS_CP_EEXIST', 'Target already exists') E('ERR_FS_CP_EINVAL', 'Invalid src or dest') E('ERR_FS_CP_FIFO_PIPE', 'Cannot copy a FIFO pipe') E('ERR_FS_CP_NON_DIR_TO_DIR', 'Cannot overwrite non-directory with directory') E('ERR_FS_CP_SOCKET', 'Cannot copy a socket file') E('ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY', 'Cannot overwrite symlink in subdirectory of self') E('ERR_FS_CP_UNKNOWN', 'Cannot copy an unknown file type') E('ERR_FS_EISDIR', 'Path is a directory') module.exports.ERR_INVALID_ARG_TYPE = class ERR_INVALID_ARG_TYPE extends Error { constructor (name, expected, actual) { super() this.code = 'ERR_INVALID_ARG_TYPE' this.message = `The ${name} argument must be ${expected}. Received ${typeof actual}` } } PK ~\  @npmcli/fs/lib/readdir-scoped.jsnu[const { readdir } = require('fs/promises') const { join } = require('path') const readdirScoped = async (dir) => { const results = [] for (const item of await readdir(dir)) { if (item.startsWith('@')) { for (const scopedItem of await readdir(join(dir, item))) { results.push(join(item, scopedItem)) } } else { results.push(item) } } return results } module.exports = readdirScoped PK ~\I  @npmcli/fs/lib/index.jsnu['use strict' const cp = require('./cp/index.js') const withTempDir = require('./with-temp-dir.js') const readdirScoped = require('./readdir-scoped.js') const moveFile = require('./move-file.js') module.exports = { cp, withTempDir, readdirScoped, moveFile, } PK ~\L΄@npmcli/fs/lib/with-temp-dir.jsnu[const { join, sep } = require('path') const getOptions = require('./common/get-options.js') const { mkdir, mkdtemp, rm } = require('fs/promises') // create a temp directory, ensure its permissions match its parent, then call // the supplied function passing it the path to the directory. clean up after // the function finishes, whether it throws or not const withTempDir = async (root, fn, opts) => { const options = getOptions(opts, { copy: ['tmpPrefix'], }) // create the directory await mkdir(root, { recursive: true }) const target = await mkdtemp(join(`${root}${sep}`, options.tmpPrefix || '')) let err let result try { result = await fn(target) } catch (_err) { err = _err } try { await rm(target, { force: true, recursive: true }) } catch { // ignore errors } if (err) { throw err } return result } module.exports = withTempDir PK ~\i$@npmcli/fs/lib/common/get-options.jsnu[// given an input that may or may not be an object, return an object that has // a copy of every defined property listed in 'copy'. if the input is not an // object, assign it to the property named by 'wrap' const getOptions = (input, { copy, wrap }) => { const result = {} if (input && typeof input === 'object') { for (const prop of copy) { if (input[prop] !== undefined) { result[prop] = input[prop] } } } else { result[wrap] = input } return result } module.exports = getOptions PK ~\#@npmcli/fs/lib/common/node.jsnu[const semver = require('semver') const satisfies = (range) => { return semver.satisfies(process.version, range, { includePrerelease: true }) } module.exports = { satisfies, } PK ~\r@npmcli/fs/LICENSE.mdnu[ ISC License Copyright npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND NPM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NPM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\\dmm@npmcli/query/package.jsonnu[{ "_id": "@npmcli/query@3.1.0", "_inBundle": true, "_location": "/npm/@npmcli/query", "_phantomChildren": {}, "_requiredBy": [ "/npm/@npmcli/arborist" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/query/issues" }, "contributors": [ { "name": "Ruy Adorno", "url": "https://ruyadorno.com" } ], "dependencies": { "postcss-selector-parser": "^6.0.10" }, "description": "npm query parser and tools", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.21.3", "tap": "^16.2.0" }, "engines": { "node": "^14.17.0 || ^16.13.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/query#readme", "keywords": [ "ast", "npm", "npmcli", "parser", "postcss", "postcss-selector-parser", "query" ], "license": "ISC", "main": "lib/index.js", "name": "@npmcli/query", "repository": { "type": "git", "url": "git+https://github.com/npm/query.git" }, "scripts": { "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.21.3", "publish": true }, "version": "3.1.0" } PK ~\붾 @npmcli/query/lib/index.jsnu['use strict' const parser = require('postcss-selector-parser') const arrayDelimiter = Symbol('arrayDelimiter') const escapeSlashes = str => str.replace(/\//g, '\\/') const unescapeSlashes = str => str.replace(/\\\//g, '/') // recursively fixes up any :attr pseudo-class found const fixupAttr = astNode => { const properties = [] const matcher = {} for (const selectorAstNode of astNode.nodes) { const [firstAstNode] = selectorAstNode.nodes if (firstAstNode.type === 'tag') { properties.push(firstAstNode.value) } } const lastSelectorAstNode = astNode.nodes.pop() const [attributeAstNode] = lastSelectorAstNode.nodes if (attributeAstNode.value === ':attr') { const appendParts = fixupAttr(attributeAstNode) properties.push(arrayDelimiter, ...appendParts.lookupProperties) matcher.qualifiedAttribute = appendParts.attributeMatcher.qualifiedAttribute matcher.operator = appendParts.attributeMatcher.operator matcher.value = appendParts.attributeMatcher.value // backwards compatibility matcher.attribute = appendParts.attributeMatcher.attribute if (appendParts.attributeMatcher.insensitive) { matcher.insensitive = true } } else { if (attributeAstNode.type !== 'attribute') { throw Object.assign( new Error('`:attr` pseudo-class expects an attribute matcher as the last value'), { code: 'EQUERYATTR' } ) } matcher.qualifiedAttribute = unescapeSlashes(attributeAstNode.qualifiedAttribute) matcher.operator = attributeAstNode.operator matcher.value = attributeAstNode.value // backwards compatibility matcher.attribute = matcher.qualifiedAttribute if (attributeAstNode.insensitive) { matcher.insensitive = true } } astNode.lookupProperties = properties astNode.attributeMatcher = matcher astNode.nodes.length = 0 return astNode } // fixed up nested pseudo nodes will have their internal selectors moved // to a new root node that will be referenced by the `nestedNode` property, // this tweak makes it simpler to reuse `retrieveNodesFromParsedAst` to // recursively parse and extract results from the internal selectors const fixupNestedPseudo = astNode => { // create a new ast root node and relocate any children // selectors of the current ast node to this new root const newRootNode = parser.root() astNode.nestedNode = newRootNode newRootNode.nodes = [...astNode.nodes] // clean up the ast by removing the children nodes from the // current ast node while also cleaning up their `parent` refs astNode.nodes.length = 0 for (const currAstNode of newRootNode.nodes) { currAstNode.parent = newRootNode } // recursively fixup nodes of any nested selector transformAst(newRootNode) } // :semver(, [version|range|selector], [function]) // note: the first or second parameter must be a static version or range const fixupSemverSpecs = astNode => { // if we have three nodes, the last is the semver function to use, pull that out first if (astNode.nodes.length === 3) { const funcNode = astNode.nodes.pop().nodes[0] if (funcNode.type === 'tag') { astNode.semverFunc = funcNode.value } else if (funcNode.type === 'string') { // a string is always in some type of quotes, we don't want those so slice them off astNode.semverFunc = funcNode.value.slice(1, -1) } else { // anything that isn't a tag or a string isn't a function name throw Object.assign( new Error('`:semver` pseudo-class expects a function name as last value'), { code: 'ESEMVERFUNC' } ) } } // now if we have 1 node, it's a static value // istanbul ignore else if (astNode.nodes.length === 1) { const semverNode = astNode.nodes.pop() astNode.semverValue = semverNode.nodes.reduce((res, next) => `${res}${String(next)}`, '') } else if (astNode.nodes.length === 2) { // and if we have two nodes, one of them is a static value and we need to determine which it is for (let i = 0; i < astNode.nodes.length; ++i) { const type = astNode.nodes[i].nodes[0].type // the type of the first child may be combinator for ranges, such as >14 if (type === 'tag' || type === 'combinator') { const semverNode = astNode.nodes.splice(i, 1)[0] astNode.semverValue = semverNode.nodes.reduce((res, next) => `${res}${String(next)}`, '') astNode.semverPosition = i break } } if (typeof astNode.semverValue === 'undefined') { throw Object.assign( new Error('`:semver` pseudo-class expects a static value in the first or second position'), { code: 'ESEMVERVALUE' } ) } } // if we got here, the last remaining child should be attribute selector if (astNode.nodes.length === 1) { fixupAttr(astNode) } else { // if we don't have a selector, we default to `[version]` astNode.attributeMatcher = { insensitive: false, attribute: 'version', qualifiedAttribute: 'version', } astNode.lookupProperties = [] } astNode.nodes.length = 0 } const fixupTypes = astNode => { const [valueAstNode] = astNode.nodes[0].nodes const { value } = valueAstNode || {} astNode.typeValue = value astNode.nodes.length = 0 } const fixupPaths = astNode => { astNode.pathValue = unescapeSlashes(String(astNode.nodes[0])) astNode.nodes.length = 0 } const fixupOutdated = astNode => { if (astNode.nodes.length) { astNode.outdatedKind = String(astNode.nodes[0]) astNode.nodes.length = 0 } } const fixupVuln = astNode => { const vulns = [] if (astNode.nodes.length) { for (const selector of astNode.nodes) { const vuln = {} for (const node of selector.nodes) { if (node.type !== 'attribute') { throw Object.assign( new Error(':vuln pseudo-class only accepts attribute matchers or "cwe" tag'), { code: 'EQUERYATTR' } ) } if (!['severity', 'cwe'].includes(node._attribute)) { throw Object.assign( new Error(':vuln pseudo-class only matches "severity" and "cwe" attributes'), { code: 'EQUERYATTR' } ) } if (!node.operator) { node.operator = '=' node.value = '*' } if (node.operator !== '=') { throw Object.assign( new Error(':vuln pseudo-class attribute selector only accepts "=" operator', node), { code: 'EQUERYATTR' } ) } if (!vuln[node._attribute]) { vuln[node._attribute] = [] } vuln[node._attribute].push(node._value) } vulns.push(vuln) } astNode.vulns = vulns astNode.nodes.length = 0 } } // a few of the supported ast nodes need to be tweaked in order to properly be // interpreted as proper arborist query selectors, namely semver ranges from // both ids and :semver pseudo-class selectors need to be translated from what // are usually multiple ast nodes, such as: tag:1, class:.0, class:.0 to a // single `1.0.0` value, other pseudo-class selectors also get preprocessed in // order to make it simpler to execute later when traversing each ast node // using rootNode.walk(), such as :path, :type, etc. transformAst handles all // these modifications to the parsed ast by doing an extra, initial traversal // of the parsed ast from the query and modifying the parsed nodes accordingly const transformAst = selector => { selector.walk((nextAstNode) => { switch (nextAstNode.value) { case ':attr': return fixupAttr(nextAstNode) case ':is': case ':has': case ':not': return fixupNestedPseudo(nextAstNode) case ':path': return fixupPaths(nextAstNode) case ':semver': return fixupSemverSpecs(nextAstNode) case ':type': return fixupTypes(nextAstNode) case ':outdated': return fixupOutdated(nextAstNode) case ':vuln': return fixupVuln(nextAstNode) } }) } const queryParser = (query) => { // if query is an empty string or any falsy // value, just returns an empty result if (!query) { return [] } return parser(transformAst) .astSync(escapeSlashes(query), { lossless: false }) } module.exports = { parser: queryParser, arrayDelimiter, } PK ~\r@npmcli/query/LICENSEnu[ ISC License Copyright npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND NPM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NPM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\R|@npmcli/run-script/package.jsonnu[{ "_id": "@npmcli/run-script@8.1.0", "_inBundle": true, "_location": "/npm/@npmcli/run-script", "_phantomChildren": {}, "_requiredBy": [ "/npm", "/npm/@npmcli/arborist", "/npm/libnpmexec", "/npm/libnpmpack", "/npm/libnpmversion", "/npm/pacote" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/run-script/issues" }, "dependencies": { "@npmcli/node-gyp": "^3.0.0", "@npmcli/package-json": "^5.0.0", "@npmcli/promise-spawn": "^7.0.0", "node-gyp": "^10.0.0", "proc-log": "^4.0.0", "which": "^4.0.0" }, "description": "Run a lifecycle script for a package (descendant of npm-lifecycle)", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.21.4", "spawk": "^1.8.1", "tap": "^16.0.1" }, "engines": { "node": "^16.14.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/run-script#readme", "license": "ISC", "main": "lib/run-script.js", "name": "@npmcli/run-script", "repository": { "type": "git", "url": "git+https://github.com/npm/run-script.git" }, "scripts": { "eslint": "eslint", "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.21.4", "publish": "true" }, "version": "8.1.0" } PK ~\ϖ&(@npmcli/run-script/lib/signal-manager.jsnu[const runningProcs = new Set() let handlersInstalled = false const forwardedSignals = [ 'SIGINT', 'SIGTERM', ] // no-op, this is so receiving the signal doesn't cause us to exit immediately // instead, we exit after all children have exited when we re-send the signal // to ourselves. see the catch handler at the bottom of run-script-pkg.js const handleSignal = signal => { for (const proc of runningProcs) { proc.kill(signal) } } const setupListeners = () => { for (const signal of forwardedSignals) { process.on(signal, handleSignal) } handlersInstalled = true } const cleanupListeners = () => { if (runningProcs.size === 0) { for (const signal of forwardedSignals) { process.removeListener(signal, handleSignal) } handlersInstalled = false } } const add = proc => { runningProcs.add(proc) if (!handlersInstalled) { setupListeners() } proc.once('exit', () => { runningProcs.delete(proc) cleanupListeners() }) } module.exports = { add, handleSignal, forwardedSignals, } PK ~\;{$@npmcli/run-script/lib/run-script.jsnu[const PackageJson = require('@npmcli/package-json') const runScriptPkg = require('./run-script-pkg.js') const validateOptions = require('./validate-options.js') const isServerPackage = require('./is-server-package.js') const runScript = async options => { validateOptions(options) if (options.pkg) { return runScriptPkg(options) } const { content: pkg } = await PackageJson.normalize(options.path) return runScriptPkg({ ...options, pkg }) } module.exports = Object.assign(runScript, { isServerPackage }) PK ~\SF//)@npmcli/run-script/lib/make-spawn-args.jsnu[/* eslint camelcase: "off" */ const setPATH = require('./set-path.js') const { resolve } = require('path') const npm_config_node_gyp = require.resolve('node-gyp/bin/node-gyp.js') const makeSpawnArgs = options => { const { event, path, scriptShell = true, binPaths, env, stdio, cmd, args, stdioString, } = options const spawnEnv = setPATH(path, binPaths, { // we need to at least save the PATH environment var ...process.env, ...env, npm_package_json: resolve(path, 'package.json'), npm_lifecycle_event: event, npm_lifecycle_script: cmd, npm_config_node_gyp, }) const spawnOpts = { env: spawnEnv, stdioString, stdio, cwd: path, shell: scriptShell, } return [cmd, args, spawnOpts] } module.exports = makeSpawnArgs PK ~\C::&@npmcli/run-script/lib/package-envs.jsnu[const packageEnvs = (vals, prefix, env = {}) => { for (const [key, val] of Object.entries(vals)) { if (val === undefined) { continue } else if (val === null || val === false) { env[`${prefix}${key}`] = '' } else if (Array.isArray(val)) { val.forEach((item, index) => { packageEnvs({ [`${key}_${index}`]: item }, `${prefix}`, env) }) } else if (typeof val === 'object') { packageEnvs(val, `${prefix}${key}_`, env) } else { env[`${prefix}${key}`] = String(val) } } return env } // https://github.com/npm/rfcs/pull/183 defines which fields we put into the environment module.exports = pkg => { return packageEnvs({ name: pkg.name, version: pkg.version, config: pkg.config, engines: pkg.engines, bin: pkg.bin, }, 'npm_package_') } PK ~\GI""0@npmcli/run-script/lib/node-gyp-bin/node-gyp.cmdnu[@node "%npm_config_node_gyp%" %* PK ~\ଳ33,@npmcli/run-script/lib/node-gyp-bin/node-gypnu[#!/usr/bin/env sh node "$npm_config_node_gyp" "$@" PK ~\n|K="@npmcli/run-script/lib/set-path.jsnu[const { resolve, dirname, delimiter } = require('path') // the path here is relative, even though it does not need to be // in order to make the posix tests pass in windows const nodeGypPath = resolve(__dirname, '../lib/node-gyp-bin') // Windows typically calls its PATH environ 'Path', but this is not // guaranteed, nor is it guaranteed to be the only one. Merge them // all together in the order they appear in the object. const setPATH = (projectPath, binPaths, env) => { const PATH = Object.keys(env).filter(p => /^path$/i.test(p) && env[p]) .map(p => env[p].split(delimiter)) .reduce((set, p) => set.concat(p.filter(concatted => !set.includes(concatted))), []) .join(delimiter) const pathArr = [] if (binPaths) { pathArr.push(...binPaths) } // unshift the ./node_modules/.bin from every folder // walk up until dirname() does nothing, at the root // XXX we should specify a cwd that we don't go above let p = projectPath let pp do { pathArr.push(resolve(p, 'node_modules', '.bin')) pp = p p = dirname(p) } while (p !== pp) pathArr.push(nodeGypPath, PATH) const pathVal = pathArr.join(delimiter) // XXX include the node-gyp-bin path somehow? Probably better for // npm or arborist or whoever to just provide that by putting it in // the PATH environ, since that's preserved anyway. for (const key of Object.keys(env)) { if (/^path$/i.test(key)) { env[key] = pathVal } } return env } module.exports = setPATH PK ~\E_*@npmcli/run-script/lib/validate-options.jsnu[const validateOptions = options => { if (typeof options !== 'object' || !options) { throw new TypeError('invalid options object provided to runScript') } const { event, path, scriptShell, env = {}, stdio = 'pipe', args = [], cmd, } = options if (!event || typeof event !== 'string') { throw new TypeError('valid event not provided to runScript') } if (!path || typeof path !== 'string') { throw new TypeError('valid path not provided to runScript') } if (scriptShell !== undefined && typeof scriptShell !== 'string') { throw new TypeError('invalid scriptShell option provided to runScript') } if (typeof env !== 'object' || !env) { throw new TypeError('invalid env option provided to runScript') } if (typeof stdio !== 'string' && !Array.isArray(stdio)) { throw new TypeError('invalid stdio option provided to runScript') } if (!Array.isArray(args) || args.some(a => typeof a !== 'string')) { throw new TypeError('invalid args option provided to runScript') } if (cmd !== undefined && typeof cmd !== 'string') { throw new TypeError('invalid cmd option provided to runScript') } } module.exports = validateOptions PK ~\O# (@npmcli/run-script/lib/run-script-pkg.jsnu[const makeSpawnArgs = require('./make-spawn-args.js') const promiseSpawn = require('@npmcli/promise-spawn') const packageEnvs = require('./package-envs.js') const { isNodeGypPackage, defaultGypInstallScript } = require('@npmcli/node-gyp') const signalManager = require('./signal-manager.js') const isServerPackage = require('./is-server-package.js') const runScriptPkg = async options => { const { event, path, scriptShell, binPaths = false, env = {}, stdio = 'pipe', pkg, args = [], stdioString, // how long to wait for a process.kill signal // only exposed here so that we can make the test go a bit faster. signalTimeout = 500, } = options const { scripts = {}, gypfile } = pkg let cmd = null if (options.cmd) { cmd = options.cmd } else if (pkg.scripts && pkg.scripts[event]) { cmd = pkg.scripts[event] } else if ( // If there is no preinstall or install script, default to rebuilding node-gyp packages. event === 'install' && !scripts.install && !scripts.preinstall && gypfile !== false && await isNodeGypPackage(path) ) { cmd = defaultGypInstallScript } else if (event === 'start' && await isServerPackage(path)) { cmd = 'node server.js' } if (!cmd) { return { code: 0, signal: null } } let inputEnd = () => {} if (stdio === 'inherit') { let banner if (pkg._id) { banner = `\n> ${pkg._id} ${event}\n` } else { banner = `\n> ${event}\n` } banner += `> ${cmd.trim().replace(/\n/g, '\n> ')}` if (args.length) { banner += ` ${args.join(' ')}` } banner += '\n' const { output, input } = require('proc-log') output.standard(banner) inputEnd = input.start() } const [spawnShell, spawnArgs, spawnOpts] = makeSpawnArgs({ event, path, scriptShell, binPaths, env: { ...env, ...packageEnvs(pkg) }, stdio, cmd, args, stdioString, }) const p = promiseSpawn(spawnShell, spawnArgs, spawnOpts, { event, script: cmd, pkgid: pkg._id, path, }) if (stdio === 'inherit') { signalManager.add(p.process) } if (p.stdin) { p.stdin.end() } return p.catch(er => { const { signal } = er // coverage disabled because win32 never emits signals /* istanbul ignore next */ if (stdio === 'inherit' && signal) { // by the time we reach here, the child has already exited. we send the // signal back to ourselves again so that npm will exit with the same // status as the child process.kill(process.pid, signal) // just in case we don't die, reject after 500ms // this also keeps the node process open long enough to actually // get the signal, rather than terminating gracefully. return new Promise((res, rej) => setTimeout(() => rej(er), signalTimeout)) } else { throw er } }).finally(inputEnd) } module.exports = runScriptPkg PK ~\o { try { const st = await stat(resolve(path, 'server.js')) return st.isFile() } catch (er) { return false } } PK ~\.9@npmcli/run-script/LICENSEnu[The ISC License Copyright (c) npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\`L@npmcli/git/package.jsonnu[{ "_id": "@npmcli/git@5.0.7", "_inBundle": true, "_location": "/npm/@npmcli/git", "_phantomChildren": {}, "_requiredBy": [ "/npm/@npmcli/package-json", "/npm/libnpmversion", "/npm/pacote" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/git/issues" }, "dependencies": { "@npmcli/promise-spawn": "^7.0.0", "lru-cache": "^10.0.1", "npm-pick-manifest": "^9.0.0", "proc-log": "^4.0.0", "promise-inflight": "^1.0.1", "promise-retry": "^2.0.1", "semver": "^7.3.5", "which": "^4.0.0" }, "description": "a util for spawning git from npm CLI contexts", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.22.0", "npm-package-arg": "^11.0.0", "slash": "^3.0.0", "tap": "^16.0.1" }, "engines": { "node": "^16.14.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/git#readme", "license": "ISC", "main": "lib/index.js", "name": "@npmcli/git", "repository": { "type": "git", "url": "git+https://github.com/npm/git.git" }, "scripts": { "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "timeout": 600, "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.22.0", "publish": true }, "version": "5.0.7" } PK ~\E2mm@npmcli/git/lib/utils.jsnu[const isWindows = opts => (opts.fakePlatform || process.platform) === 'win32' exports.isWindows = isWindows PK ~\T1I]]@npmcli/git/lib/make-error.jsnu[const { GitConnectionError, GitPathspecError, GitUnknownError, } = require('./errors.js') const connectionErrorRe = new RegExp([ 'remote error: Internal Server Error', 'The remote end hung up unexpectedly', 'Connection timed out', 'Operation timed out', 'Failed to connect to .* Timed out', 'Connection reset by peer', 'SSL_ERROR_SYSCALL', 'The requested URL returned error: 503', ].join('|')) const missingPathspecRe = /pathspec .* did not match any file\(s\) known to git/ function makeError (er) { const message = er.stderr let gitEr if (connectionErrorRe.test(message)) { gitEr = new GitConnectionError(message) } else if (missingPathspecRe.test(message)) { gitEr = new GitPathspecError(message) } else { gitEr = new GitUnknownError(message) } return Object.assign(gitEr, er) } module.exports = makeError PK ~\zII@npmcli/git/lib/clone.jsnu[// The goal here is to minimize both git workload and // the number of refs we download over the network. // // Every method ends up with the checked out working dir // at the specified ref, and resolves with the git sha. // Only certain whitelisted hosts get shallow cloning. // Many hosts (including GHE) don't always support it. // A failed shallow fetch takes a LOT longer than a full // fetch in most cases, so we skip it entirely. // Set opts.gitShallow = true/false to force this behavior // one way or the other. const shallowHosts = new Set([ 'github.com', 'gist.github.com', 'gitlab.com', 'bitbucket.com', 'bitbucket.org', ]) // we have to use url.parse until we add the same shim that hosted-git-info has // to handle scp:// urls const { parse } = require('url') // eslint-disable-line node/no-deprecated-api const path = require('path') const getRevs = require('./revs.js') const spawn = require('./spawn.js') const { isWindows } = require('./utils.js') const pickManifest = require('npm-pick-manifest') const fs = require('fs/promises') module.exports = (repo, ref = 'HEAD', target = null, opts = {}) => getRevs(repo, opts).then(revs => clone( repo, revs, ref, resolveRef(revs, ref, opts), target || defaultTarget(repo, opts.cwd), opts )) const maybeShallow = (repo, opts) => { if (opts.gitShallow === false || opts.gitShallow) { return opts.gitShallow } return shallowHosts.has(parse(repo).host) } const defaultTarget = (repo, /* istanbul ignore next */ cwd = process.cwd()) => path.resolve(cwd, path.basename(repo.replace(/[/\\]?\.git$/, ''))) const clone = (repo, revs, ref, revDoc, target, opts) => { if (!revDoc) { return unresolved(repo, ref, target, opts) } if (revDoc.sha === revs.refs.HEAD.sha) { return plain(repo, revDoc, target, opts) } if (revDoc.type === 'tag' || revDoc.type === 'branch') { return branch(repo, revDoc, target, opts) } return other(repo, revDoc, target, opts) } const resolveRef = (revs, ref, opts) => { const { spec = {} } = opts ref = spec.gitCommittish || ref /* istanbul ignore next - will fail anyway, can't pull */ if (!revs) { return null } if (spec.gitRange) { return pickManifest(revs, spec.gitRange, opts) } if (!ref) { return revs.refs.HEAD } if (revs.refs[ref]) { return revs.refs[ref] } if (revs.shas[ref]) { return revs.refs[revs.shas[ref][0]] } return null } // pull request or some other kind of advertised ref const other = (repo, revDoc, target, opts) => { const shallow = maybeShallow(repo, opts) const fetchOrigin = ['fetch', 'origin', revDoc.rawRef] .concat(shallow ? ['--depth=1'] : []) const git = (args) => spawn(args, { ...opts, cwd: target }) return fs.mkdir(target, { recursive: true }) .then(() => git(['init'])) .then(() => isWindows(opts) ? git(['config', '--local', '--add', 'core.longpaths', 'true']) : null) .then(() => git(['remote', 'add', 'origin', repo])) .then(() => git(fetchOrigin)) .then(() => git(['checkout', revDoc.sha])) .then(() => updateSubmodules(target, opts)) .then(() => revDoc.sha) } // tag or branches. use -b const branch = (repo, revDoc, target, opts) => { const args = [ 'clone', '-b', revDoc.ref, repo, target, '--recurse-submodules', ] if (maybeShallow(repo, opts)) { args.push('--depth=1') } if (isWindows(opts)) { args.push('--config', 'core.longpaths=true') } return spawn(args, opts).then(() => revDoc.sha) } // just the head. clone it const plain = (repo, revDoc, target, opts) => { const args = [ 'clone', repo, target, '--recurse-submodules', ] if (maybeShallow(repo, opts)) { args.push('--depth=1') } if (isWindows(opts)) { args.push('--config', 'core.longpaths=true') } return spawn(args, opts).then(() => revDoc.sha) } const updateSubmodules = async (target, opts) => { const hasSubmodules = await fs.stat(`${target}/.gitmodules`) .then(() => true) .catch(() => false) if (!hasSubmodules) { return null } return spawn([ 'submodule', 'update', '-q', '--init', '--recursive', ], { ...opts, cwd: target }) } const unresolved = (repo, ref, target, opts) => { // can't do this one shallowly, because the ref isn't advertised // but we can avoid checking out the working dir twice, at least const lp = isWindows(opts) ? ['--config', 'core.longpaths=true'] : [] const cloneArgs = ['clone', '--mirror', '-q', repo, target + '/.git'] const git = (args) => spawn(args, { ...opts, cwd: target }) return fs.mkdir(target, { recursive: true }) .then(() => git(cloneArgs.concat(lp))) .then(() => git(['init'])) .then(() => git(['checkout', ref])) .then(() => updateSubmodules(target, opts)) .then(() => git(['rev-parse', '--revs-only', 'HEAD'])) .then(({ stdout }) => stdout.trim()) } PK ~\y<@npmcli/git/lib/is.jsnu[// not an airtight indicator, but a good gut-check to even bother trying const { stat } = require('fs/promises') module.exports = ({ cwd = process.cwd() } = {}) => stat(cwd + '/.git').then(() => true, () => false) PK ~\]@npmcli/git/lib/spawn.jsnu[const spawn = require('@npmcli/promise-spawn') const promiseRetry = require('promise-retry') const { log } = require('proc-log') const makeError = require('./make-error.js') const makeOpts = require('./opts.js') module.exports = (gitArgs, opts = {}) => { const whichGit = require('./which.js') const gitPath = whichGit(opts) if (gitPath instanceof Error) { return Promise.reject(gitPath) } // undocumented option, mostly only here for tests const args = opts.allowReplace || gitArgs[0] === '--no-replace-objects' ? gitArgs : ['--no-replace-objects', ...gitArgs] let retryOpts = opts.retry if (retryOpts === null || retryOpts === undefined) { retryOpts = { retries: opts.fetchRetries || 2, factor: opts.fetchRetryFactor || 10, maxTimeout: opts.fetchRetryMaxtimeout || 60000, minTimeout: opts.fetchRetryMintimeout || 1000, } } return promiseRetry((retryFn, number) => { if (number !== 1) { log.silly('git', `Retrying git command: ${ args.join(' ')} attempt # ${number}`) } return spawn(gitPath, args, makeOpts(opts)) .catch(er => { const gitError = makeError(er) if (!gitError.shouldRetry(number)) { throw gitError } retryFn(gitError) }) }, retryOpts) } PK ~\@K@npmcli/git/lib/index.jsnu[module.exports = { clone: require('./clone.js'), revs: require('./revs.js'), spawn: require('./spawn.js'), is: require('./is.js'), find: require('./find.js'), isClean: require('./is-clean.js'), errors: require('./errors.js'), } PK ~\o@npmcli/git/lib/is-clean.jsnu[const spawn = require('./spawn.js') module.exports = (opts = {}) => spawn(['status', '--porcelain=v1', '-uno'], opts) .then(res => !res.stdout.trim().split(/\r?\n+/) .map(l => l.trim()).filter(l => l).length) PK ~\U CC@npmcli/git/lib/errors.jsnu[ const maxRetry = 3 class GitError extends Error { shouldRetry () { return false } } class GitConnectionError extends GitError { constructor () { super('A git connection error occurred') } shouldRetry (number) { return number < maxRetry } } class GitPathspecError extends GitError { constructor () { super('The git reference could not be found') } } class GitUnknownError extends GitError { constructor () { super('An unknown git error occurred') } } module.exports = { GitConnectionError, GitPathspecError, GitUnknownError, } PK ~\]n @npmcli/git/lib/lines-to-revs.jsnu[// turn an array of lines from `git ls-remote` into a thing // vaguely resembling a packument, where docs are a resolved ref const semver = require('semver') module.exports = lines => finish(lines.reduce(linesToRevsReducer, { versions: {}, 'dist-tags': {}, refs: {}, shas: {}, })) const finish = revs => distTags(shaList(peelTags(revs))) // We can check out shallow clones on specific SHAs if we have a ref const shaList = revs => { Object.keys(revs.refs).forEach(ref => { const doc = revs.refs[ref] if (!revs.shas[doc.sha]) { revs.shas[doc.sha] = [ref] } else { revs.shas[doc.sha].push(ref) } }) return revs } // Replace any tags with their ^{} counterparts, if those exist const peelTags = revs => { Object.keys(revs.refs).filter(ref => ref.endsWith('^{}')).forEach(ref => { const peeled = revs.refs[ref] const unpeeled = revs.refs[ref.replace(/\^\{\}$/, '')] if (unpeeled) { unpeeled.sha = peeled.sha delete revs.refs[ref] } }) return revs } const distTags = revs => { // not entirely sure what situations would result in an // ichabod repo, but best to be careful in Sleepy Hollow anyway const HEAD = revs.refs.HEAD || /* istanbul ignore next */ {} const versions = Object.keys(revs.versions) versions.forEach(v => { // simulate a dist-tags with latest pointing at the // 'latest' branch if one exists and is a version, // or HEAD if not. const ver = revs.versions[v] if (revs.refs.latest && ver.sha === revs.refs.latest.sha) { revs['dist-tags'].latest = v } else if (ver.sha === HEAD.sha) { revs['dist-tags'].HEAD = v if (!revs.refs.latest) { revs['dist-tags'].latest = v } } }) return revs } const refType = ref => { if (ref.startsWith('refs/tags/')) { return 'tag' } if (ref.startsWith('refs/heads/')) { return 'branch' } if (ref.startsWith('refs/pull/')) { return 'pull' } if (ref === 'HEAD') { return 'head' } // Could be anything, ignore for now /* istanbul ignore next */ return 'other' } // return the doc, or null if we should ignore it. const lineToRevDoc = line => { const split = line.trim().split(/\s+/, 2) if (split.length < 2) { return null } const sha = split[0].trim() const rawRef = split[1].trim() const type = refType(rawRef) if (type === 'tag') { // refs/tags/foo^{} is the 'peeled tag', ie the commit // that is tagged by refs/tags/foo they resolve to the same // content, just different objects in git's data structure. // But, we care about the thing the tag POINTS to, not the tag // object itself, so we only look at the peeled tag refs, and // ignore the pointer. // For now, though, we have to save both, because some tags // don't have peels, if they were not annotated. const ref = rawRef.slice('refs/tags/'.length) return { sha, ref, rawRef, type } } if (type === 'branch') { const ref = rawRef.slice('refs/heads/'.length) return { sha, ref, rawRef, type } } if (type === 'pull') { // NB: merged pull requests installable with #pull/123/merge // for the merged pr, or #pull/123 for the PR head const ref = rawRef.slice('refs/'.length).replace(/\/head$/, '') return { sha, ref, rawRef, type } } if (type === 'head') { const ref = 'HEAD' return { sha, ref, rawRef, type } } // at this point, all we can do is leave the ref un-munged return { sha, ref: rawRef, rawRef, type } } const linesToRevsReducer = (revs, line) => { const doc = lineToRevDoc(line) if (!doc) { return revs } revs.refs[doc.ref] = doc revs.refs[doc.rawRef] = doc if (doc.type === 'tag') { // try to pull a semver value out of tags like `release-v1.2.3` // which is a pretty common pattern. const match = !doc.ref.endsWith('^{}') && doc.ref.match(/v?(\d+\.\d+\.\d+(?:[-+].+)?)$/) if (match && semver.valid(match[1], true)) { revs.versions[semver.clean(match[1], true)] = doc } } return revs } PK ~\s2SS@npmcli/git/lib/which.jsnu[const which = require('which') let gitPath try { gitPath = which.sync('git') } catch { // ignore errors } module.exports = (opts = {}) => { if (opts.git) { return opts.git } if (!gitPath || opts.git === false) { return Object.assign(new Error('No git binary found in $PATH'), { code: 'ENOGIT' }) } return gitPath } PK ~\[l{<<@npmcli/git/lib/find.jsnu[const is = require('./is.js') const { dirname } = require('path') module.exports = async ({ cwd = process.cwd(), root } = {}) => { while (true) { if (await is({ cwd })) { return cwd } const next = dirname(cwd) if (cwd === root || cwd === next) { return null } cwd = next } } PK ~\D@npmcli/git/lib/revs.jsnu[const pinflight = require('promise-inflight') const spawn = require('./spawn.js') const { LRUCache } = require('lru-cache') const revsCache = new LRUCache({ max: 100, ttl: 5 * 60 * 1000, }) const linesToRevs = require('./lines-to-revs.js') module.exports = async (repo, opts = {}) => { if (!opts.noGitRevCache) { const cached = revsCache.get(repo) if (cached) { return cached } } return pinflight(`ls-remote:${repo}`, () => spawn(['ls-remote', repo], opts) .then(({ stdout }) => linesToRevs(stdout.trim().split('\n'))) .then(revs => { revsCache.set(repo, revs) return revs }) ) } PK ~\Sss@npmcli/git/lib/opts.jsnu[// Values we want to set if they're not already defined by the end user // This defaults to accepting new ssh host key fingerprints const gitEnv = { GIT_ASKPASS: 'echo', GIT_SSH_COMMAND: 'ssh -oStrictHostKeyChecking=accept-new', } module.exports = (opts = {}) => ({ stdioString: true, ...opts, shell: false, env: opts.env || { ...gitEnv, ...process.env }, }) PK ~\|q@npmcli/git/LICENSEnu[The ISC License Copyright (c) npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE NPM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE NPM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\-yc@npmcli/config/package.jsonnu[{ "_id": "@npmcli/config@8.3.3", "_inBundle": true, "_location": "/npm/@npmcli/config", "_phantomChildren": {}, "_requiredBy": [ "/npm" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/cli/issues" }, "dependencies": { "@npmcli/map-workspaces": "^3.0.2", "ci-info": "^4.0.0", "ini": "^4.1.2", "nopt": "^7.2.1", "proc-log": "^4.2.0", "read-package-json-fast": "^3.0.2", "semver": "^7.3.5", "walk-up-path": "^3.0.1" }, "description": "Configuration management for the npm cli", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/mock-globals": "^1.0.0", "@npmcli/template-oss": "4.22.0", "tap": "^16.3.8" }, "engines": { "node": "^16.14.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/cli#readme", "license": "ISC", "main": "lib/index.js", "name": "@npmcli/config", "repository": { "type": "git", "url": "git+https://github.com/npm/cli.git", "directory": "workspaces/config" }, "scripts": { "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.22.0", "content": "../../scripts/template-oss/index.js" }, "version": "8.3.3" } PK ~\@npmcli/config/lib/nerf-dart.jsnu[const { URL } = require('node:url') /** * Maps a URL to an identifier. * * Name courtesy schiffertronix media LLC, a New Jersey corporation * * @param {String} uri The URL to be nerfed. * * @returns {String} A nerfed URL. */ module.exports = (url) => { const parsed = new URL(url) const from = `${parsed.protocol}//${parsed.host}${parsed.pathname}` const rel = new URL('.', from) const res = `//${rel.host}${rel.pathname}` return res } PK ~\EI I -@npmcli/config/lib/definitions/definitions.jsnu[const Definition = require('./definition.js') const ciInfo = require('ci-info') const querystring = require('node:querystring') const { join } = require('node:path') const isWindows = process.platform === 'win32' // used by cafile flattening to flatOptions.ca const { readFileSync } = require('node:fs') const maybeReadFile = file => { try { return readFileSync(file, 'utf8') } catch (er) { if (er.code !== 'ENOENT') { throw er } return null } } const buildOmitList = obj => { const include = obj.include || [] const omit = obj.omit || [] const only = obj.only if (/^prod(uction)?$/.test(only) || obj.production) { omit.push('dev') } else if (obj.production === false) { include.push('dev') } if (/^dev/.test(obj.also)) { include.push('dev') } if (obj.dev) { include.push('dev') } if (obj.optional === false) { omit.push('optional') } else if (obj.optional === true) { include.push('optional') } obj.omit = [...new Set(omit)].filter(type => !include.includes(type)) obj.include = [...new Set(include)] if (obj.omit.includes('dev')) { process.env.NODE_ENV = 'production' } return obj.omit } const editor = process.env.EDITOR || process.env.VISUAL || (isWindows ? `${process.env.SYSTEMROOT}\\notepad.exe` : 'vi') const shell = isWindows ? process.env.ComSpec || 'cmd' : process.env.SHELL || 'sh' const { networkInterfaces } = require('node:os') const getLocalAddresses = () => { try { return Object.values(networkInterfaces()).map( int => int.map(({ address }) => address) ).reduce((set, addrs) => set.concat(addrs), [null]) } catch (e) { return [null] } } const unicode = /UTF-?8$/i.test( process.env.LC_ALL || process.env.LC_CTYPE || process.env.LANG ) // use LOCALAPPDATA on Windows, if set // https://github.com/npm/cli/pull/899 const cacheRoot = (isWindows && process.env.LOCALAPPDATA) || '~' const cacheExtra = isWindows ? 'npm-cache' : '.npm' const cache = `${cacheRoot}/${cacheExtra}` // TODO: refactor these type definitions so that they are less // weird to pull out of the config module. // TODO: use better type definition/validation API, nopt's is so weird. const { semver: { type: Semver }, Umask: { type: Umask }, url: { type: url }, path: { type: path }, } = require('../type-defs.js') // basic flattening function, just copy it over camelCase const flatten = (key, obj, flatOptions) => { const camel = key.replace(/-([a-z])/g, (_0, _1) => _1.toUpperCase()) flatOptions[camel] = obj[key] } // TODO: // Instead of having each definition provide a flatten method, // provide the (?list of?) flat option field(s?) that it impacts. // When that config is set, we mark the relevant flatOption fields // dirty. Then, a getter for that field defines how we actually // set it. // // So, `save-dev`, `save-optional`, `save-prod`, et al would indicate // that they affect the `saveType` flat option. Then the config.flat // object has a `get saveType () { ... }` that looks at the "real" // config settings from files etc and returns the appropriate value. // // Getters will also (maybe?) give us a hook to audit flat option // usage, so we can document and group these more appropriately. // // This will be a problem with cases where we currently do: // const opts = { ...npm.flatOptions, foo: 'bar' }, but we can maybe // instead do `npm.config.set('foo', 'bar')` prior to passing the // config object down where it needs to go. // // This way, when we go hunting for "where does saveType come from anyway!?" // while fixing some Arborist bug, we won't have to hunt through too // many places. // XXX: We should really deprecate all these `--save-blah` switches // in favor of a single `--save-type` option. The unfortunate shortcut // we took for `--save-peer --save-optional` being `--save-type=peerOptional` // makes this tricky, and likely a breaking change. // Define all config keys we know about. They are indexed by their own key for // ease of lookup later. This duplication is an optimization so that we don't // have to do an extra function call just to "reuse" the key in both places. const definitions = { _auth: new Definition('_auth', { default: null, type: [null, String], description: ` A basic-auth string to use when authenticating against the npm registry. This will ONLY be used to authenticate against the npm registry. For other registries you will need to scope it like "//other-registry.tld/:_auth" Warning: This should generally not be set via a command-line option. It is safer to use a registry-provided authentication bearer token stored in the ~/.npmrc file by running \`npm login\`. `, flatten, }), access: new Definition('access', { default: null, defaultDescription: ` 'public' for new packages, existing packages it will not change the current level `, type: [null, 'restricted', 'public'], description: ` If you do not want your scoped package to be publicly viewable (and installable) set \`--access=restricted\`. Unscoped packages can not be set to \`restricted\`. Note: This defaults to not changing the current access level for existing packages. Specifying a value of \`restricted\` or \`public\` during publish will change the access for an existing package the same way that \`npm access set status\` would. `, flatten, }), all: new Definition('all', { default: false, type: Boolean, short: 'a', description: ` When running \`npm outdated\` and \`npm ls\`, setting \`--all\` will show all outdated or installed packages, rather than only those directly depended upon by the current project. `, flatten, }), 'allow-same-version': new Definition('allow-same-version', { default: false, type: Boolean, description: ` Prevents throwing an error when \`npm version\` is used to set the new version to the same value as the current version. `, flatten, }), also: new Definition('also', { default: null, type: [null, 'dev', 'development'], description: ` When set to \`dev\` or \`development\`, this is an alias for \`--include=dev\`. `, deprecated: 'Please use --include=dev instead.', flatten (key, obj, flatOptions) { definitions.omit.flatten('omit', obj, flatOptions) }, }), audit: new Definition('audit', { default: true, type: Boolean, description: ` When "true" submit audit reports alongside the current npm command to the default registry and all registries configured for scopes. See the documentation for [\`npm audit\`](/commands/npm-audit) for details on what is submitted. `, flatten, }), 'audit-level': new Definition('audit-level', { default: null, type: [null, 'info', 'low', 'moderate', 'high', 'critical', 'none'], description: ` The minimum level of vulnerability for \`npm audit\` to exit with a non-zero exit code. `, flatten, }), 'auth-type': new Definition('auth-type', { default: 'web', type: ['legacy', 'web'], description: ` What authentication strategy to use with \`login\`. Note that if an \`otp\` config is given, this value will always be set to \`legacy\`. `, flatten, }), before: new Definition('before', { default: null, type: [null, Date], description: ` If passed to \`npm install\`, will rebuild the npm tree such that only versions that were available **on or before** the \`--before\` time get installed. If there's no versions available for the current set of direct dependencies, the command will error. If the requested version is a \`dist-tag\` and the given tag does not pass the \`--before\` filter, the most recent version less than or equal to that tag will be used. For example, \`foo@latest\` might install \`foo@1.2\` even though \`latest\` is \`2.0\`. `, flatten, }), 'bin-links': new Definition('bin-links', { default: true, type: Boolean, description: ` Tells npm to create symlinks (or \`.cmd\` shims on Windows) for package executables. Set to false to have it not do this. This can be used to work around the fact that some file systems don't support symlinks, even on ostensibly Unix systems. `, flatten, }), browser: new Definition('browser', { default: null, defaultDescription: ` OS X: \`"open"\`, Windows: \`"start"\`, Others: \`"xdg-open"\` `, type: [null, Boolean, String], description: ` The browser that is called by npm commands to open websites. Set to \`false\` to suppress browser behavior and instead print urls to terminal. Set to \`true\` to use default system URL opener. `, flatten, }), ca: new Definition('ca', { default: null, type: [null, String, Array], description: ` The Certificate Authority signing certificate that is trusted for SSL connections to the registry. Values should be in PEM format (Windows calls it "Base-64 encoded X.509 (.CER)") with newlines replaced by the string "\\n". For example: \`\`\`ini ca="-----BEGIN CERTIFICATE-----\\nXXXX\\nXXXX\\n-----END CERTIFICATE-----" \`\`\` Set to \`null\` to only allow "known" registrars, or to a specific CA cert to trust only that specific signing authority. Multiple CAs can be trusted by specifying an array of certificates: \`\`\`ini ca[]="..." ca[]="..." \`\`\` See also the \`strict-ssl\` config. `, flatten, }), cache: new Definition('cache', { default: cache, defaultDescription: ` Windows: \`%LocalAppData%\\npm-cache\`, Posix: \`~/.npm\` `, type: path, description: ` The location of npm's cache directory. `, flatten (key, obj, flatOptions) { flatOptions.cache = join(obj.cache, '_cacache') flatOptions.npxCache = join(obj.cache, '_npx') flatOptions.tufCache = join(obj.cache, '_tuf') }, }), 'cache-max': new Definition('cache-max', { default: Infinity, type: Number, description: ` \`--cache-max=0\` is an alias for \`--prefer-online\` `, deprecated: ` This option has been deprecated in favor of \`--prefer-online\` `, flatten (key, obj, flatOptions) { if (obj[key] <= 0) { flatOptions.preferOnline = true } }, }), 'cache-min': new Definition('cache-min', { default: 0, type: Number, description: ` \`--cache-min=9999 (or bigger)\` is an alias for \`--prefer-offline\`. `, deprecated: ` This option has been deprecated in favor of \`--prefer-offline\`. `, flatten (key, obj, flatOptions) { if (obj[key] >= 9999) { flatOptions.preferOffline = true } }, }), cafile: new Definition('cafile', { default: null, type: path, description: ` A path to a file containing one or multiple Certificate Authority signing certificates. Similar to the \`ca\` setting, but allows for multiple CA's, as well as for the CA information to be stored in a file on disk. `, flatten (key, obj, flatOptions) { // always set to null in defaults if (!obj.cafile) { return } const raw = maybeReadFile(obj.cafile) if (!raw) { return } const delim = '-----END CERTIFICATE-----' flatOptions.ca = raw.replace(/\r\n/g, '\n').split(delim) .filter(section => section.trim()) .map(section => section.trimLeft() + delim) }, }), call: new Definition('call', { default: '', type: String, short: 'c', description: ` Optional companion option for \`npm exec\`, \`npx\` that allows for specifying a custom command to be run along with the installed packages. \`\`\`bash npm exec --package yo --package generator-node --call "yo node" \`\`\` `, flatten, }), cert: new Definition('cert', { default: null, type: [null, String], description: ` A client certificate to pass when accessing the registry. Values should be in PEM format (Windows calls it "Base-64 encoded X.509 (.CER)") with newlines replaced by the string "\\n". For example: \`\`\`ini cert="-----BEGIN CERTIFICATE-----\\nXXXX\\nXXXX\\n-----END CERTIFICATE-----" \`\`\` It is _not_ the path to a certificate file, though you can set a registry-scoped "certfile" path like "//other-registry.tld/:certfile=/path/to/cert.pem". `, deprecated: ` \`key\` and \`cert\` are no longer used for most registry operations. Use registry scoped \`keyfile\` and \`certfile\` instead. Example: //other-registry.tld/:keyfile=/path/to/key.pem //other-registry.tld/:certfile=/path/to/cert.crt `, flatten, }), cidr: new Definition('cidr', { default: null, type: [null, String, Array], description: ` This is a list of CIDR address to be used when configuring limited access tokens with the \`npm token create\` command. `, flatten, }), // This should never be directly used, the flattened value is the derived value // and is sent to other modules, and is also exposed as `npm.color` for use // inside npm itself. color: new Definition('color', { default: !process.env.NO_COLOR || process.env.NO_COLOR === '0', usage: '--color|--no-color|--color always', defaultDescription: ` true unless the NO_COLOR environ is set to something other than '0' `, type: ['always', Boolean], description: ` If false, never shows colors. If \`"always"\` then always shows colors. If true, then only prints color codes for tty file descriptors. `, flatten (key, obj, flatOptions) { flatOptions.color = !obj.color ? false : obj.color === 'always' ? true : !!process.stdout.isTTY flatOptions.logColor = !obj.color ? false : obj.color === 'always' ? true : !!process.stderr.isTTY }, }), 'commit-hooks': new Definition('commit-hooks', { default: true, type: Boolean, description: ` Run git commit hooks when using the \`npm version\` command. `, flatten, }), cpu: new Definition('cpu', { default: null, type: [null, String], description: ` Override CPU architecture of native modules to install. Acceptable values are same as \`cpu\` field of package.json, which comes from \`process.arch\`. `, flatten, }), depth: new Definition('depth', { default: null, defaultDescription: ` \`Infinity\` if \`--all\` is set, otherwise \`1\` `, type: [null, Number], description: ` The depth to go when recursing packages for \`npm ls\`. If not set, \`npm ls\` will show only the immediate dependencies of the root project. If \`--all\` is set, then npm will show all dependencies by default. `, flatten, }), description: new Definition('description', { default: true, type: Boolean, usage: '--no-description', description: ` Show the description in \`npm search\` `, flatten (key, obj, flatOptions) { flatOptions.search = flatOptions.search || { limit: 20 } flatOptions.search[key] = obj[key] }, }), dev: new Definition('dev', { default: false, type: Boolean, description: ` Alias for \`--include=dev\`. `, deprecated: 'Please use --include=dev instead.', flatten (key, obj, flatOptions) { definitions.omit.flatten('omit', obj, flatOptions) }, }), diff: new Definition('diff', { default: [], hint: '', type: [String, Array], description: ` Define arguments to compare in \`npm diff\`. `, flatten, }), 'diff-ignore-all-space': new Definition('diff-ignore-all-space', { default: false, type: Boolean, description: ` Ignore whitespace when comparing lines in \`npm diff\`. `, flatten, }), 'diff-name-only': new Definition('diff-name-only', { default: false, type: Boolean, description: ` Prints only filenames when using \`npm diff\`. `, flatten, }), 'diff-no-prefix': new Definition('diff-no-prefix', { default: false, type: Boolean, description: ` Do not show any source or destination prefix in \`npm diff\` output. Note: this causes \`npm diff\` to ignore the \`--diff-src-prefix\` and \`--diff-dst-prefix\` configs. `, flatten, }), 'diff-dst-prefix': new Definition('diff-dst-prefix', { default: 'b/', hint: '', type: String, description: ` Destination prefix to be used in \`npm diff\` output. `, flatten, }), 'diff-src-prefix': new Definition('diff-src-prefix', { default: 'a/', hint: '', type: String, description: ` Source prefix to be used in \`npm diff\` output. `, flatten, }), 'diff-text': new Definition('diff-text', { default: false, type: Boolean, description: ` Treat all files as text in \`npm diff\`. `, flatten, }), 'diff-unified': new Definition('diff-unified', { default: 3, type: Number, description: ` The number of lines of context to print in \`npm diff\`. `, flatten, }), 'dry-run': new Definition('dry-run', { default: false, type: Boolean, description: ` Indicates that you don't want npm to make any changes and that it should only report what it would have done. This can be passed into any of the commands that modify your local installation, eg, \`install\`, \`update\`, \`dedupe\`, \`uninstall\`, as well as \`pack\` and \`publish\`. Note: This is NOT honored by other network related commands, eg \`dist-tags\`, \`owner\`, etc. `, flatten, }), editor: new Definition('editor', { default: editor, defaultDescription: ` The EDITOR or VISUAL environment variables, or '%SYSTEMROOT%\\notepad.exe' on Windows, or 'vi' on Unix systems `, type: String, description: ` The command to run for \`npm edit\` and \`npm config edit\`. `, flatten, }), 'engine-strict': new Definition('engine-strict', { default: false, type: Boolean, description: ` If set to true, then npm will stubbornly refuse to install (or even consider installing) any package that claims to not be compatible with the current Node.js version. This can be overridden by setting the \`--force\` flag. `, flatten, }), 'expect-result-count': new Definition('expect-result-count', { default: null, type: [null, Number], hint: '', exclusive: ['expect-results'], description: ` Tells to expect a specific number of results from the command. `, }), 'expect-results': new Definition('expect-results', { default: null, type: [null, Boolean], exclusive: ['expect-result-count'], description: ` Tells npm whether or not to expect results from the command. Can be either true (expect some results) or false (expect no results). `, }), 'fetch-retries': new Definition('fetch-retries', { default: 2, type: Number, description: ` The "retries" config for the \`retry\` module to use when fetching packages from the registry. npm will retry idempotent read requests to the registry in the case of network failures or 5xx HTTP errors. `, flatten (key, obj, flatOptions) { flatOptions.retry = flatOptions.retry || {} flatOptions.retry.retries = obj[key] }, }), 'fetch-retry-factor': new Definition('fetch-retry-factor', { default: 10, type: Number, description: ` The "factor" config for the \`retry\` module to use when fetching packages. `, flatten (key, obj, flatOptions) { flatOptions.retry = flatOptions.retry || {} flatOptions.retry.factor = obj[key] }, }), 'fetch-retry-maxtimeout': new Definition('fetch-retry-maxtimeout', { default: 60000, defaultDescription: '60000 (1 minute)', type: Number, description: ` The "maxTimeout" config for the \`retry\` module to use when fetching packages. `, flatten (key, obj, flatOptions) { flatOptions.retry = flatOptions.retry || {} flatOptions.retry.maxTimeout = obj[key] }, }), 'fetch-retry-mintimeout': new Definition('fetch-retry-mintimeout', { default: 10000, defaultDescription: '10000 (10 seconds)', type: Number, description: ` The "minTimeout" config for the \`retry\` module to use when fetching packages. `, flatten (key, obj, flatOptions) { flatOptions.retry = flatOptions.retry || {} flatOptions.retry.minTimeout = obj[key] }, }), 'fetch-timeout': new Definition('fetch-timeout', { default: 5 * 60 * 1000, defaultDescription: `${5 * 60 * 1000} (5 minutes)`, type: Number, description: ` The maximum amount of time to wait for HTTP requests to complete. `, flatten (key, obj, flatOptions) { flatOptions.timeout = obj[key] }, }), force: new Definition('force', { default: false, type: Boolean, short: 'f', description: ` Removes various protections against unfortunate side effects, common mistakes, unnecessary performance degradation, and malicious input. * Allow clobbering non-npm files in global installs. * Allow the \`npm version\` command to work on an unclean git repository. * Allow deleting the cache folder with \`npm cache clean\`. * Allow installing packages that have an \`engines\` declaration requiring a different version of npm. * Allow installing packages that have an \`engines\` declaration requiring a different version of \`node\`, even if \`--engine-strict\` is enabled. * Allow \`npm audit fix\` to install modules outside your stated dependency range (including SemVer-major changes). * Allow unpublishing all versions of a published package. * Allow conflicting peerDependencies to be installed in the root project. * Implicitly set \`--yes\` during \`npm init\`. * Allow clobbering existing values in \`npm pkg\` * Allow unpublishing of entire packages (not just a single version). If you don't have a clear idea of what you want to do, it is strongly recommended that you do not use this option! `, flatten, }), 'foreground-scripts': new Definition('foreground-scripts', { default: false, defaultDescription: `\`false\` unless when using \`npm pack\` or \`npm publish\` where it defaults to \`true\``, type: Boolean, description: ` Run all build scripts (ie, \`preinstall\`, \`install\`, and \`postinstall\`) scripts for installed packages in the foreground process, sharing standard input, output, and error with the main npm process. Note that this will generally make installs run slower, and be much noisier, but can be useful for debugging. `, flatten, }), 'format-package-lock': new Definition('format-package-lock', { default: true, type: Boolean, description: ` Format \`package-lock.json\` or \`npm-shrinkwrap.json\` as a human readable file. `, flatten, }), fund: new Definition('fund', { default: true, type: Boolean, description: ` When "true" displays the message at the end of each \`npm install\` acknowledging the number of dependencies looking for funding. See [\`npm fund\`](/commands/npm-fund) for details. `, flatten, }), git: new Definition('git', { default: 'git', type: String, description: ` The command to use for git commands. If git is installed on the computer, but is not in the \`PATH\`, then set this to the full path to the git binary. `, flatten, }), 'git-tag-version': new Definition('git-tag-version', { default: true, type: Boolean, description: ` Tag the commit when using the \`npm version\` command. Setting this to false results in no commit being made at all. `, flatten, }), global: new Definition('global', { default: false, type: Boolean, short: 'g', description: ` Operates in "global" mode, so that packages are installed into the \`prefix\` folder instead of the current working directory. See [folders](/configuring-npm/folders) for more on the differences in behavior. * packages are installed into the \`{prefix}/lib/node_modules\` folder, instead of the current working directory. * bin files are linked to \`{prefix}/bin\` * man pages are linked to \`{prefix}/share/man\` `, flatten: (key, obj, flatOptions) => { flatten(key, obj, flatOptions) if (flatOptions.global) { flatOptions.location = 'global' } }, }), // the globalconfig has its default defined outside of this module globalconfig: new Definition('globalconfig', { type: path, default: '', defaultDescription: ` The global --prefix setting plus 'etc/npmrc'. For example, '/usr/local/etc/npmrc' `, description: ` The config file to read for global config options. `, flatten, }), 'global-style': new Definition('global-style', { default: false, type: Boolean, description: ` Only install direct dependencies in the top level \`node_modules\`, but hoist on deeper dependencies. Sets \`--install-strategy=shallow\`. `, deprecated: ` This option has been deprecated in favor of \`--install-strategy=shallow\` `, flatten (key, obj, flatOptions) { if (obj[key]) { obj['install-strategy'] = 'shallow' flatOptions.installStrategy = 'shallow' } }, }), heading: new Definition('heading', { default: 'npm', type: String, description: ` The string that starts all the debugging log output. `, flatten, }), 'https-proxy': new Definition('https-proxy', { default: null, type: [null, url], description: ` A proxy to use for outgoing https requests. If the \`HTTPS_PROXY\` or \`https_proxy\` or \`HTTP_PROXY\` or \`http_proxy\` environment variables are set, proxy settings will be honored by the underlying \`make-fetch-happen\` library. `, flatten, }), 'if-present': new Definition('if-present', { default: false, type: Boolean, envExport: false, description: ` If true, npm will not exit with an error code when \`run-script\` is invoked for a script that isn't defined in the \`scripts\` section of \`package.json\`. This option can be used when it's desirable to optionally run a script when it's present and fail if the script fails. This is useful, for example, when running scripts that may only apply for some builds in an otherwise generic CI setup. `, flatten, }), 'ignore-scripts': new Definition('ignore-scripts', { default: false, type: Boolean, description: ` If true, npm does not run scripts specified in package.json files. Note that commands explicitly intended to run a particular script, such as \`npm start\`, \`npm stop\`, \`npm restart\`, \`npm test\`, and \`npm run-script\` will still run their intended script if \`ignore-scripts\` is set, but they will *not* run any pre- or post-scripts. `, flatten, }), include: new Definition('include', { default: [], type: [Array, 'prod', 'dev', 'optional', 'peer'], description: ` Option that allows for defining which types of dependencies to install. This is the inverse of \`--omit=\`. Dependency types specified in \`--include\` will not be omitted, regardless of the order in which omit/include are specified on the command-line. `, flatten (key, obj, flatOptions) { // just call the omit flattener, it reads from obj.include definitions.omit.flatten('omit', obj, flatOptions) }, }), 'include-staged': new Definition('include-staged', { default: false, type: Boolean, description: ` Allow installing "staged" published packages, as defined by [npm RFC PR #92](https://github.com/npm/rfcs/pull/92). This is experimental, and not implemented by the npm public registry. `, flatten, }), 'include-workspace-root': new Definition('include-workspace-root', { default: false, type: Boolean, envExport: false, description: ` Include the workspace root when workspaces are enabled for a command. When false, specifying individual workspaces via the \`workspace\` config, or all workspaces via the \`workspaces\` flag, will cause npm to operate only on the specified workspaces, and not on the root project. `, flatten, }), 'init-author-email': new Definition('init-author-email', { default: '', hint: '', type: String, description: ` The value \`npm init\` should use by default for the package author's email. `, }), 'init-author-name': new Definition('init-author-name', { default: '', hint: '', type: String, description: ` The value \`npm init\` should use by default for the package author's name. `, }), 'init-author-url': new Definition('init-author-url', { default: '', type: ['', url], hint: '', description: ` The value \`npm init\` should use by default for the package author's homepage. `, }), 'init-license': new Definition('init-license', { default: 'ISC', hint: '', type: String, description: ` The value \`npm init\` should use by default for the package license. `, }), 'init-module': new Definition('init-module', { default: '~/.npm-init.js', type: path, hint: '', description: ` A module that will be loaded by the \`npm init\` command. See the documentation for the [init-package-json](https://github.com/npm/init-package-json) module for more information, or [npm init](/commands/npm-init). `, }), 'init-version': new Definition('init-version', { default: '1.0.0', type: Semver, hint: '', description: ` The value that \`npm init\` should use by default for the package version number, if not already set in package.json. `, }), // these "aliases" are historically supported in .npmrc files, unfortunately // They should be removed in a future npm version. 'init.author.email': new Definition('init.author.email', { default: '', type: String, deprecated: ` Use \`--init-author-email\` instead.`, description: ` Alias for \`--init-author-email\` `, }), 'init.author.name': new Definition('init.author.name', { default: '', type: String, deprecated: ` Use \`--init-author-name\` instead. `, description: ` Alias for \`--init-author-name\` `, }), 'init.author.url': new Definition('init.author.url', { default: '', type: ['', url], deprecated: ` Use \`--init-author-url\` instead. `, description: ` Alias for \`--init-author-url\` `, }), 'init.license': new Definition('init.license', { default: 'ISC', type: String, deprecated: ` Use \`--init-license\` instead. `, description: ` Alias for \`--init-license\` `, }), 'init.module': new Definition('init.module', { default: '~/.npm-init.js', type: path, deprecated: ` Use \`--init-module\` instead. `, description: ` Alias for \`--init-module\` `, }), 'init.version': new Definition('init.version', { default: '1.0.0', type: Semver, deprecated: ` Use \`--init-version\` instead. `, description: ` Alias for \`--init-version\` `, }), 'install-links': new Definition('install-links', { default: false, type: Boolean, description: ` When set file: protocol dependencies will be packed and installed as regular dependencies instead of creating a symlink. This option has no effect on workspaces. `, flatten, }), 'install-strategy': new Definition('install-strategy', { default: 'hoisted', type: ['hoisted', 'nested', 'shallow', 'linked'], description: ` Sets the strategy for installing packages in node_modules. hoisted (default): Install non-duplicated in top-level, and duplicated as necessary within directory structure. nested: (formerly --legacy-bundling) install in place, no hoisting. shallow (formerly --global-style) only install direct deps at top-level. linked: (experimental) install in node_modules/.store, link in place, unhoisted. `, flatten, }), json: new Definition('json', { default: false, type: Boolean, description: ` Whether or not to output JSON data, rather than the normal output. * In \`npm pkg set\` it enables parsing set values with JSON.parse() before saving them to your \`package.json\`. Not supported by all npm commands. `, flatten, }), key: new Definition('key', { default: null, type: [null, String], description: ` A client key to pass when accessing the registry. Values should be in PEM format with newlines replaced by the string "\\n". For example: \`\`\`ini key="-----BEGIN PRIVATE KEY-----\\nXXXX\\nXXXX\\n-----END PRIVATE KEY-----" \`\`\` It is _not_ the path to a key file, though you can set a registry-scoped "keyfile" path like "//other-registry.tld/:keyfile=/path/to/key.pem". `, deprecated: ` \`key\` and \`cert\` are no longer used for most registry operations. Use registry scoped \`keyfile\` and \`certfile\` instead. Example: //other-registry.tld/:keyfile=/path/to/key.pem //other-registry.tld/:certfile=/path/to/cert.crt `, flatten, }), 'legacy-bundling': new Definition('legacy-bundling', { default: false, type: Boolean, description: ` Instead of hoisting package installs in \`node_modules\`, install packages in the same manner that they are depended on. This may cause very deep directory structures and duplicate package installs as there is no de-duplicating. Sets \`--install-strategy=nested\`. `, deprecated: ` This option has been deprecated in favor of \`--install-strategy=nested\` `, flatten (key, obj, flatOptions) { if (obj[key]) { obj['install-strategy'] = 'nested' flatOptions.installStrategy = 'nested' } }, }), 'legacy-peer-deps': new Definition('legacy-peer-deps', { default: false, type: Boolean, description: ` Causes npm to completely ignore \`peerDependencies\` when building a package tree, as in npm versions 3 through 6. If a package cannot be installed because of overly strict \`peerDependencies\` that collide, it provides a way to move forward resolving the situation. This differs from \`--omit=peer\`, in that \`--omit=peer\` will avoid unpacking \`peerDependencies\` on disk, but will still design a tree such that \`peerDependencies\` _could_ be unpacked in a correct place. Use of \`legacy-peer-deps\` is not recommended, as it will not enforce the \`peerDependencies\` contract that meta-dependencies may rely on. `, flatten, }), libc: new Definition('libc', { default: null, type: [null, String], description: ` Override libc of native modules to install. Acceptable values are same as \`libc\` field of package.json `, flatten, }), link: new Definition('link', { default: false, type: Boolean, description: ` Used with \`npm ls\`, limiting output to only those packages that are linked. `, }), 'local-address': new Definition('local-address', { default: null, type: getLocalAddresses(), typeDescription: 'IP Address', description: ` The IP address of the local interface to use when making connections to the npm registry. Must be IPv4 in versions of Node prior to 0.12. `, flatten, }), location: new Definition('location', { default: 'user', short: 'L', type: [ 'global', 'user', 'project', ], defaultDescription: ` "user" unless \`--global\` is passed, which will also set this value to "global" `, description: ` When passed to \`npm config\` this refers to which config file to use. When set to "global" mode, packages are installed into the \`prefix\` folder instead of the current working directory. See [folders](/configuring-npm/folders) for more on the differences in behavior. * packages are installed into the \`{prefix}/lib/node_modules\` folder, instead of the current working directory. * bin files are linked to \`{prefix}/bin\` * man pages are linked to \`{prefix}/share/man\` `, flatten: (key, obj, flatOptions) => { flatten(key, obj, flatOptions) if (flatOptions.global) { flatOptions.location = 'global' } if (obj.location === 'global') { flatOptions.global = true } }, }), 'lockfile-version': new Definition('lockfile-version', { default: null, type: [null, 1, 2, 3, '1', '2', '3'], defaultDescription: ` Version 3 if no lockfile, auto-converting v1 lockfiles to v3, otherwise maintain current lockfile version.`, description: ` Set the lockfile format version to be used in package-lock.json and npm-shrinkwrap-json files. Possible options are: 1: The lockfile version used by npm versions 5 and 6. Lacks some data that is used during the install, resulting in slower and possibly less deterministic installs. Prevents lockfile churn when interoperating with older npm versions. 2: The default lockfile version used by npm version 7 and 8. Includes both the version 1 lockfile data and version 3 lockfile data, for maximum determinism and interoperability, at the expense of more bytes on disk. 3: Only the new lockfile information introduced in npm version 7. Smaller on disk than lockfile version 2, but not interoperable with older npm versions. Ideal if all users are on npm version 7 and higher. `, flatten: (key, obj, flatOptions) => { flatOptions.lockfileVersion = obj[key] && parseInt(obj[key], 10) }, }), loglevel: new Definition('loglevel', { default: 'notice', type: [ 'silent', 'error', 'warn', 'notice', 'http', 'info', 'verbose', 'silly', ], description: ` What level of logs to report. All logs are written to a debug log, with the path to that file printed if the execution of a command fails. Any logs of a higher level than the setting are shown. The default is "notice". See also the \`foreground-scripts\` config. `, flatten (key, obj, flatOptions) { flatOptions.silent = obj[key] === 'silent' }, }), 'logs-dir': new Definition('logs-dir', { default: null, type: [null, path], defaultDescription: ` A directory named \`_logs\` inside the cache `, description: ` The location of npm's log directory. See [\`npm logging\`](/using-npm/logging) for more information. `, }), 'logs-max': new Definition('logs-max', { default: 10, type: Number, description: ` The maximum number of log files to store. If set to 0, no log files will be written for the current run. `, }), long: new Definition('long', { default: false, type: Boolean, short: 'l', description: ` Show extended information in \`ls\`, \`search\`, and \`help-search\`. `, }), maxsockets: new Definition('maxsockets', { default: 15, type: Number, description: ` The maximum number of connections to use per origin (protocol/host/port combination). `, flatten (key, obj, flatOptions) { flatOptions.maxSockets = obj[key] }, }), message: new Definition('message', { default: '%s', type: String, short: 'm', description: ` Commit message which is used by \`npm version\` when creating version commit. Any "%s" in the message will be replaced with the version number. `, flatten, }), 'node-options': new Definition('node-options', { default: null, type: [null, String], description: ` Options to pass through to Node.js via the \`NODE_OPTIONS\` environment variable. This does not impact how npm itself is executed but it does impact how lifecycle scripts are called. `, }), noproxy: new Definition('noproxy', { default: '', defaultDescription: ` The value of the NO_PROXY environment variable `, type: [String, Array], description: ` Domain extensions that should bypass any proxies. Also accepts a comma-delimited string. `, flatten (key, obj, flatOptions) { if (Array.isArray(obj[key])) { flatOptions.noProxy = obj[key].join(',') } else { flatOptions.noProxy = obj[key] } }, }), offline: new Definition('offline', { default: false, type: Boolean, description: ` Force offline mode: no network requests will be done during install. To allow the CLI to fill in missing cache data, see \`--prefer-offline\`. `, flatten, }), omit: new Definition('omit', { default: process.env.NODE_ENV === 'production' ? ['dev'] : [], defaultDescription: ` 'dev' if the \`NODE_ENV\` environment variable is set to 'production', otherwise empty. `, type: [Array, 'dev', 'optional', 'peer'], description: ` Dependency types to omit from the installation tree on disk. Note that these dependencies _are_ still resolved and added to the \`package-lock.json\` or \`npm-shrinkwrap.json\` file. They are just not physically installed on disk. If a package type appears in both the \`--include\` and \`--omit\` lists, then it will be included. If the resulting omit list includes \`'dev'\`, then the \`NODE_ENV\` environment variable will be set to \`'production'\` for all lifecycle scripts. `, flatten (key, obj, flatOptions) { flatOptions.omit = buildOmitList(obj) }, }), 'omit-lockfile-registry-resolved': new Definition('omit-lockfile-registry-resolved', { default: false, type: Boolean, description: ` This option causes npm to create lock files without a \`resolved\` key for registry dependencies. Subsequent installs will need to resolve tarball endpoints with the configured registry, likely resulting in a longer install time. `, flatten, }), only: new Definition('only', { default: null, type: [null, 'prod', 'production'], deprecated: ` Use \`--omit=dev\` to omit dev dependencies from the install. `, description: ` When set to \`prod\` or \`production\`, this is an alias for \`--omit=dev\`. `, flatten (key, obj, flatOptions) { definitions.omit.flatten('omit', obj, flatOptions) }, }), optional: new Definition('optional', { default: null, type: [null, Boolean], deprecated: ` Use \`--omit=optional\` to exclude optional dependencies, or \`--include=optional\` to include them. Default value does install optional deps unless otherwise omitted. `, description: ` Alias for --include=optional or --omit=optional `, flatten (key, obj, flatOptions) { definitions.omit.flatten('omit', obj, flatOptions) }, }), os: new Definition('os', { default: null, type: [null, String], description: ` Override OS of native modules to install. Acceptable values are same as \`os\` field of package.json, which comes from \`process.platform\`. `, flatten, }), otp: new Definition('otp', { default: null, type: [null, String], description: ` This is a one-time password from a two-factor authenticator. It's needed when publishing or changing package permissions with \`npm access\`. If not set, and a registry response fails with a challenge for a one-time password, npm will prompt on the command line for one. `, flatten (key, obj, flatOptions) { flatten(key, obj, flatOptions) if (obj.otp) { obj['auth-type'] = 'legacy' flatten('auth-type', obj, flatOptions) } }, }), package: new Definition('package', { default: [], hint: '', type: [String, Array], description: ` The package or packages to install for [\`npm exec\`](/commands/npm-exec) `, flatten, }), 'package-lock': new Definition('package-lock', { default: true, type: Boolean, description: ` If set to false, then ignore \`package-lock.json\` files when installing. This will also prevent _writing_ \`package-lock.json\` if \`save\` is true. `, flatten: (key, obj, flatOptions) => { flatten(key, obj, flatOptions) if (flatOptions.packageLockOnly) { flatOptions.packageLock = true } }, }), 'package-lock-only': new Definition('package-lock-only', { default: false, type: Boolean, description: ` If set to true, the current operation will only use the \`package-lock.json\`, ignoring \`node_modules\`. For \`update\` this means only the \`package-lock.json\` will be updated, instead of checking \`node_modules\` and downloading dependencies. For \`list\` this means the output will be based on the tree described by the \`package-lock.json\`, rather than the contents of \`node_modules\`. `, flatten: (key, obj, flatOptions) => { flatten(key, obj, flatOptions) if (flatOptions.packageLockOnly) { flatOptions.packageLock = true } }, }), 'pack-destination': new Definition('pack-destination', { default: '.', type: String, description: ` Directory in which \`npm pack\` will save tarballs. `, flatten, }), parseable: new Definition('parseable', { default: false, type: Boolean, short: 'p', description: ` Output parseable results from commands that write to standard output. For \`npm search\`, this will be tab-separated table format. `, flatten, }), 'prefer-dedupe': new Definition('prefer-dedupe', { default: false, type: Boolean, description: ` Prefer to deduplicate packages if possible, rather than choosing a newer version of a dependency. `, flatten, }), 'prefer-offline': new Definition('prefer-offline', { default: false, type: Boolean, description: ` If true, staleness checks for cached data will be bypassed, but missing data will be requested from the server. To force full offline mode, use \`--offline\`. `, flatten, }), 'prefer-online': new Definition('prefer-online', { default: false, type: Boolean, description: ` If true, staleness checks for cached data will be forced, making the CLI look for updates immediately even for fresh package data. `, flatten, }), // `prefix` has its default defined outside of this module prefix: new Definition('prefix', { type: path, short: 'C', default: '', defaultDescription: ` In global mode, the folder where the node executable is installed. Otherwise, the nearest parent folder containing either a package.json file or a node_modules folder. `, description: ` The location to install global items. If set on the command line, then it forces non-global commands to run in the specified folder. `, }), preid: new Definition('preid', { default: '', hint: 'prerelease-id', type: String, description: ` The "prerelease identifier" to use as a prefix for the "prerelease" part of a semver. Like the \`rc\` in \`1.2.0-rc.8\`. `, flatten, }), production: new Definition('production', { default: null, type: [null, Boolean], deprecated: 'Use `--omit=dev` instead.', description: 'Alias for `--omit=dev`', flatten (key, obj, flatOptions) { definitions.omit.flatten('omit', obj, flatOptions) }, }), progress: new Definition('progress', { default: !ciInfo.isCI, defaultDescription: ` \`true\` unless running in a known CI system `, type: Boolean, description: ` When set to \`true\`, npm will display a progress bar during time intensive operations, if \`process.stderr\` and \`process.stdout\` are a TTY. Set to \`false\` to suppress the progress bar. `, flatten (key, obj, flatOptions) { flatOptions.progress = !obj.progress ? false // progress is only written to stderr but we disable it unless stdout is a tty // also. This prevents the progress from appearing when piping output to another // command which doesn't break anything, but does look very odd to users. : !!process.stderr.isTTY && !!process.stdout.isTTY && process.env.TERM !== 'dumb' }, }), provenance: new Definition('provenance', { default: false, type: Boolean, exclusive: ['provenance-file'], description: ` When publishing from a supported cloud CI/CD system, the package will be publicly linked to where it was built and published from. `, flatten, }), 'provenance-file': new Definition('provenance-file', { default: null, type: path, hint: '', exclusive: ['provenance'], description: ` When publishing, the provenance bundle at the given path will be used. `, flatten, }), proxy: new Definition('proxy', { default: null, type: [null, false, url], // allow proxy to be disabled explicitly description: ` A proxy to use for outgoing http requests. If the \`HTTP_PROXY\` or \`http_proxy\` environment variables are set, proxy settings will be honored by the underlying \`request\` library. `, flatten, }), 'read-only': new Definition('read-only', { default: false, type: Boolean, description: ` This is used to mark a token as unable to publish when configuring limited access tokens with the \`npm token create\` command. `, flatten, }), 'rebuild-bundle': new Definition('rebuild-bundle', { default: true, type: Boolean, description: ` Rebuild bundled dependencies after installation. `, flatten, }), registry: new Definition('registry', { default: 'https://registry.npmjs.org/', type: url, description: ` The base URL of the npm registry. `, flatten, }), 'replace-registry-host': new Definition('replace-registry-host', { default: 'npmjs', hint: ' | hostname', type: ['npmjs', 'never', 'always', String], description: ` Defines behavior for replacing the registry host in a lockfile with the configured registry. The default behavior is to replace package dist URLs from the default registry (https://registry.npmjs.org) to the configured registry. If set to "never", then use the registry value. If set to "always", then replace the registry host with the configured host every time. You may also specify a bare hostname (e.g., "registry.npmjs.org"). `, flatten, }), save: new Definition('save', { default: true, defaultDescription: `\`true\` unless when using \`npm update\` where it defaults to \`false\``, usage: '-S|--save|--no-save|--save-prod|--save-dev|--save-optional|--save-peer|--save-bundle', type: Boolean, short: 'S', description: ` Save installed packages to a \`package.json\` file as dependencies. When used with the \`npm rm\` command, removes the dependency from \`package.json\`. Will also prevent writing to \`package-lock.json\` if set to \`false\`. `, flatten, }), 'save-bundle': new Definition('save-bundle', { default: false, type: Boolean, short: 'B', description: ` If a package would be saved at install time by the use of \`--save\`, \`--save-dev\`, or \`--save-optional\`, then also put it in the \`bundleDependencies\` list. Ignored if \`--save-peer\` is set, since peerDependencies cannot be bundled. `, flatten (key, obj, flatOptions) { // XXX update arborist to just ignore it if resulting saveType is peer // otherwise this won't have the expected effect: // // npm config set save-peer true // npm i foo --save-bundle --save-prod <-- should bundle flatOptions.saveBundle = obj['save-bundle'] && !obj['save-peer'] }, }), 'save-dev': new Definition('save-dev', { default: false, type: Boolean, short: 'D', description: ` Save installed packages to a package.json file as \`devDependencies\`. `, flatten (key, obj, flatOptions) { if (!obj[key]) { if (flatOptions.saveType === 'dev') { delete flatOptions.saveType } return } flatOptions.saveType = 'dev' }, }), 'save-exact': new Definition('save-exact', { default: false, type: Boolean, short: 'E', description: ` Dependencies saved to package.json will be configured with an exact version rather than using npm's default semver range operator. `, flatten (key, obj, flatOptions) { // just call the save-prefix flattener, it reads from obj['save-exact'] definitions['save-prefix'].flatten('save-prefix', obj, flatOptions) }, }), 'save-optional': new Definition('save-optional', { default: false, type: Boolean, short: 'O', description: ` Save installed packages to a package.json file as \`optionalDependencies\`. `, flatten (key, obj, flatOptions) { if (!obj[key]) { if (flatOptions.saveType === 'optional') { delete flatOptions.saveType } else if (flatOptions.saveType === 'peerOptional') { flatOptions.saveType = 'peer' } return } if (flatOptions.saveType === 'peerOptional') { return } if (flatOptions.saveType === 'peer') { flatOptions.saveType = 'peerOptional' } else { flatOptions.saveType = 'optional' } }, }), 'save-peer': new Definition('save-peer', { default: false, type: Boolean, description: ` Save installed packages to a package.json file as \`peerDependencies\` `, flatten (key, obj, flatOptions) { if (!obj[key]) { if (flatOptions.saveType === 'peer') { delete flatOptions.saveType } else if (flatOptions.saveType === 'peerOptional') { flatOptions.saveType = 'optional' } return } if (flatOptions.saveType === 'peerOptional') { return } if (flatOptions.saveType === 'optional') { flatOptions.saveType = 'peerOptional' } else { flatOptions.saveType = 'peer' } }, }), 'save-prefix': new Definition('save-prefix', { default: '^', type: String, description: ` Configure how versions of packages installed to a package.json file via \`--save\` or \`--save-dev\` get prefixed. For example if a package has version \`1.2.3\`, by default its version is set to \`^1.2.3\` which allows minor upgrades for that package, but after \`npm config set save-prefix='~'\` it would be set to \`~1.2.3\` which only allows patch upgrades. `, flatten (key, obj, flatOptions) { flatOptions.savePrefix = obj['save-exact'] ? '' : obj['save-prefix'] obj['save-prefix'] = flatOptions.savePrefix }, }), 'save-prod': new Definition('save-prod', { default: false, type: Boolean, short: 'P', description: ` Save installed packages into \`dependencies\` specifically. This is useful if a package already exists in \`devDependencies\` or \`optionalDependencies\`, but you want to move it to be a non-optional production dependency. This is the default behavior if \`--save\` is true, and neither \`--save-dev\` or \`--save-optional\` are true. `, flatten (key, obj, flatOptions) { if (!obj[key]) { if (flatOptions.saveType === 'prod') { delete flatOptions.saveType } return } flatOptions.saveType = 'prod' }, }), 'sbom-format': new Definition('sbom-format', { default: null, type: [ 'cyclonedx', 'spdx', ], description: ` SBOM format to use when generating SBOMs. `, flatten, }), 'sbom-type': new Definition('sbom-type', { default: 'library', type: [ 'library', 'application', 'framework', ], description: ` The type of package described by the generated SBOM. For SPDX, this is the value for the \`primaryPackagePurpose\` field. For CycloneDX, this is the value for the \`type\` field. `, flatten, }), scope: new Definition('scope', { default: '', defaultDescription: ` the scope of the current project, if any, or "" `, type: String, hint: '<@scope>', description: ` Associate an operation with a scope for a scoped registry. Useful when logging in to or out of a private registry: \`\`\` # log in, linking the scope to the custom registry npm login --scope=@mycorp --registry=https://registry.mycorp.com # log out, removing the link and the auth token npm logout --scope=@mycorp \`\`\` This will cause \`@mycorp\` to be mapped to the registry for future installation of packages specified according to the pattern \`@mycorp/package\`. This will also cause \`npm init\` to create a scoped package. \`\`\` # accept all defaults, and create a package named "@foo/whatever", # instead of just named "whatever" npm init --scope=@foo --yes \`\`\` `, flatten (key, obj, flatOptions) { const value = obj[key] const scope = value && !/^@/.test(value) ? `@${value}` : value flatOptions.scope = scope // projectScope is kept for compatibility with npm-registry-fetch flatOptions.projectScope = scope }, }), 'script-shell': new Definition('script-shell', { default: null, defaultDescription: ` '/bin/sh' on POSIX systems, 'cmd.exe' on Windows `, type: [null, String], description: ` The shell to use for scripts run with the \`npm exec\`, \`npm run\` and \`npm init \` commands. `, flatten (key, obj, flatOptions) { flatOptions.scriptShell = obj[key] || undefined }, }), searchexclude: new Definition('searchexclude', { default: '', type: String, description: ` Space-separated options that limit the results from search. `, flatten (key, obj, flatOptions) { flatOptions.search = flatOptions.search || { limit: 20 } flatOptions.search.exclude = obj[key].toLowerCase() }, }), searchlimit: new Definition('searchlimit', { default: 20, type: Number, description: ` Number of items to limit search results to. Will not apply at all to legacy searches. `, flatten (key, obj, flatOptions) { flatOptions.search = flatOptions.search || {} flatOptions.search.limit = obj[key] }, }), searchopts: new Definition('searchopts', { default: '', type: String, description: ` Space-separated options that are always passed to search. `, flatten (key, obj, flatOptions) { flatOptions.search = flatOptions.search || { limit: 20 } flatOptions.search.opts = querystring.parse(obj[key]) }, }), searchstaleness: new Definition('searchstaleness', { default: 15 * 60, type: Number, description: ` The age of the cache, in seconds, before another registry request is made if using legacy search endpoint. `, flatten (key, obj, flatOptions) { flatOptions.search = flatOptions.search || { limit: 20 } flatOptions.search.staleness = obj[key] }, }), shell: new Definition('shell', { default: shell, defaultDescription: ` SHELL environment variable, or "bash" on Posix, or "cmd.exe" on Windows `, type: String, description: ` The shell to run for the \`npm explore\` command. `, flatten, }), shrinkwrap: new Definition('shrinkwrap', { default: true, type: Boolean, deprecated: ` Use the --package-lock setting instead. `, description: ` Alias for --package-lock `, flatten (key, obj, flatOptions) { obj['package-lock'] = obj.shrinkwrap definitions['package-lock'].flatten('package-lock', obj, flatOptions) }, }), 'sign-git-commit': new Definition('sign-git-commit', { default: false, type: Boolean, description: ` If set to true, then the \`npm version\` command will commit the new package version using \`-S\` to add a signature. Note that git requires you to have set up GPG keys in your git configs for this to work properly. `, flatten, }), 'sign-git-tag': new Definition('sign-git-tag', { default: false, type: Boolean, description: ` If set to true, then the \`npm version\` command will tag the version using \`-s\` to add a signature. Note that git requires you to have set up GPG keys in your git configs for this to work properly. `, flatten, }), 'strict-peer-deps': new Definition('strict-peer-deps', { default: false, type: Boolean, description: ` If set to \`true\`, and \`--legacy-peer-deps\` is not set, then _any_ conflicting \`peerDependencies\` will be treated as an install failure, even if npm could reasonably guess the appropriate resolution based on non-peer dependency relationships. By default, conflicting \`peerDependencies\` deep in the dependency graph will be resolved using the nearest non-peer dependency specification, even if doing so will result in some packages receiving a peer dependency outside the range set in their package's \`peerDependencies\` object. When such an override is performed, a warning is printed, explaining the conflict and the packages involved. If \`--strict-peer-deps\` is set, then this warning is treated as a failure. `, flatten, }), 'strict-ssl': new Definition('strict-ssl', { default: true, type: Boolean, description: ` Whether or not to do SSL key validation when making requests to the registry via https. See also the \`ca\` config. `, flatten (key, obj, flatOptions) { flatOptions.strictSSL = obj[key] }, }), tag: new Definition('tag', { default: 'latest', type: String, description: ` If you ask npm to install a package and don't tell it a specific version, then it will install the specified tag. It is the tag added to the package@version specified in the \`npm dist-tag add\` command, if no explicit tag is given. When used by the \`npm diff\` command, this is the tag used to fetch the tarball that will be compared with the local files by default. If used in the \`npm publish\` command, this is the tag that will be added to the package submitted to the registry. `, flatten (key, obj, flatOptions) { flatOptions.defaultTag = obj[key] }, }), 'tag-version-prefix': new Definition('tag-version-prefix', { default: 'v', type: String, description: ` If set, alters the prefix used when tagging a new version when performing a version increment using \`npm version\`. To remove the prefix altogether, set it to the empty string: \`""\`. Because other tools may rely on the convention that npm version tags look like \`v1.0.0\`, _only use this property if it is absolutely necessary_. In particular, use care when overriding this setting for public packages. `, flatten, }), timing: new Definition('timing', { default: false, type: Boolean, description: ` If true, writes timing information to a process specific json file in the cache or \`logs-dir\`. The file name ends with \`-timing.json\`. You can quickly view it with this [json](https://npm.im/json) command line: \`cat ~/.npm/_logs/*-timing.json | npm exec -- json -g\`. Timing information will also be reported in the terminal. To suppress this while still writing the timing file, use \`--silent\`. `, }), umask: new Definition('umask', { default: 0, type: Umask, description: ` The "umask" value to use when setting the file creation mode on files and folders. Folders and executables are given a mode which is \`0o777\` masked against this value. Other files are given a mode which is \`0o666\` masked against this value. Note that the underlying system will _also_ apply its own umask value to files and folders that are created, and npm does not circumvent this, but rather adds the \`--umask\` config to it. Thus, the effective default umask value on most POSIX systems is 0o22, meaning that folders and executables are created with a mode of 0o755 and other files are created with a mode of 0o644. `, flatten, }), unicode: new Definition('unicode', { default: unicode, defaultDescription: ` false on windows, true on mac/unix systems with a unicode locale, as defined by the \`LC_ALL\`, \`LC_CTYPE\`, or \`LANG\` environment variables. `, type: Boolean, description: ` When set to true, npm uses unicode characters in the tree output. When false, it uses ascii characters instead of unicode glyphs. `, flatten, }), 'update-notifier': new Definition('update-notifier', { default: true, type: Boolean, description: ` Set to false to suppress the update notification when using an older version of npm than the latest. `, }), usage: new Definition('usage', { default: false, type: Boolean, short: ['?', 'H', 'h'], description: ` Show short usage output about the command specified. `, }), 'user-agent': new Definition('user-agent', { default: 'npm/{npm-version} ' + 'node/{node-version} ' + '{platform} ' + '{arch} ' + 'workspaces/{workspaces} ' + '{ci}', type: String, description: ` Sets the User-Agent request header. The following fields are replaced with their actual counterparts: * \`{npm-version}\` - The npm version in use * \`{node-version}\` - The Node.js version in use * \`{platform}\` - The value of \`process.platform\` * \`{arch}\` - The value of \`process.arch\` * \`{workspaces}\` - Set to \`true\` if the \`workspaces\` or \`workspace\` options are set. * \`{ci}\` - The value of the \`ci-name\` config, if set, prefixed with \`ci/\`, or an empty string if \`ci-name\` is empty. `, flatten (key, obj, flatOptions) { const value = obj[key] const ciName = ciInfo.name?.toLowerCase().split(' ').join('-') || null let inWorkspaces = false if (obj.workspaces || obj.workspace && obj.workspace.length) { inWorkspaces = true } flatOptions.userAgent = value.replace(/\{node-version\}/gi, process.version) .replace(/\{npm-version\}/gi, obj['npm-version']) .replace(/\{platform\}/gi, process.platform) .replace(/\{arch\}/gi, process.arch) .replace(/\{workspaces\}/gi, inWorkspaces) .replace(/\{ci\}/gi, ciName ? `ci/${ciName}` : '') .trim() // We can't clobber the original or else subsequent flattening will fail // (i.e. when we change the underlying config values) // obj[key] = flatOptions.userAgent // user-agent is a unique kind of config item that gets set from a template // and ends up translated. Because of this, the normal "should we set this // to process.env also doesn't work process.env.npm_config_user_agent = flatOptions.userAgent }, }), userconfig: new Definition('userconfig', { default: '~/.npmrc', type: path, description: ` The location of user-level configuration settings. This may be overridden by the \`npm_config_userconfig\` environment variable or the \`--userconfig\` command line option, but may _not_ be overridden by settings in the \`globalconfig\` file. `, }), version: new Definition('version', { default: false, type: Boolean, short: 'v', description: ` If true, output the npm version and exit successfully. Only relevant when specified explicitly on the command line. `, }), versions: new Definition('versions', { default: false, type: Boolean, description: ` If true, output the npm version as well as node's \`process.versions\` map and the version in the current working directory's \`package.json\` file if one exists, and exit successfully. Only relevant when specified explicitly on the command line. `, }), viewer: new Definition('viewer', { default: isWindows ? 'browser' : 'man', defaultDescription: ` "man" on Posix, "browser" on Windows `, type: String, description: ` The program to use to view help content. Set to \`"browser"\` to view html help content in the default web browser. `, }), which: new Definition('which', { default: null, hint: '', type: [null, Number], description: ` If there are multiple funding sources, which 1-indexed source URL to open. `, }), workspace: new Definition('workspace', { default: [], type: [String, Array], hint: '', short: 'w', envExport: false, description: ` Enable running a command in the context of the configured workspaces of the current project while filtering by running only the workspaces defined by this configuration option. Valid values for the \`workspace\` config are either: * Workspace names * Path to a workspace directory * Path to a parent workspace directory (will result in selecting all workspaces within that folder) When set for the \`npm init\` command, this may be set to the folder of a workspace which does not yet exist, to create the folder and set it up as a brand new workspace within the project. `, flatten: (key, obj, flatOptions) => { definitions['user-agent'].flatten('user-agent', obj, flatOptions) }, }), workspaces: new Definition('workspaces', { default: null, type: [null, Boolean], short: 'ws', envExport: false, description: ` Set to true to run the command in the context of **all** configured workspaces. Explicitly setting this to false will cause commands like \`install\` to ignore workspaces altogether. When not set explicitly: - Commands that operate on the \`node_modules\` tree (install, update, etc.) will link workspaces into the \`node_modules\` folder. - Commands that do other things (test, exec, publish, etc.) will operate on the root project, _unless_ one or more workspaces are specified in the \`workspace\` config. `, flatten: (key, obj, flatOptions) => { definitions['user-agent'].flatten('user-agent', obj, flatOptions) // TODO: this is a derived value, and should be reworked when we have a // pattern for derived value // workspacesEnabled is true whether workspaces is null or true // commands contextually work with workspaces or not regardless of // configuration, so we need an option specifically to disable workspaces flatOptions.workspacesEnabled = obj[key] !== false }, }), 'workspaces-update': new Definition('workspaces-update', { default: true, type: Boolean, description: ` If set to true, the npm cli will run an update after operations that may possibly change the workspaces installed to the \`node_modules\` folder. `, flatten, }), yes: new Definition('yes', { default: null, type: [null, Boolean], short: 'y', description: ` Automatically answer "yes" to any prompts that npm might print on the command line. `, }), } module.exports = definitions PK ~\""'@npmcli/config/lib/definitions/index.jsnu[const definitions = require('./definitions.js') // use the defined flattening function, and copy over any scoped // registries and registry-specific "nerfdart" configs verbatim // // TODO: make these getters so that we only have to make dirty // the thing that changed, and then flatten the fields that // could have changed when a config.set is called. // // TODO: move nerfdart auth stuff into a nested object that // is only passed along to paths that end up calling npm-registry-fetch. const flatten = (obj, flat = {}) => { for (const [key, val] of Object.entries(obj)) { const def = definitions[key] if (def && def.flatten) { def.flatten(key, obj, flat) } else if (/@.*:registry$/i.test(key) || /^\/\//.test(key)) { flat[key] = val } } return flat } const definitionProps = Object.entries(definitions) .reduce((acc, [key, { short = [], default: d }]) => { // can be either an array or string for (const s of [].concat(short)) { acc.shorthands[s] = [`--${key}`] } acc.defaults[key] = d return acc }, { shorthands: {}, defaults: {} }) // aliases where they get expanded into a completely different thing // these are NOT supported in the environment or npmrc files, only // expanded on the CLI. // TODO: when we switch off of nopt, use an arg parser that supports // more reasonable aliasing and short opts right in the definitions set. const shorthands = { 'enjoy-by': ['--before'], d: ['--loglevel', 'info'], dd: ['--loglevel', 'verbose'], ddd: ['--loglevel', 'silly'], quiet: ['--loglevel', 'warn'], q: ['--loglevel', 'warn'], s: ['--loglevel', 'silent'], silent: ['--loglevel', 'silent'], verbose: ['--loglevel', 'verbose'], desc: ['--description'], help: ['--usage'], local: ['--no-global'], n: ['--no-yes'], no: ['--no-yes'], porcelain: ['--parseable'], readonly: ['--read-only'], reg: ['--registry'], iwr: ['--include-workspace-root'], ...definitionProps.shorthands, } module.exports = { defaults: definitionProps.defaults, definitions, flatten, shorthands, } PK ~\+Jkk,@npmcli/config/lib/definitions/definition.jsnu[// class that describes a config key we know about // this keeps us from defining a config key and not // providing a default, description, etc. // // TODO: some kind of categorization system, so we can // say "these are for registry access", "these are for // version resolution" etc. const required = ['type', 'description', 'default', 'key'] const allowed = [ 'default', 'defaultDescription', 'deprecated', 'description', 'exclusive', 'flatten', 'hint', 'key', 'short', 'type', 'typeDescription', 'usage', 'envExport', ] const { semver: { type: semver }, Umask: { type: Umask }, url: { type: url }, path: { type: path }, } = require('../type-defs.js') class Definition { constructor (key, def) { this.key = key // if it's set falsey, don't export it, otherwise we do by default this.envExport = true Object.assign(this, def) this.validate() if (!this.defaultDescription) { this.defaultDescription = describeValue(this.default) } if (!this.typeDescription) { this.typeDescription = describeType(this.type) } // hint is only used for non-boolean values if (!this.hint) { if (this.type === Number) { this.hint = '' } else { this.hint = `<${this.key}>` } } if (!this.usage) { this.usage = describeUsage(this) } } validate () { for (const req of required) { if (!Object.prototype.hasOwnProperty.call(this, req)) { throw new Error(`config lacks ${req}: ${this.key}`) } } if (!this.key) { throw new Error(`config lacks key: ${this.key}`) } for (const field of Object.keys(this)) { if (!allowed.includes(field)) { throw new Error(`config defines unknown field ${field}: ${this.key}`) } } } // a textual description of this config, suitable for help output describe () { const description = unindent(this.description) const noEnvExport = this.envExport ? '' : ` This value is not exported to the environment for child processes. ` const deprecated = !this.deprecated ? '' : `* DEPRECATED: ${unindent(this.deprecated)}\n` /* eslint-disable-next-line max-len */ const exclusive = !this.exclusive ? '' : `\nThis config can not be used with: \`${this.exclusive.join('`, `')}\`` return wrapAll(`#### \`${this.key}\` * Default: ${unindent(this.defaultDescription)} * Type: ${unindent(this.typeDescription)} ${deprecated} ${description} ${exclusive} ${noEnvExport}`) } } const describeUsage = def => { let key = '' // Single type if (!Array.isArray(def.type)) { if (def.short) { key = `-${def.short}|` } if (def.type === Boolean && def.default !== false) { key = `${key}--no-${def.key}` } else { key = `${key}--${def.key}` } if (def.type !== Boolean) { key = `${key} ${def.hint}` } return key } key = `--${def.key}` if (def.short) { key = `-${def.short}|--${def.key}` } // Multiple types let types = def.type const multiple = types.includes(Array) const bool = types.includes(Boolean) // null type means optional and doesn't currently affect usage output since // all non-optional params have defaults so we render everything as optional types = types.filter(t => t !== null && t !== Array && t !== Boolean) if (!types.length) { return key } let description if (!types.some(t => typeof t !== 'string')) { // Specific values, use specifics given description = `<${types.filter(d => d).join('|')}>` } else { // Generic values, use hint description = def.hint } if (bool) { // Currently none of our multi-type configs with boolean values default to // false so all their hints should show `--no-`, if we ever add ones that // default to false we can branch the logic here key = `--no-${def.key}|${key}` } const usage = `${key} ${description}` if (multiple) { return `${usage} [${usage} ...]` } else { return usage } } const describeType = type => { if (Array.isArray(type)) { const descriptions = type.filter(t => t !== Array).map(t => describeType(t)) // [a] => "a" // [a, b] => "a or b" // [a, b, c] => "a, b, or c" // [a, Array] => "a (can be set multiple times)" // [a, Array, b] => "a or b (can be set multiple times)" const last = descriptions.length > 1 ? [descriptions.pop()] : [] const oxford = descriptions.length > 1 ? ', or ' : ' or ' const words = [descriptions.join(', ')].concat(last).join(oxford) const multiple = type.includes(Array) ? ' (can be set multiple times)' : '' return `${words}${multiple}` } // Note: these are not quite the same as the description printed // when validation fails. In that case, we want to give the user // a bit more information to help them figure out what's wrong. switch (type) { case String: return 'String' case Number: return 'Number' case Umask: return 'Octal numeric string in range 0000..0777 (0..511)' case Boolean: return 'Boolean' case Date: return 'Date' case path: return 'Path' case semver: return 'SemVer string' case url: return 'URL' default: return describeValue(type) } } // if it's a string, quote it. otherwise, just cast to string. const describeValue = val => (typeof val === 'string' ? JSON.stringify(val) : String(val)) const unindent = s => { // get the first \n followed by a bunch of spaces, and pluck off // that many spaces from the start of every line. const match = s.match(/\n +/) return !match ? s.trim() : s.split(match[0]).join('\n').trim() } const wrap = s => { const cols = Math.min(Math.max(20, process.stdout.columns) || 80, 80) - 5 return unindent(s) .split(/[ \n]+/) .reduce((left, right) => { const last = left.split('\n').pop() const join = last.length && last.length + right.length > cols ? '\n' : ' ' return left + join + right }) } const wrapAll = s => { let inCodeBlock = false return s .split('\n\n') .map(block => { if (inCodeBlock || block.startsWith('```')) { inCodeBlock = !block.endsWith('```') return block } if (block.charAt(0) === '*') { return ( '* ' + block .slice(1) .trim() .split('\n* ') .map(li => { return wrap(li).replace(/\n/g, '\n ') }) .join('\n* ') ) } else { return wrap(block) } }) .join('\n\n') } module.exports = Definition PK ~\?0E!ll@npmcli/config/lib/type-defs.jsnu[const nopt = require('nopt') const { validate: validateUmask } = require('./umask.js') class Umask {} class Semver {} const semverValid = require('semver/functions/valid') const validateSemver = (data, k, val) => { const valid = semverValid(val) if (!valid) { return false } data[k] = valid } const noptValidatePath = nopt.typeDefs.path.validate const validatePath = (data, k, val) => { if (typeof val !== 'string') { return false } return noptValidatePath(data, k, val) } // add descriptions so we can validate more usefully module.exports = { ...nopt.typeDefs, semver: { type: Semver, validate: validateSemver, description: 'full valid SemVer string', }, Umask: { type: Umask, validate: validateUmask, description: 'octal number in range 0o000..0o777 (0..511)', }, url: { ...nopt.typeDefs.url, description: 'full url with "http://"', }, path: { ...nopt.typeDefs.path, validate: validatePath, description: 'valid filesystem path', }, Number: { ...nopt.typeDefs.Number, description: 'numeric value', }, Boolean: { ...nopt.typeDefs.Boolean, description: 'boolean value (true or false)', }, Date: { ...nopt.typeDefs.Date, description: 'valid Date string', }, } // TODO: make nopt less of a global beast so this kludge isn't necessary nopt.typeDefs = module.exports PK ~\<>>&@npmcli/config/lib/type-description.jsnu[// return the description of the valid values of a field // returns a string for one thing, or an array of descriptions const typeDefs = require('./type-defs.js') const typeDescription = t => { if (!t || typeof t !== 'function' && typeof t !== 'object') { return t } if (Array.isArray(t)) { return t.map(t => typeDescription(t)) } for (const { type, description } of Object.values(typeDefs)) { if (type === t) { return description || type } } return t } module.exports = t => [].concat(typeDescription(t)).filter(t => t !== undefined) PK ~\|&-pp@npmcli/config/lib/index.jsnu[// TODO: set the scope config from package.json or explicit cli config const { walkUp } = require('walk-up-path') const ini = require('ini') const nopt = require('nopt') const { log, time } = require('proc-log') const { resolve, dirname, join } = require('node:path') const { homedir } = require('node:os') const { readFile, writeFile, chmod, unlink, stat, mkdir, } = require('node:fs/promises') const fileExists = (...p) => stat(resolve(...p)) .then((st) => st.isFile()) .catch(() => false) const dirExists = (...p) => stat(resolve(...p)) .then((st) => st.isDirectory()) .catch(() => false) const hasOwnProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key) const typeDefs = require('./type-defs.js') const nerfDart = require('./nerf-dart.js') const envReplace = require('./env-replace.js') const parseField = require('./parse-field.js') const setEnvs = require('./set-envs.js') // types that can be saved back to const confFileTypes = new Set([ 'global', 'user', 'project', ]) const confTypes = new Set([ 'default', 'builtin', ...confFileTypes, 'env', 'cli', ]) class Config { #loaded = false #flatten // populated the first time we flatten the object #flatOptions = null static get typeDefs () { return typeDefs } constructor ({ definitions, shorthands, flatten, npmPath, // options just to override in tests, mostly env = process.env, argv = process.argv, platform = process.platform, execPath = process.execPath, cwd = process.cwd(), excludeNpmCwd = false, }) { // turn the definitions into nopt's weirdo syntax this.definitions = definitions const types = {} const defaults = {} this.deprecated = {} for (const [key, def] of Object.entries(definitions)) { defaults[key] = def.default types[key] = def.type if (def.deprecated) { this.deprecated[key] = def.deprecated.trim().replace(/\n +/, '\n') } } this.#flatten = flatten this.types = types this.shorthands = shorthands this.defaults = defaults this.npmPath = npmPath this.npmBin = join(this.npmPath, 'bin/npm-cli.js') this.argv = argv this.env = env this.execPath = execPath this.platform = platform this.cwd = cwd this.excludeNpmCwd = excludeNpmCwd // set when we load configs this.globalPrefix = null this.localPrefix = null this.localPackage = null // defaults to env.HOME, but will always be *something* this.home = null // set up the prototype chain of config objects const wheres = [...confTypes] this.data = new Map() let parent = null for (const where of wheres) { this.data.set(where, parent = new ConfigData(parent)) } this.data.set = () => { throw new Error('cannot change internal config data structure') } this.data.delete = () => { throw new Error('cannot change internal config data structure') } this.sources = new Map([]) this.list = [] for (const { data } of this.data.values()) { this.list.unshift(data) } Object.freeze(this.list) this.#loaded = false } get loaded () { return this.#loaded } get prefix () { return this.#get('global') ? this.globalPrefix : this.localPrefix } // return the location where key is found. find (key) { if (!this.loaded) { throw new Error('call config.load() before reading values') } // have to look in reverse order const entries = [...this.data.entries()] for (let i = entries.length - 1; i > -1; i--) { const [where, { data }] = entries[i] if (hasOwnProperty(data, key)) { return where } } return null } get (key, where) { if (!this.loaded) { throw new Error('call config.load() before reading values') } return this.#get(key, where) } // we need to get values sometimes, so use this internal one to do so // while in the process of loading. #get (key, where = null) { if (where !== null && !confTypes.has(where)) { throw new Error('invalid config location param: ' + where) } const { data } = this.data.get(where || 'cli') return where === null || hasOwnProperty(data, key) ? data[key] : undefined } set (key, val, where = 'cli') { if (!this.loaded) { throw new Error('call config.load() before setting values') } if (!confTypes.has(where)) { throw new Error('invalid config location param: ' + where) } this.#checkDeprecated(key) const { data, raw } = this.data.get(where) data[key] = val if (['global', 'user', 'project'].includes(where)) { raw[key] = val } // this is now dirty, the next call to this.valid will have to check it this.data.get(where)[_valid] = null // the flat options are invalidated, regenerate next time they're needed this.#flatOptions = null } get flat () { if (this.#flatOptions) { return this.#flatOptions } // create the object for flat options passed to deps const timeEnd = time.start('config:load:flatten') this.#flatOptions = {} // walk from least priority to highest for (const { data } of this.data.values()) { this.#flatten(data, this.#flatOptions) } this.#flatOptions.nodeBin = this.execPath this.#flatOptions.npmBin = this.npmBin timeEnd() return this.#flatOptions } delete (key, where = 'cli') { if (!this.loaded) { throw new Error('call config.load() before deleting values') } if (!confTypes.has(where)) { throw new Error('invalid config location param: ' + where) } const { data, raw } = this.data.get(where) delete data[key] if (['global', 'user', 'project'].includes(where)) { delete raw[key] } } async load () { if (this.loaded) { throw new Error('attempting to load npm config multiple times') } // first load the defaults, which sets the global prefix this.loadDefaults() // next load the builtin config, as this sets new effective defaults await this.loadBuiltinConfig() // cli and env are not async, and can set the prefix, relevant to project this.loadCLI() this.loadEnv() // next project config, which can affect userconfig location await this.loadProjectConfig() // then user config, which can affect globalconfig location await this.loadUserConfig() // last but not least, global config file await this.loadGlobalConfig() // set this before calling setEnvs, so that we don't have to share // private attributes, as that module also does a bunch of get operations this.#loaded = true // set proper globalPrefix now that everything is loaded this.globalPrefix = this.get('prefix') this.setEnvs() } loadDefaults () { this.loadGlobalPrefix() this.loadHome() const defaultsObject = { ...this.defaults, prefix: this.globalPrefix, } try { defaultsObject['npm-version'] = require(join(this.npmPath, 'package.json')).version } catch { // in some weird state where the passed in npmPath does not have a package.json // this will never happen in npm, but is guarded here in case this is consumed // in other ways + tests } this.#loadObject(defaultsObject, 'default', 'default values') const { data } = this.data.get('default') // if the prefix is set on cli, env, or userconfig, then we need to // default the globalconfig file to that location, instead of the default // global prefix. It's weird that `npm get globalconfig --prefix=/foo` // returns `/foo/etc/npmrc`, but better to not change it at this point. // define a custom getter, but turn into a normal prop // if we set it. otherwise it can't be set on child objects Object.defineProperty(data, 'globalconfig', { get: () => resolve(this.#get('prefix'), 'etc/npmrc'), set (value) { Object.defineProperty(data, 'globalconfig', { value, configurable: true, writable: true, enumerable: true, }) }, configurable: true, enumerable: true, }) } loadHome () { this.home = this.env.HOME || homedir() } loadGlobalPrefix () { if (this.globalPrefix) { throw new Error('cannot load default global prefix more than once') } if (this.env.PREFIX) { this.globalPrefix = this.env.PREFIX } else if (this.platform === 'win32') { // c:\node\node.exe --> prefix=c:\node\ this.globalPrefix = dirname(this.execPath) } else { // /usr/local/bin/node --> prefix=/usr/local this.globalPrefix = dirname(dirname(this.execPath)) // destdir only is respected on Unix if (this.env.DESTDIR) { this.globalPrefix = join(this.env.DESTDIR, this.globalPrefix) } } } loadEnv () { const conf = Object.create(null) for (const [envKey, envVal] of Object.entries(this.env)) { if (!/^npm_config_/i.test(envKey) || envVal === '') { continue } let key = envKey.slice('npm_config_'.length) if (!key.startsWith('//')) { // don't normalize nerf-darted keys key = key.replace(/(?!^)_/g, '-') // don't replace _ at the start of the key .toLowerCase() } conf[key] = envVal } this.#loadObject(conf, 'env', 'environment') } loadCLI () { nopt.invalidHandler = (k, val, type) => this.invalidHandler(k, val, type, 'command line options', 'cli') const conf = nopt(this.types, this.shorthands, this.argv) nopt.invalidHandler = null this.parsedArgv = conf.argv delete conf.argv this.#loadObject(conf, 'cli', 'command line options') } get valid () { for (const [where, { valid }] of this.data.entries()) { if (valid === false || valid === null && !this.validate(where)) { return false } } return true } validate (where) { if (!where) { let valid = true const authProblems = [] for (const entryWhere of this.data.keys()) { // no need to validate our defaults, we know they're fine // cli was already validated when parsed the first time if (entryWhere === 'default' || entryWhere === 'builtin' || entryWhere === 'cli') { continue } const ret = this.validate(entryWhere) valid = valid && ret if (['global', 'user', 'project'].includes(entryWhere)) { // after validating everything else, we look for old auth configs we no longer support // if these keys are found, we build up a list of them and the appropriate action and // attach it as context on the thrown error // first, keys that should be removed for (const key of ['_authtoken', '-authtoken']) { if (this.get(key, entryWhere)) { authProblems.push({ action: 'delete', key, where: entryWhere }) } } // NOTE we pull registry without restricting to the current 'where' because we want to // suggest scoping things to the registry they would be applied to, which is the default // regardless of where it was defined const nerfedReg = nerfDart(this.get('registry')) // keys that should be nerfed but currently are not for (const key of ['_auth', '_authToken', 'username', '_password']) { if (this.get(key, entryWhere)) { // username and _password must both exist in the same file to be recognized correctly if (key === 'username' && !this.get('_password', entryWhere)) { authProblems.push({ action: 'delete', key, where: entryWhere }) } else if (key === '_password' && !this.get('username', entryWhere)) { authProblems.push({ action: 'delete', key, where: entryWhere }) } else { authProblems.push({ action: 'rename', from: key, to: `${nerfedReg}:${key}`, where: entryWhere, }) } } } } } if (authProblems.length) { const { ErrInvalidAuth } = require('./errors.js') throw new ErrInvalidAuth(authProblems) } return valid } else { const obj = this.data.get(where) obj[_valid] = true nopt.invalidHandler = (k, val, type) => this.invalidHandler(k, val, type, obj.source, where) nopt.clean(obj.data, this.types, typeDefs) nopt.invalidHandler = null return obj[_valid] } } // fixes problems identified by validate(), accepts the 'problems' property from a thrown // ErrInvalidAuth to avoid having to check everything again repair (problems) { if (!problems) { try { this.validate() } catch (err) { // coverage skipped here because we don't need to test re-throwing an error // istanbul ignore next if (err.code !== 'ERR_INVALID_AUTH') { throw err } problems = err.problems } finally { if (!problems) { problems = [] } } } for (const problem of problems) { // coverage disabled for else branch because it doesn't do anything and shouldn't // istanbul ignore else if (problem.action === 'delete') { this.delete(problem.key, problem.where) } else if (problem.action === 'rename') { const raw = this.data.get(problem.where).raw?.[problem.from] const calculated = this.get(problem.from, problem.where) this.set(problem.to, raw || calculated, problem.where) this.delete(problem.from, problem.where) } } } // Returns true if the value is coming directly from the source defined // in default definitions, if the current value for the key config is // coming from any other different source, returns false isDefault (key) { const [defaultType, ...types] = [...confTypes] const defaultData = this.data.get(defaultType).data return hasOwnProperty(defaultData, key) && types.every(type => { const typeData = this.data.get(type).data return !hasOwnProperty(typeData, key) }) } invalidHandler (k, val, type, source, where) { const typeDescription = require('./type-description.js') log.warn( 'invalid config', k + '=' + JSON.stringify(val), `set in ${source}` ) this.data.get(where)[_valid] = false if (Array.isArray(type)) { if (type.includes(typeDefs.url.type)) { type = typeDefs.url.type } else { /* istanbul ignore if - no actual configs matching this, but * path types SHOULD be handled this way, like URLs, for the * same reason */ if (type.includes(typeDefs.path.type)) { type = typeDefs.path.type } } } const typeDesc = typeDescription(type) const mustBe = typeDesc .filter(m => m !== undefined && m !== Array) const msg = 'Must be' + this.#getOneOfKeywords(mustBe, typeDesc) const desc = mustBe.length === 1 ? mustBe[0] : [...new Set(mustBe.map(n => typeof n === 'string' ? n : JSON.stringify(n)))].join(', ') log.warn('invalid config', msg, desc) } #getOneOfKeywords (mustBe, typeDesc) { let keyword if (mustBe.length === 1 && typeDesc.includes(Array)) { keyword = ' one or more' } else if (mustBe.length > 1 && typeDesc.includes(Array)) { keyword = ' one or more of:' } else if (mustBe.length > 1) { keyword = ' one of:' } else { keyword = '' } return keyword } #loadObject (obj, where, source, er = null) { // obj is the raw data read from the file const conf = this.data.get(where) if (conf.source) { const m = `double-loading "${where}" configs from ${source}, ` + `previously loaded from ${conf.source}` throw new Error(m) } if (this.sources.has(source)) { const m = `double-loading config "${source}" as "${where}", ` + `previously loaded as "${this.sources.get(source)}"` throw new Error(m) } conf.source = source this.sources.set(source, where) if (er) { conf.loadError = er if (er.code !== 'ENOENT') { log.verbose('config', `error loading ${where} config`, er) } } else { conf.raw = obj for (const [key, value] of Object.entries(obj)) { const k = envReplace(key, this.env) const v = this.parseField(value, k) if (where !== 'default') { this.#checkDeprecated(k) if (this.definitions[key]?.exclusive) { for (const exclusive of this.definitions[key].exclusive) { if (!this.isDefault(exclusive)) { throw new TypeError(`--${key} can not be provided when using --${exclusive}`) } } } } conf.data[k] = v } } } #checkDeprecated (key) { // XXX(npm9+) make this throw an error if (this.deprecated[key]) { log.warn('config', key, this.deprecated[key]) } } // Parse a field, coercing it to the best type available. parseField (f, key, listElement = false) { return parseField(f, key, this, listElement) } async #loadFile (file, type) { // only catch the error from readFile, not from the loadObject call log.silly('config', `load:file:${file}`) await readFile(file, 'utf8').then( data => { const parsedConfig = ini.parse(data) if (type === 'project' && parsedConfig.prefix) { // Log error if prefix is mentioned in project .npmrc /* eslint-disable-next-line max-len */ log.error('config', `prefix cannot be changed from project config: ${file}.`) } return this.#loadObject(parsedConfig, type, file) }, er => this.#loadObject(null, type, file, er) ) } loadBuiltinConfig () { return this.#loadFile(resolve(this.npmPath, 'npmrc'), 'builtin') } async loadProjectConfig () { // the localPrefix can be set by the CLI config, but otherwise is // found by walking up the folder tree. either way, we load it before // we return to make sure localPrefix is set await this.loadLocalPrefix() // if we have not detected a local package json yet, try now that we // have a local prefix if (this.localPackage == null) { this.localPackage = await fileExists(this.localPrefix, 'package.json') } if (this.#get('global') === true || this.#get('location') === 'global') { this.data.get('project').source = '(global mode enabled, ignored)' this.sources.set(this.data.get('project').source, 'project') return } const projectFile = resolve(this.localPrefix, '.npmrc') // if we're in the ~ directory, and there happens to be a node_modules // folder (which is not TOO uncommon, it turns out), then we can end // up loading the "project" config where the "userconfig" will be, // which causes some calamaties. So, we only load project config if // it doesn't match what the userconfig will be. if (projectFile !== this.#get('userconfig')) { return this.#loadFile(projectFile, 'project') } else { this.data.get('project').source = '(same as "user" config, ignored)' this.sources.set(this.data.get('project').source, 'project') } } async loadLocalPrefix () { const cliPrefix = this.#get('prefix', 'cli') if (cliPrefix) { this.localPrefix = cliPrefix return } const cliWorkspaces = this.#get('workspaces', 'cli') const isGlobal = this.#get('global') || this.#get('location') === 'global' for (const p of walkUp(this.cwd)) { // HACK: this is an option set in tests to stop the local prefix from being set // on tests that are created inside the npm repo if (this.excludeNpmCwd && p === this.npmPath) { break } const hasPackageJson = await fileExists(p, 'package.json') if (!this.localPrefix && (hasPackageJson || await dirExists(p, 'node_modules'))) { this.localPrefix = p this.localPackage = hasPackageJson // if workspaces are disabled, or we're in global mode, return now if (cliWorkspaces === false || isGlobal) { return } // otherwise, continue the loop continue } if (this.localPrefix && hasPackageJson) { const rpj = require('read-package-json-fast') // if we already set localPrefix but this dir has a package.json // then we need to see if `p` is a workspace root by reading its package.json // however, if reading it fails then we should just move on const pkg = await rpj(resolve(p, 'package.json')).catch(() => false) if (!pkg) { continue } const mapWorkspaces = require('@npmcli/map-workspaces') const workspaces = await mapWorkspaces({ cwd: p, pkg }) for (const w of workspaces.values()) { if (w === this.localPrefix) { // see if there's a .npmrc file in the workspace, if so log a warning if (await fileExists(this.localPrefix, '.npmrc')) { log.warn('config', `ignoring workspace config at ${this.localPrefix}/.npmrc`) } // set the workspace in the default layer, which allows it to be overridden easily const { data } = this.data.get('default') data.workspace = [this.localPrefix] this.localPrefix = p this.localPackage = hasPackageJson log.info('config', `found workspace root at ${this.localPrefix}`) // we found a root, so we return now return } } } } if (!this.localPrefix) { this.localPrefix = this.cwd } } loadUserConfig () { return this.#loadFile(this.#get('userconfig'), 'user') } loadGlobalConfig () { return this.#loadFile(this.#get('globalconfig'), 'global') } async save (where) { if (!this.loaded) { throw new Error('call config.load() before saving') } if (!confFileTypes.has(where)) { throw new Error('invalid config location param: ' + where) } const conf = this.data.get(where) conf[_loadError] = null if (where === 'user') { // if email is nerfed, then we want to de-nerf it const nerfed = nerfDart(this.get('registry')) const email = this.get(`${nerfed}:email`, 'user') if (email) { this.delete(`${nerfed}:email`, 'user') this.set('email', email, 'user') } } // We need the actual raw data before we called parseField so that we are // saving the same content back to the file const iniData = ini.stringify(conf.raw).trim() + '\n' if (!iniData.trim()) { // ignore the unlink error (eg, if file doesn't exist) await unlink(conf.source).catch(() => {}) return } const dir = dirname(conf.source) await mkdir(dir, { recursive: true }) await writeFile(conf.source, iniData, 'utf8') const mode = where === 'user' ? 0o600 : 0o666 await chmod(conf.source, mode) } clearCredentialsByURI (uri, level = 'user') { const nerfed = nerfDart(uri) const def = nerfDart(this.get('registry')) if (def === nerfed) { this.delete(`-authtoken`, level) this.delete(`_authToken`, level) this.delete(`_authtoken`, level) this.delete(`_auth`, level) this.delete(`_password`, level) this.delete(`username`, level) // de-nerf email if it's nerfed to the default registry const email = this.get(`${nerfed}:email`, level) if (email) { this.set('email', email, level) } } this.delete(`${nerfed}:_authToken`, level) this.delete(`${nerfed}:_auth`, level) this.delete(`${nerfed}:_password`, level) this.delete(`${nerfed}:username`, level) this.delete(`${nerfed}:email`, level) this.delete(`${nerfed}:certfile`, level) this.delete(`${nerfed}:keyfile`, level) } setCredentialsByURI (uri, { token, username, password, certfile, keyfile }) { const nerfed = nerfDart(uri) // field that hasn't been used as documented for a LONG time, // and as of npm 7.10.0, isn't used at all. We just always // send auth if we have it, only to the URIs under the nerf dart. this.delete(`${nerfed}:always-auth`, 'user') this.delete(`${nerfed}:email`, 'user') if (certfile && keyfile) { this.set(`${nerfed}:certfile`, certfile, 'user') this.set(`${nerfed}:keyfile`, keyfile, 'user') // cert/key may be used in conjunction with other credentials, thus no `else` } if (token) { this.set(`${nerfed}:_authToken`, token, 'user') this.delete(`${nerfed}:_password`, 'user') this.delete(`${nerfed}:username`, 'user') } else if (username || password) { if (!username) { throw new Error('must include username') } if (!password) { throw new Error('must include password') } this.delete(`${nerfed}:_authToken`, 'user') this.set(`${nerfed}:username`, username, 'user') // note: not encrypted, no idea why we bothered to do this, but oh well // protects against shoulder-hacks if password is memorable, I guess? const encoded = Buffer.from(password, 'utf8').toString('base64') this.set(`${nerfed}:_password`, encoded, 'user') } else if (!certfile || !keyfile) { throw new Error('No credentials to set.') } } // this has to be a bit more complicated to support legacy data of all forms getCredentialsByURI (uri) { const nerfed = nerfDart(uri) const def = nerfDart(this.get('registry')) const creds = {} // email is handled differently, it used to always be nerfed and now it never should be // if it's set nerfed to the default registry, then we copy it to the unnerfed key // TODO: evaluate removing 'email' from the credentials object returned here const email = this.get(`${nerfed}:email`) || this.get('email') if (email) { if (nerfed === def) { this.set('email', email, 'user') } creds.email = email } const certfileReg = this.get(`${nerfed}:certfile`) const keyfileReg = this.get(`${nerfed}:keyfile`) if (certfileReg && keyfileReg) { creds.certfile = certfileReg creds.keyfile = keyfileReg // cert/key may be used in conjunction with other credentials, thus no `return` } const tokenReg = this.get(`${nerfed}:_authToken`) if (tokenReg) { creds.token = tokenReg return creds } const userReg = this.get(`${nerfed}:username`) const passReg = this.get(`${nerfed}:_password`) if (userReg && passReg) { creds.username = userReg creds.password = Buffer.from(passReg, 'base64').toString('utf8') const auth = `${creds.username}:${creds.password}` creds.auth = Buffer.from(auth, 'utf8').toString('base64') return creds } const authReg = this.get(`${nerfed}:_auth`) if (authReg) { const authDecode = Buffer.from(authReg, 'base64').toString('utf8') const authSplit = authDecode.split(':') creds.username = authSplit.shift() creds.password = authSplit.join(':') creds.auth = authReg return creds } // at this point, nothing else is usable so just return what we do have return creds } // set up the environment object we have with npm_config_* environs // for all configs that are different from their default values, and // set EDITOR and HOME. setEnvs () { setEnvs(this) } } const _loadError = Symbol('loadError') const _valid = Symbol('valid') class ConfigData { #data #source = null #raw = null constructor (parent) { this.#data = Object.create(parent && parent.data) this.#raw = {} this[_valid] = true } get data () { return this.#data } get valid () { return this[_valid] } set source (s) { if (this.#source) { throw new Error('cannot set ConfigData source more than once') } this.#source = s } get source () { return this.#source } set loadError (e) { if (this[_loadError] || (Object.keys(this.#raw).length)) { throw new Error('cannot set ConfigData loadError after load') } this[_loadError] = e } get loadError () { return this[_loadError] } set raw (r) { if (Object.keys(this.#raw).length || this[_loadError]) { throw new Error('cannot set ConfigData raw after load') } this.#raw = r } get raw () { return this.#raw } } module.exports = Config PK ~\*J@npmcli/config/lib/umask.jsnu[const parse = val => { // this is run via nopt and parse field where everything is // converted to a string first, ignoring coverage for now // instead of figuring out what is happening under the hood in nopt // istanbul ignore else if (typeof val === 'string') { if (/^0o?[0-7]+$/.test(val)) { return parseInt(val.replace(/^0o?/, ''), 8) } else if (/^[1-9][0-9]*$/.test(val)) { return parseInt(val, 10) } else { throw new Error(`invalid umask value: ${val}`) } } else { if (typeof val !== 'number') { throw new Error(`invalid umask value: ${val}`) } val = Math.floor(val) if (val < 0 || val > 511) { throw new Error(`invalid umask value: ${val}`) } return val } } const validate = (data, k, val) => { try { data[k] = parse(val) return true } catch (er) { return false } } module.exports = { parse, validate } PK ~\Q_z!@npmcli/config/lib/env-replace.jsnu[// replace any ${ENV} values with the appropriate environ. const envExpr = /(? f.replace(envExpr, (orig, esc, name) => { const val = env[name] !== undefined ? env[name] : `$\{${name}}` // consume the escape chars that are relevant. if (esc.length % 2) { return orig.slice((esc.length + 1) / 2) } return (esc.slice(esc.length / 2)) + val }) PK ~\pm@npmcli/config/lib/errors.jsnu['use strict' class ErrInvalidAuth extends Error { constructor (problems) { let message = 'Invalid auth configuration found: ' message += problems.map((problem) => { // istanbul ignore else if (problem.action === 'delete') { return `\`${problem.key}\` is not allowed in ${problem.where} config` } else if (problem.action === 'rename') { return `\`${problem.from}\` must be renamed to \`${problem.to}\` in ${problem.where} config` } }).join(', ') message += '\nPlease run `npm config fix` to repair your configuration.`' super(message) this.code = 'ERR_INVALID_AUTH' this.problems = problems } } module.exports = { ErrInvalidAuth, } PK ~\[ @npmcli/config/lib/set-envs.jsnu[// Set environment variables for any non-default configs, // so that they're already there when we run lifecycle scripts. // // See https://github.com/npm/rfcs/pull/90 // Return the env key if this is a thing that belongs in the env. // Ie, if the key isn't a @scope, //nerf.dart, or _private, // and the value is a string or array. Otherwise return false. const envKey = (key, val) => { return !/^[/@_]/.test(key) && (typeof envVal(val) === 'string') && `npm_config_${key.replace(/-/g, '_').toLowerCase()}` } const envVal = val => Array.isArray(val) ? val.map(v => envVal(v)).join('\n\n') : val === null || val === undefined || val === false ? '' : typeof val === 'object' ? null : String(val) const sameConfigValue = (def, val) => !Array.isArray(val) || !Array.isArray(def) ? def === val : sameArrayValue(def, val) const sameArrayValue = (def, val) => { if (def.length !== val.length) { return false } for (let i = 0; i < def.length; i++) { /* istanbul ignore next - there are no array configs where the default * is not an empty array, so this loop is a no-op, but it's the correct * thing to do if we ever DO add a config like that. */ if (def[i] !== val[i]) { return false } } return true } const setEnv = (env, rawKey, rawVal) => { const val = envVal(rawVal) const key = envKey(rawKey, val) if (key && val !== null) { env[key] = val } } const setEnvs = (config) => { // This ensures that all npm config values that are not the defaults are // shared appropriately with child processes, without false positives. const { env, defaults, definitions, list: [cliConf, envConf], } = config env.INIT_CWD = process.cwd() // if the key is deprecated, skip it always. // if the key is the default value, // if the environ is NOT the default value, // set the environ // else skip it, it's fine // if the key is NOT the default value, // if the env is setting it, then leave it (already set) // otherwise, set the env const cliSet = new Set(Object.keys(cliConf)) const envSet = new Set(Object.keys(envConf)) for (const key in cliConf) { const { deprecated, envExport = true } = definitions[key] || {} if (deprecated || envExport === false) { continue } if (sameConfigValue(defaults[key], cliConf[key])) { // config is the default, if the env thought different, then we // have to set it BACK to the default in the environment. if (!sameConfigValue(envConf[key], cliConf[key])) { setEnv(env, key, cliConf[key]) } } else { // config is not the default. if the env wasn't the one to set // it that way, then we have to put it in the env if (!(envSet.has(key) && !cliSet.has(key))) { setEnv(env, key, cliConf[key]) } } } // also set some other common nice envs that we want to rely on env.HOME = config.home env.npm_config_global_prefix = config.globalPrefix env.npm_config_local_prefix = config.localPrefix if (cliConf.editor) { env.EDITOR = cliConf.editor } // note: this doesn't afect the *current* node process, of course, since // it's already started, but it does affect the options passed to scripts. if (cliConf['node-options']) { env.NODE_OPTIONS = cliConf['node-options'] } env.npm_execpath = config.npmBin env.NODE = env.npm_node_execpath = config.execPath } module.exports = setEnvs PK ~\,z7!@npmcli/config/lib/parse-field.jsnu[// Parse a field, coercing it to the best type available. const typeDefs = require('./type-defs.js') const envReplace = require('./env-replace.js') const { resolve } = require('node:path') const { parse: umaskParse } = require('./umask.js') const parseField = (f, key, opts, listElement = false) => { if (typeof f !== 'string' && !Array.isArray(f)) { return f } const { platform, types, home, env } = opts // type can be array or a single thing. coerce to array. const typeList = new Set([].concat(types[key])) const isPath = typeList.has(typeDefs.path.type) const isBool = typeList.has(typeDefs.Boolean.type) const isString = isPath || typeList.has(typeDefs.String.type) const isUmask = typeList.has(typeDefs.Umask.type) const isNumber = typeList.has(typeDefs.Number.type) const isList = !listElement && typeList.has(Array) const isDate = typeList.has(typeDefs.Date.type) if (Array.isArray(f)) { return !isList ? f : f.map(field => parseField(field, key, opts, true)) } // now we know it's a string f = f.trim() // list types get put in the environment separated by double-\n // usually a single \n would suffice, but ca/cert configs can contain // line breaks and multiple entries. if (isList) { return parseField(f.split('\n\n'), key, opts) } // --foo is like --foo=true for boolean types if (isBool && !isString && f === '') { return true } // string types can be the string 'true', 'false', etc. // otherwise, parse these values out if (!isString && !isPath && !isNumber) { switch (f) { case 'true': return true case 'false': return false case 'null': return null case 'undefined': return undefined } } f = envReplace(f, env) if (isDate) { return new Date(f) } if (isPath) { const homePattern = platform === 'win32' ? /^~(\/|\\)/ : /^~\// if (homePattern.test(f) && home) { f = resolve(home, f.slice(2)) } else { f = resolve(f) } } if (isUmask) { try { return umaskParse(f) } catch (er) { // let it warn later when we validate return f } } if (isNumber && !isNaN(f)) { f = +f } return f } module.exports = parseField PK ~\.9@npmcli/config/LICENSEnu[The ISC License Copyright (c) npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\eW)9&9&@npmcli/config/README.mdnu[# `@npmcli/config` Configuration management for the npm cli. This module is the spiritual descendant of [`npmconf`](http://npm.im/npmconf), and the code that once lived in npm's `lib/config/` folder. It does the management of configuration files that npm uses, but importantly, does _not_ define all the configuration defaults or types, as those parts make more sense to live within the npm CLI itself. The only exceptions: - The `prefix` config value has some special semantics, setting the local prefix if specified on the CLI options and not in global mode, or the global prefix otherwise. - The `project` config file is loaded based on the local prefix (which can only be set by the CLI config options, and otherwise defaults to a walk up the folder tree to the first parent containing a `node_modules` folder, `package.json` file, or `package-lock.json` file.) - The `userconfig` value, as set by the environment and CLI (defaulting to `~/.npmrc`, is used to load user configs. - The `globalconfig` value, as set by the environment, CLI, and `userconfig` file (defaulting to `$PREFIX/etc/npmrc`) is used to load global configs. - A `builtin` config, read from a `npmrc` file in the root of the npm project itself, overrides all defaults. The resulting hierarchy of configs: - CLI switches. eg `--some-key=some-value` on the command line. These are parsed by [`nopt`](http://npm.im/nopt), which is not a great choice, but it's the one that npm has used forever, and changing it will be difficult. - Environment variables. eg `npm_config_some_key=some_value` in the environment. There is no way at this time to modify this prefix. - INI-formatted project configs. eg `some-key = some-value` in the `localPrefix` folder (ie, the `cwd`, or its nearest parent that contains either a `node_modules` folder or `package.json` file.) - INI-formatted userconfig file. eg `some-key = some-value` in `~/.npmrc`. The `userconfig` config value can be overridden by the `cli`, `env`, or `project` configs to change this value. - INI-formatted globalconfig file. eg `some-key = some-value` in the `globalPrefix` folder, which is inferred by looking at the location of the node executable, or the `prefix` setting in the `cli`, `env`, `project`, or `userconfig`. The `globalconfig` value at any of those levels can override this. - INI-formatted builtin config file. eg `some-key = some-value` in `/usr/local/lib/node_modules/npm/npmrc`. This is not configurable, and is determined by looking in the `npmPath` folder. - Default values (passed in by npm when it loads this module). ## USAGE ```js const Config = require('@npmcli/config') const { shorthands, definitions, flatten } = require('@npmcli/config/lib/definitions') const conf = new Config({ // path to the npm module being run npmPath: resolve(__dirname, '..'), definitions, shorthands, flatten, // optional, defaults to process.argv // argv: [] <- if you are using this package in your own cli // and dont want to have colliding argv argv: process.argv, // optional, defaults to process.env env: process.env, // optional, defaults to process.execPath execPath: process.execPath, // optional, defaults to process.platform platform: process.platform, // optional, defaults to process.cwd() cwd: process.cwd(), }) // emits log events on the process object // see `proc-log` for more info process.on('log', (level, ...args) => { console.log(level, ...args) }) // returns a promise that fails if config loading fails, and // resolves when the config object is ready for action conf.load().then(() => { conf.validate() console.log('loaded ok! some-key = ' + conf.get('some-key')) }).catch(er => { console.error('error loading configs!', er) }) ``` ## API The `Config` class is the sole export. ```js const Config = require('@npmcli/config') ``` ### static `Config.typeDefs` The type definitions passed to `nopt` for CLI option parsing and known configuration validation. ### constructor `new Config(options)` Options: - `types` Types of all known config values. Note that some are effectively given semantic value in the config loading process itself. - `shorthands` An object mapping a shorthand value to an array of CLI arguments that replace it. - `defaults` Default values for each of the known configuration keys. These should be defined for all configs given a type, and must be valid. - `npmPath` The path to the `npm` module, for loading the `builtin` config file. - `cwd` Optional, defaults to `process.cwd()`, used for inferring the `localPrefix` and loading the `project` config. - `platform` Optional, defaults to `process.platform`. Used when inferring the `globalPrefix` from the `execPath`, since this is done diferently on Windows. - `execPath` Optional, defaults to `process.execPath`. Used to infer the `globalPrefix`. - `env` Optional, defaults to `process.env`. Source of the environment variables for configuration. - `argv` Optional, defaults to `process.argv`. Source of the CLI options used for configuration. Returns a `config` object, which is not yet loaded. Fields: - `config.globalPrefix` The prefix for `global` operations. Set by the `prefix` config value, or defaults based on the location of the `execPath` option. - `config.localPrefix` The prefix for `local` operations. Set by the `prefix` config value on the CLI only, or defaults to either the `cwd` or its nearest ancestor containing a `node_modules` folder or `package.json` file. - `config.sources` A read-only `Map` of the file (or a comment, if no file found, or relevant) to the config level loaded from that source. - `config.data` A `Map` of config level to `ConfigData` objects. These objects should not be modified directly under any circumstances. - `source` The source where this data was loaded from. - `raw` The raw data used to generate this config data, as it was parsed initially from the environment, config file, or CLI options. - `data` The data object reflecting the inheritance of configs up to this point in the chain. - `loadError` Any errors encountered that prevented the loading of this config data. - `config.list` A list sorted in priority of all the config data objects in the prototype chain. `config.list[0]` is the `cli` level, `config.list[1]` is the `env` level, and so on. - `cwd` The `cwd` param - `env` The `env` param - `argv` The `argv` param - `execPath` The `execPath` param - `platform` The `platform` param - `defaults` The `defaults` param - `shorthands` The `shorthands` param - `types` The `types` param - `npmPath` The `npmPath` param - `globalPrefix` The effective `globalPrefix` - `localPrefix` The effective `localPrefix` - `prefix` If `config.get('global')` is true, then `globalPrefix`, otherwise `localPrefix` - `home` The user's home directory, found by looking at `env.HOME` or calling `os.homedir()`. - `loaded` A boolean indicating whether or not configs are loaded - `valid` A getter that returns `true` if all the config objects are valid. Any data objects that have been modified with `config.set(...)` will be re-evaluated when `config.valid` is read. ### `config.load()` Load configuration from the various sources of information. Returns a `Promise` that resolves when configuration is loaded, and fails if a fatal error is encountered. ### `config.find(key)` Find the effective place in the configuration levels a given key is set. Returns one of: `cli`, `env`, `project`, `user`, `global`, `builtin`, or `default`. Returns `null` if the key is not set. ### `config.get(key, where = 'cli')` Load the given key from the config stack. ### `config.set(key, value, where = 'cli')` Set the key to the specified value, at the specified level in the config stack. ### `config.delete(key, where = 'cli')` Delete the configuration key from the specified level in the config stack. ### `config.validate(where)` Verify that all known configuration options are set to valid values, and log a warning if they are invalid. Invalid auth options will cause this method to throw an error with a `code` property of `ERR_INVALID_AUTH`, and a `problems` property listing the specific concerns with the current configuration. If `where` is not set, then all config objects are validated. Returns `true` if all configs are valid. Note that it's usually enough (and more efficient) to just check `config.valid`, since each data object is marked for re-evaluation on every `config.set()` operation. ### `config.repair(problems)` Accept an optional array of problems (as thrown by `config.validate()`) and perform the necessary steps to resolve them. If no problems are provided, this method will call `config.validate()` internally to retrieve them. Note that you must `await config.save('user')` in order to persist the changes. ### `config.isDefault(key)` Returns `true` if the value is coming directly from the default definitions, if the current value for the key config is coming from any other source, returns `false`. This method can be used for avoiding or tweaking default values, e.g: > Given a global default definition of foo='foo' it's possible to read that > value such as: > > ```js > const save = config.get('foo') > ``` > > Now in a different place of your app it's possible to avoid using the `foo` > default value, by checking to see if the current config value is currently > one that was defined by the default definitions: > > ```js > const save = config.isDefault('foo') ? 'bar' : config.get('foo') > ``` ### `config.save(where)` Save the config file specified by the `where` param. Must be one of `project`, `user`, `global`, `builtin`. PK ~\mguussri/package.jsonnu[{ "_id": "ssri@10.0.6", "_inBundle": true, "_location": "/npm/ssri", "_phantomChildren": {}, "_requiredBy": [ "/npm", "/npm/@npmcli/arborist", "/npm/cacache", "/npm/libnpmpublish", "/npm/make-fetch-happen", "/npm/pacote" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/ssri/issues" }, "dependencies": { "minipass": "^7.0.3" }, "description": "Standard Subresource Integrity library -- parses, serializes, generates, and verifies integrity metadata according to the SRI spec.", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.22.0", "tap": "^16.0.1" }, "engines": { "node": "^14.17.0 || ^16.13.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/ssri#readme", "keywords": [ "w3c", "web", "security", "integrity", "checksum", "hashing", "subresource integrity", "sri", "sri hash", "sri string", "sri generator", "html" ], "license": "ISC", "main": "lib/index.js", "name": "ssri", "repository": { "type": "git", "url": "git+https://github.com/npm/ssri.git" }, "scripts": { "coverage": "tap", "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "postrelease": "npm publish", "posttest": "npm run lint", "prerelease": "npm t", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "check-coverage": true, "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.22.0", "publish": "true" }, "version": "10.0.6" } PK ~\Ks>>ssri/lib/index.jsnu['use strict' const crypto = require('crypto') const { Minipass } = require('minipass') const SPEC_ALGORITHMS = ['sha512', 'sha384', 'sha256'] const DEFAULT_ALGORITHMS = ['sha512'] // TODO: this should really be a hardcoded list of algorithms we support, // rather than [a-z0-9]. const BASE64_REGEX = /^[a-z0-9+/]+(?:=?=?)$/i const SRI_REGEX = /^([a-z0-9]+)-([^?]+)([?\S*]*)$/ const STRICT_SRI_REGEX = /^([a-z0-9]+)-([A-Za-z0-9+/=]{44,88})(\?[\x21-\x7E]*)?$/ const VCHAR_REGEX = /^[\x21-\x7E]+$/ const getOptString = options => options?.length ? `?${options.join('?')}` : '' class IntegrityStream extends Minipass { #emittedIntegrity #emittedSize #emittedVerified constructor (opts) { super() this.size = 0 this.opts = opts // may be overridden later, but set now for class consistency this.#getOptions() // options used for calculating stream. can't be changed. if (opts?.algorithms) { this.algorithms = [...opts.algorithms] } else { this.algorithms = [...DEFAULT_ALGORITHMS] } if (this.algorithm !== null && !this.algorithms.includes(this.algorithm)) { this.algorithms.push(this.algorithm) } this.hashes = this.algorithms.map(crypto.createHash) } #getOptions () { // For verification this.sri = this.opts?.integrity ? parse(this.opts?.integrity, this.opts) : null this.expectedSize = this.opts?.size if (!this.sri) { this.algorithm = null } else if (this.sri.isHash) { this.goodSri = true this.algorithm = this.sri.algorithm } else { this.goodSri = !this.sri.isEmpty() this.algorithm = this.sri.pickAlgorithm(this.opts) } this.digests = this.goodSri ? this.sri[this.algorithm] : null this.optString = getOptString(this.opts?.options) } on (ev, handler) { if (ev === 'size' && this.#emittedSize) { return handler(this.#emittedSize) } if (ev === 'integrity' && this.#emittedIntegrity) { return handler(this.#emittedIntegrity) } if (ev === 'verified' && this.#emittedVerified) { return handler(this.#emittedVerified) } return super.on(ev, handler) } emit (ev, data) { if (ev === 'end') { this.#onEnd() } return super.emit(ev, data) } write (data) { this.size += data.length this.hashes.forEach(h => h.update(data)) return super.write(data) } #onEnd () { if (!this.goodSri) { this.#getOptions() } const newSri = parse(this.hashes.map((h, i) => { return `${this.algorithms[i]}-${h.digest('base64')}${this.optString}` }).join(' '), this.opts) // Integrity verification mode const match = this.goodSri && newSri.match(this.sri, this.opts) if (typeof this.expectedSize === 'number' && this.size !== this.expectedSize) { /* eslint-disable-next-line max-len */ const err = new Error(`stream size mismatch when checking ${this.sri}.\n Wanted: ${this.expectedSize}\n Found: ${this.size}`) err.code = 'EBADSIZE' err.found = this.size err.expected = this.expectedSize err.sri = this.sri this.emit('error', err) } else if (this.sri && !match) { /* eslint-disable-next-line max-len */ const err = new Error(`${this.sri} integrity checksum failed when using ${this.algorithm}: wanted ${this.digests} but got ${newSri}. (${this.size} bytes)`) err.code = 'EINTEGRITY' err.found = newSri err.expected = this.digests err.algorithm = this.algorithm err.sri = this.sri this.emit('error', err) } else { this.#emittedSize = this.size this.emit('size', this.size) this.#emittedIntegrity = newSri this.emit('integrity', newSri) if (match) { this.#emittedVerified = match this.emit('verified', match) } } } } class Hash { get isHash () { return true } constructor (hash, opts) { const strict = opts?.strict this.source = hash.trim() // set default values so that we make V8 happy to // always see a familiar object template. this.digest = '' this.algorithm = '' this.options = [] // 3.1. Integrity metadata (called "Hash" by ssri) // https://w3c.github.io/webappsec-subresource-integrity/#integrity-metadata-description const match = this.source.match( strict ? STRICT_SRI_REGEX : SRI_REGEX ) if (!match) { return } if (strict && !SPEC_ALGORITHMS.includes(match[1])) { return } this.algorithm = match[1] this.digest = match[2] const rawOpts = match[3] if (rawOpts) { this.options = rawOpts.slice(1).split('?') } } hexDigest () { return this.digest && Buffer.from(this.digest, 'base64').toString('hex') } toJSON () { return this.toString() } match (integrity, opts) { const other = parse(integrity, opts) if (!other) { return false } if (other.isIntegrity) { const algo = other.pickAlgorithm(opts, [this.algorithm]) if (!algo) { return false } const foundHash = other[algo].find(hash => hash.digest === this.digest) if (foundHash) { return foundHash } return false } return other.digest === this.digest ? other : false } toString (opts) { if (opts?.strict) { // Strict mode enforces the standard as close to the foot of the // letter as it can. if (!( // The spec has very restricted productions for algorithms. // https://www.w3.org/TR/CSP2/#source-list-syntax SPEC_ALGORITHMS.includes(this.algorithm) && // Usually, if someone insists on using a "different" base64, we // leave it as-is, since there's multiple standards, and the // specified is not a URL-safe variant. // https://www.w3.org/TR/CSP2/#base64_value this.digest.match(BASE64_REGEX) && // Option syntax is strictly visual chars. // https://w3c.github.io/webappsec-subresource-integrity/#grammardef-option-expression // https://tools.ietf.org/html/rfc5234#appendix-B.1 this.options.every(opt => opt.match(VCHAR_REGEX)) )) { return '' } } return `${this.algorithm}-${this.digest}${getOptString(this.options)}` } } function integrityHashToString (toString, sep, opts, hashes) { const toStringIsNotEmpty = toString !== '' let shouldAddFirstSep = false let complement = '' const lastIndex = hashes.length - 1 for (let i = 0; i < lastIndex; i++) { const hashString = Hash.prototype.toString.call(hashes[i], opts) if (hashString) { shouldAddFirstSep = true complement += hashString complement += sep } } const finalHashString = Hash.prototype.toString.call(hashes[lastIndex], opts) if (finalHashString) { shouldAddFirstSep = true complement += finalHashString } if (toStringIsNotEmpty && shouldAddFirstSep) { return toString + sep + complement } return toString + complement } class Integrity { get isIntegrity () { return true } toJSON () { return this.toString() } isEmpty () { return Object.keys(this).length === 0 } toString (opts) { let sep = opts?.sep || ' ' let toString = '' if (opts?.strict) { // Entries must be separated by whitespace, according to spec. sep = sep.replace(/\S+/g, ' ') for (const hash of SPEC_ALGORITHMS) { if (this[hash]) { toString = integrityHashToString(toString, sep, opts, this[hash]) } } } else { for (const hash of Object.keys(this)) { toString = integrityHashToString(toString, sep, opts, this[hash]) } } return toString } concat (integrity, opts) { const other = typeof integrity === 'string' ? integrity : stringify(integrity, opts) return parse(`${this.toString(opts)} ${other}`, opts) } hexDigest () { return parse(this, { single: true }).hexDigest() } // add additional hashes to an integrity value, but prevent // *changing* an existing integrity hash. merge (integrity, opts) { const other = parse(integrity, opts) for (const algo in other) { if (this[algo]) { if (!this[algo].find(hash => other[algo].find(otherhash => hash.digest === otherhash.digest))) { throw new Error('hashes do not match, cannot update integrity') } } else { this[algo] = other[algo] } } } match (integrity, opts) { const other = parse(integrity, opts) if (!other) { return false } const algo = other.pickAlgorithm(opts, Object.keys(this)) return ( !!algo && this[algo] && other[algo] && this[algo].find(hash => other[algo].find(otherhash => hash.digest === otherhash.digest ) ) ) || false } // Pick the highest priority algorithm present, optionally also limited to a // set of hashes found in another integrity. When limiting it may return // nothing. pickAlgorithm (opts, hashes) { const pickAlgorithm = opts?.pickAlgorithm || getPrioritizedHash const keys = Object.keys(this).filter(k => { if (hashes?.length) { return hashes.includes(k) } return true }) if (keys.length) { return keys.reduce((acc, algo) => pickAlgorithm(acc, algo) || acc) } // no intersection between this and hashes, return null } } module.exports.parse = parse function parse (sri, opts) { if (!sri) { return null } if (typeof sri === 'string') { return _parse(sri, opts) } else if (sri.algorithm && sri.digest) { const fullSri = new Integrity() fullSri[sri.algorithm] = [sri] return _parse(stringify(fullSri, opts), opts) } else { return _parse(stringify(sri, opts), opts) } } function _parse (integrity, opts) { // 3.4.3. Parse metadata // https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata if (opts?.single) { return new Hash(integrity, opts) } const hashes = integrity.trim().split(/\s+/).reduce((acc, string) => { const hash = new Hash(string, opts) if (hash.algorithm && hash.digest) { const algo = hash.algorithm if (!acc[algo]) { acc[algo] = [] } acc[algo].push(hash) } return acc }, new Integrity()) return hashes.isEmpty() ? null : hashes } module.exports.stringify = stringify function stringify (obj, opts) { if (obj.algorithm && obj.digest) { return Hash.prototype.toString.call(obj, opts) } else if (typeof obj === 'string') { return stringify(parse(obj, opts), opts) } else { return Integrity.prototype.toString.call(obj, opts) } } module.exports.fromHex = fromHex function fromHex (hexDigest, algorithm, opts) { const optString = getOptString(opts?.options) return parse( `${algorithm}-${ Buffer.from(hexDigest, 'hex').toString('base64') }${optString}`, opts ) } module.exports.fromData = fromData function fromData (data, opts) { const algorithms = opts?.algorithms || [...DEFAULT_ALGORITHMS] const optString = getOptString(opts?.options) return algorithms.reduce((acc, algo) => { const digest = crypto.createHash(algo).update(data).digest('base64') const hash = new Hash( `${algo}-${digest}${optString}`, opts ) /* istanbul ignore else - it would be VERY strange if the string we * just calculated with an algo did not have an algo or digest. */ if (hash.algorithm && hash.digest) { const hashAlgo = hash.algorithm if (!acc[hashAlgo]) { acc[hashAlgo] = [] } acc[hashAlgo].push(hash) } return acc }, new Integrity()) } module.exports.fromStream = fromStream function fromStream (stream, opts) { const istream = integrityStream(opts) return new Promise((resolve, reject) => { stream.pipe(istream) stream.on('error', reject) istream.on('error', reject) let sri istream.on('integrity', s => { sri = s }) istream.on('end', () => resolve(sri)) istream.resume() }) } module.exports.checkData = checkData function checkData (data, sri, opts) { sri = parse(sri, opts) if (!sri || !Object.keys(sri).length) { if (opts?.error) { throw Object.assign( new Error('No valid integrity hashes to check against'), { code: 'EINTEGRITY', } ) } else { return false } } const algorithm = sri.pickAlgorithm(opts) const digest = crypto.createHash(algorithm).update(data).digest('base64') const newSri = parse({ algorithm, digest }) const match = newSri.match(sri, opts) opts = opts || {} if (match || !(opts.error)) { return match } else if (typeof opts.size === 'number' && (data.length !== opts.size)) { /* eslint-disable-next-line max-len */ const err = new Error(`data size mismatch when checking ${sri}.\n Wanted: ${opts.size}\n Found: ${data.length}`) err.code = 'EBADSIZE' err.found = data.length err.expected = opts.size err.sri = sri throw err } else { /* eslint-disable-next-line max-len */ const err = new Error(`Integrity checksum failed when using ${algorithm}: Wanted ${sri}, but got ${newSri}. (${data.length} bytes)`) err.code = 'EINTEGRITY' err.found = newSri err.expected = sri err.algorithm = algorithm err.sri = sri throw err } } module.exports.checkStream = checkStream function checkStream (stream, sri, opts) { opts = opts || Object.create(null) opts.integrity = sri sri = parse(sri, opts) if (!sri || !Object.keys(sri).length) { return Promise.reject(Object.assign( new Error('No valid integrity hashes to check against'), { code: 'EINTEGRITY', } )) } const checker = integrityStream(opts) return new Promise((resolve, reject) => { stream.pipe(checker) stream.on('error', reject) checker.on('error', reject) let verified checker.on('verified', s => { verified = s }) checker.on('end', () => resolve(verified)) checker.resume() }) } module.exports.integrityStream = integrityStream function integrityStream (opts = Object.create(null)) { return new IntegrityStream(opts) } module.exports.create = createIntegrity function createIntegrity (opts) { const algorithms = opts?.algorithms || [...DEFAULT_ALGORITHMS] const optString = getOptString(opts?.options) const hashes = algorithms.map(crypto.createHash) return { update: function (chunk, enc) { hashes.forEach(h => h.update(chunk, enc)) return this }, digest: function () { const integrity = algorithms.reduce((acc, algo) => { const digest = hashes.shift().digest('base64') const hash = new Hash( `${algo}-${digest}${optString}`, opts ) /* istanbul ignore else - it would be VERY strange if the hash we * just calculated with an algo did not have an algo or digest. */ if (hash.algorithm && hash.digest) { const hashAlgo = hash.algorithm if (!acc[hashAlgo]) { acc[hashAlgo] = [] } acc[hashAlgo].push(hash) } return acc }, new Integrity()) return integrity }, } } const NODE_HASHES = crypto.getHashes() // This is a Best Effort™ at a reasonable priority for hash algos const DEFAULT_PRIORITY = [ 'md5', 'whirlpool', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512', // TODO - it's unclear _which_ of these Node will actually use as its name // for the algorithm, so we guesswork it based on the OpenSSL names. 'sha3', 'sha3-256', 'sha3-384', 'sha3-512', 'sha3_256', 'sha3_384', 'sha3_512', ].filter(algo => NODE_HASHES.includes(algo)) function getPrioritizedHash (algo1, algo2) { /* eslint-disable-next-line max-len */ return DEFAULT_PRIORITY.indexOf(algo1.toLowerCase()) >= DEFAULT_PRIORITY.indexOf(algo2.toLowerCase()) ? algo1 : algo2 } PK ~\gssri/LICENSE.mdnu[ISC License Copyright 2021 (c) npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE COPYRIGHT HOLDER DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\,is-lambda/package.jsonnu[{ "_id": "is-lambda@1.0.1", "_inBundle": true, "_location": "/npm/is-lambda", "_phantomChildren": {}, "_requiredBy": [ "/npm/make-fetch-happen" ], "author": { "name": "Thomas Watson Steen", "email": "w@tson.dk", "url": "https://twitter.com/wa7son" }, "bugs": { "url": "https://github.com/watson/is-lambda/issues" }, "coordinates": [ 37.3859955, -122.0838831 ], "dependencies": {}, "description": "Detect if your code is running on an AWS Lambda server", "devDependencies": { "clear-require": "^1.0.1", "standard": "^10.0.2" }, "homepage": "https://github.com/watson/is-lambda", "keywords": [ "aws", "hosting", "hosted", "lambda", "detect" ], "license": "MIT", "main": "index.js", "name": "is-lambda", "repository": { "type": "git", "url": "git+https://github.com/watson/is-lambda.git" }, "scripts": { "test": "standard && node test.js" }, "version": "1.0.1" } PK ~\DcAAis-lambda/test.jsnu['use strict' var assert = require('assert') var clearRequire = require('clear-require') process.env.AWS_EXECUTION_ENV = 'AWS_Lambda_nodejs6.10' process.env.LAMBDA_TASK_ROOT = '/var/task' var isCI = require('./') assert(isCI) delete process.env.AWS_EXECUTION_ENV clearRequire('./') isCI = require('./') assert(!isCI) PK ~\[|`ICCis-lambda/LICENSEnu[The MIT License (MIT) Copyright (c) 2016-2017 Thomas Watson Steen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\<rris-lambda/index.jsnu['use strict' module.exports = !!( (process.env.LAMBDA_TASK_ROOT && process.env.AWS_EXECUTION_ENV) || false ) PK ~\D!YY*@isaacs/string-locale-compare/package.jsonnu[{ "_id": "@isaacs/string-locale-compare@1.1.0", "_inBundle": true, "_location": "/npm/@isaacs/string-locale-compare", "_phantomChildren": {}, "_requiredBy": [ "/npm", "/npm/@npmcli/arborist" ], "author": { "name": "Isaac Z. Schlueter", "email": "i@izs.me", "url": "https://izs.me" }, "bugs": { "url": "https://github.com/isaacs/string-locale-compare/issues" }, "description": "Compare strings with Intl.Collator if available, falling back to String.localeCompare otherwise", "devDependencies": { "tap": "^15.0.9" }, "files": [ "index.js" ], "homepage": "https://github.com/isaacs/string-locale-compare#readme", "license": "ISC", "main": "index.js", "name": "@isaacs/string-locale-compare", "repository": { "type": "git", "url": "git+https://github.com/isaacs/string-locale-compare.git" }, "scripts": { "postversion": "npm publish", "prepublishOnly": "git push origin --follow-tags", "preversion": "npm test", "snap": "tap", "test": "tap" }, "tap": { "check-coverage": true }, "version": "1.1.0" } PK ~\?&%@isaacs/string-locale-compare/LICENSEnu[The ISC License Copyright (c) Isaac Z. Schlueter Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\bC&@isaacs/string-locale-compare/index.jsnu[const hasIntl = typeof Intl === 'object' && !!Intl const Collator = hasIntl && Intl.Collator const cache = new Map() const collatorCompare = (locale, opts) => { const collator = new Collator(locale, opts) return (a, b) => collator.compare(a, b) } const localeCompare = (locale, opts) => (a, b) => a.localeCompare(b, locale, opts) const knownOptions = [ 'sensitivity', 'numeric', 'ignorePunctuation', 'caseFirst', ] const { hasOwnProperty } = Object.prototype module.exports = (locale, options = {}) => { if (!locale || typeof locale !== 'string') throw new TypeError('locale required') const opts = knownOptions.reduce((opts, k) => { if (hasOwnProperty.call(options, k)) { opts[k] = options[k] } return opts }, {}) const key = `${locale}\n${JSON.stringify(opts)}` if (cache.has(key)) return cache.get(key) const compare = hasIntl ? collatorCompare(locale, opts) : localeCompare(locale, opts) cache.set(key, compare) return compare } PK ~\'z  @isaacs/cliui/package.jsonnu[{ "_id": "@isaacs/cliui@8.0.2", "_inBundle": true, "_location": "/npm/@isaacs/cliui", "_phantomChildren": { "eastasianwidth": "0.2.0" }, "_requiredBy": [ "/npm/jackspeak" ], "author": { "name": "Ben Coe", "email": "ben@npmjs.com" }, "bugs": { "url": "https://github.com/yargs/cliui/issues" }, "dependencies": { "string-width": "^5.1.2", "string-width-cjs": "npm:string-width@^4.2.0", "strip-ansi": "^7.0.1", "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", "wrap-ansi": "^8.1.0", "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" }, "description": "easily create complex multi-column command-line-interfaces", "devDependencies": { "@types/node": "^14.0.27", "@typescript-eslint/eslint-plugin": "^4.0.0", "@typescript-eslint/parser": "^4.0.0", "c8": "^7.3.0", "chai": "^4.2.0", "chalk": "^4.1.0", "cross-env": "^7.0.2", "eslint": "^7.6.0", "eslint-plugin-import": "^2.22.0", "eslint-plugin-node": "^11.1.0", "gts": "^3.0.0", "mocha": "^10.0.0", "rimraf": "^3.0.2", "rollup": "^2.23.1", "rollup-plugin-ts": "^3.0.2", "standardx": "^7.0.0", "typescript": "^4.0.0" }, "engines": { "node": ">=12" }, "exports": { ".": [ { "import": "./index.mjs", "require": "./build/index.cjs" }, "./build/index.cjs" ] }, "files": [ "build", "index.mjs", "!*.d.ts" ], "homepage": "https://github.com/yargs/cliui#readme", "keywords": [ "cli", "command-line", "layout", "design", "console", "wrap", "table" ], "license": "ISC", "main": "build/index.cjs", "module": "./index.mjs", "name": "@isaacs/cliui", "repository": { "type": "git", "url": "git+https://github.com/yargs/cliui.git" }, "scripts": { "build:cjs": "rollup -c", "check": "standardx '**/*.ts' && standardx '**/*.js' && standardx '**/*.cjs'", "compile": "tsc", "coverage": "c8 report --check-coverage", "fix": "standardx --fix '**/*.ts' && standardx --fix '**/*.js' && standardx --fix '**/*.cjs'", "postcompile": "npm run build:cjs", "postest": "check", "precompile": "rimraf build", "prepare": "npm run compile", "pretest": "rimraf build && tsc -p tsconfig.test.json && cross-env NODE_ENV=test npm run build:cjs", "test": "c8 mocha ./test/*.cjs", "test:esm": "c8 mocha ./test/**/*.mjs" }, "standard": { "ignore": [ "**/example/**" ], "globals": [ "it" ] }, "type": "module", "version": "8.0.2" } PK ~\#*93@isaacs/cliui/node_modules/ansi-styles/package.jsonnu[{ "_from": "ansi-styles@^4.0.0", "_id": "ansi-styles@4.3.0", "_inBundle": false, "_integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "_location": "/npm/@isaacs/cliui/ansi-styles", "_phantomChildren": {}, "_requested": { "type": "range", "registry": true, "raw": "ansi-styles@^4.0.0", "name": "ansi-styles", "escapedName": "ansi-styles", "rawSpec": "^4.0.0", "saveSpec": null, "fetchSpec": "^4.0.0" }, "_requiredBy": [ "/npm/@isaacs/cliui/wrap-ansi-cjs" ], "_resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "_shasum": "edd803628ae71c04c85ae7a0906edad34b648937", "_spec": "ansi-styles@^4.0.0", "_where": "C:\\xampp\\htdocs\\emeraltd\\node_modules\\npm\\node_modules\\@isaacs\\cliui\\node_modules\\wrap-ansi-cjs", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "bugs": { "url": "https://github.com/chalk/ansi-styles/issues" }, "bundleDependencies": false, "dependencies": { "color-convert": "^2.0.1" }, "deprecated": false, "description": "ANSI escape codes for styling strings in the terminal", "devDependencies": { "@types/color-convert": "^1.9.0", "ava": "^2.3.0", "svg-term-cli": "^2.1.1", "tsd": "^0.11.0", "xo": "^0.25.3" }, "engines": { "node": ">=8" }, "files": [ "index.js", "index.d.ts" ], "funding": "https://github.com/chalk/ansi-styles?sponsor=1", "homepage": "https://github.com/chalk/ansi-styles#readme", "keywords": [ "ansi", "styles", "color", "colour", "colors", "terminal", "console", "cli", "string", "tty", "escape", "formatting", "rgb", "256", "shell", "xterm", "log", "logging", "command-line", "text" ], "license": "MIT", "name": "ansi-styles", "repository": { "type": "git", "url": "git+https://github.com/chalk/ansi-styles.git" }, "scripts": { "screenshot": "svg-term --command='node screenshot' --out=screenshot.svg --padding=3 --width=55 --height=3 --at=1000 --no-cursor", "test": "xo && ava && tsd" }, "version": "4.3.0" } PK ~\[vO0@isaacs/cliui/node_modules/ansi-styles/readme.mdnu[# ansi-styles [![Build Status](https://travis-ci.org/chalk/ansi-styles.svg?branch=master)](https://travis-ci.org/chalk/ansi-styles) > [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) for styling strings in the terminal You probably want the higher-level [chalk](https://github.com/chalk/chalk) module for styling your strings. ## Install ``` $ npm install ansi-styles ``` ## Usage ```js const style = require('ansi-styles'); console.log(`${style.green.open}Hello world!${style.green.close}`); // Color conversion between 16/256/truecolor // NOTE: If conversion goes to 16 colors or 256 colors, the original color // may be degraded to fit that color palette. This means terminals // that do not support 16 million colors will best-match the // original color. console.log(style.bgColor.ansi.hsl(120, 80, 72) + 'Hello world!' + style.bgColor.close); console.log(style.color.ansi256.rgb(199, 20, 250) + 'Hello world!' + style.color.close); console.log(style.color.ansi16m.hex('#abcdef') + 'Hello world!' + style.color.close); ``` ## API Each style has an `open` and `close` property. ## Styles ### Modifiers - `reset` - `bold` - `dim` - `italic` *(Not widely supported)* - `underline` - `inverse` - `hidden` - `strikethrough` *(Not widely supported)* ### Colors - `black` - `red` - `green` - `yellow` - `blue` - `magenta` - `cyan` - `white` - `blackBright` (alias: `gray`, `grey`) - `redBright` - `greenBright` - `yellowBright` - `blueBright` - `magentaBright` - `cyanBright` - `whiteBright` ### Background colors - `bgBlack` - `bgRed` - `bgGreen` - `bgYellow` - `bgBlue` - `bgMagenta` - `bgCyan` - `bgWhite` - `bgBlackBright` (alias: `bgGray`, `bgGrey`) - `bgRedBright` - `bgGreenBright` - `bgYellowBright` - `bgBlueBright` - `bgMagentaBright` - `bgCyanBright` - `bgWhiteBright` ## Advanced usage By default, you get a map of styles, but the styles are also available as groups. They are non-enumerable so they don't show up unless you access them explicitly. This makes it easier to expose only a subset in a higher-level module. - `style.modifier` - `style.color` - `style.bgColor` ###### Example ```js console.log(style.color.green.open); ``` Raw escape codes (i.e. without the CSI escape prefix `\u001B[` and render mode postfix `m`) are available under `style.codes`, which returns a `Map` with the open codes as keys and close codes as values. ###### Example ```js console.log(style.codes.get(36)); //=> 39 ``` ## [256 / 16 million (TrueColor) support](https://gist.github.com/XVilka/8346728) `ansi-styles` uses the [`color-convert`](https://github.com/Qix-/color-convert) package to allow for converting between various colors and ANSI escapes, with support for 256 and 16 million colors. The following color spaces from `color-convert` are supported: - `rgb` - `hex` - `keyword` - `hsl` - `hsv` - `hwb` - `ansi` - `ansi256` To use these, call the associated conversion function with the intended output, for example: ```js style.color.ansi.rgb(100, 200, 15); // RGB to 16 color ansi foreground code style.bgColor.ansi.rgb(100, 200, 15); // RGB to 16 color ansi background code style.color.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code style.bgColor.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code style.color.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color foreground code style.bgColor.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color background code ``` ## Related - [ansi-escapes](https://github.com/sindresorhus/ansi-escapes) - ANSI escape codes for manipulating the terminal ## Maintainers - [Sindre Sorhus](https://github.com/sindresorhus) - [Josh Junon](https://github.com/qix-) ## For enterprise Available as part of the Tidelift Subscription. The maintainers of `ansi-styles` and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-ansi-styles?utm_source=npm-ansi-styles&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) PK ~\/++/@isaacs/cliui/node_modules/ansi-styles/index.jsnu['use strict'; const wrapAnsi16 = (fn, offset) => (...args) => { const code = fn(...args); return `\u001B[${code + offset}m`; }; const wrapAnsi256 = (fn, offset) => (...args) => { const code = fn(...args); return `\u001B[${38 + offset};5;${code}m`; }; const wrapAnsi16m = (fn, offset) => (...args) => { const rgb = fn(...args); return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; }; const ansi2ansi = n => n; const rgb2rgb = (r, g, b) => [r, g, b]; const setLazyProperty = (object, property, get) => { Object.defineProperty(object, property, { get: () => { const value = get(); Object.defineProperty(object, property, { value, enumerable: true, configurable: true }); return value; }, enumerable: true, configurable: true }); }; /** @type {typeof import('color-convert')} */ let colorConvert; const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { if (colorConvert === undefined) { colorConvert = require('color-convert'); } const offset = isBackground ? 10 : 0; const styles = {}; for (const [sourceSpace, suite] of Object.entries(colorConvert)) { const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; if (sourceSpace === targetSpace) { styles[name] = wrap(identity, offset); } else if (typeof suite === 'object') { styles[name] = wrap(suite[targetSpace], offset); } } return styles; }; function assembleStyles() { const codes = new Map(); const styles = { modifier: { reset: [0, 0], // 21 isn't widely supported and 22 does the same thing bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29] }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], // Bright color blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39] }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], // Bright color bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49] } }; // Alias bright black as gray (and grey) styles.color.gray = styles.color.blackBright; styles.bgColor.bgGray = styles.bgColor.bgBlackBright; styles.color.grey = styles.color.blackBright; styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; for (const [groupName, group] of Object.entries(styles)) { for (const [styleName, style] of Object.entries(group)) { styles[styleName] = { open: `\u001B[${style[0]}m`, close: `\u001B[${style[1]}m` }; group[styleName] = styles[styleName]; codes.set(style[0], style[1]); } Object.defineProperty(styles, groupName, { value: group, enumerable: false }); } Object.defineProperty(styles, 'codes', { value: codes, enumerable: false }); styles.color.close = '\u001B[39m'; styles.bgColor.close = '\u001B[49m'; setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); return styles; } // Make the export immutable Object.defineProperty(module, 'exports', { enumerable: true, get: assembleStyles }); PK ~\E}UU.@isaacs/cliui/node_modules/ansi-styles/licensenu[MIT License Copyright (c) Sindre Sorhus (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\([1@isaacs/cliui/node_modules/ansi-styles/index.d.tsnu[declare type CSSColor = | 'aliceblue' | 'antiquewhite' | 'aqua' | 'aquamarine' | 'azure' | 'beige' | 'bisque' | 'black' | 'blanchedalmond' | 'blue' | 'blueviolet' | 'brown' | 'burlywood' | 'cadetblue' | 'chartreuse' | 'chocolate' | 'coral' | 'cornflowerblue' | 'cornsilk' | 'crimson' | 'cyan' | 'darkblue' | 'darkcyan' | 'darkgoldenrod' | 'darkgray' | 'darkgreen' | 'darkgrey' | 'darkkhaki' | 'darkmagenta' | 'darkolivegreen' | 'darkorange' | 'darkorchid' | 'darkred' | 'darksalmon' | 'darkseagreen' | 'darkslateblue' | 'darkslategray' | 'darkslategrey' | 'darkturquoise' | 'darkviolet' | 'deeppink' | 'deepskyblue' | 'dimgray' | 'dimgrey' | 'dodgerblue' | 'firebrick' | 'floralwhite' | 'forestgreen' | 'fuchsia' | 'gainsboro' | 'ghostwhite' | 'gold' | 'goldenrod' | 'gray' | 'green' | 'greenyellow' | 'grey' | 'honeydew' | 'hotpink' | 'indianred' | 'indigo' | 'ivory' | 'khaki' | 'lavender' | 'lavenderblush' | 'lawngreen' | 'lemonchiffon' | 'lightblue' | 'lightcoral' | 'lightcyan' | 'lightgoldenrodyellow' | 'lightgray' | 'lightgreen' | 'lightgrey' | 'lightpink' | 'lightsalmon' | 'lightseagreen' | 'lightskyblue' | 'lightslategray' | 'lightslategrey' | 'lightsteelblue' | 'lightyellow' | 'lime' | 'limegreen' | 'linen' | 'magenta' | 'maroon' | 'mediumaquamarine' | 'mediumblue' | 'mediumorchid' | 'mediumpurple' | 'mediumseagreen' | 'mediumslateblue' | 'mediumspringgreen' | 'mediumturquoise' | 'mediumvioletred' | 'midnightblue' | 'mintcream' | 'mistyrose' | 'moccasin' | 'navajowhite' | 'navy' | 'oldlace' | 'olive' | 'olivedrab' | 'orange' | 'orangered' | 'orchid' | 'palegoldenrod' | 'palegreen' | 'paleturquoise' | 'palevioletred' | 'papayawhip' | 'peachpuff' | 'peru' | 'pink' | 'plum' | 'powderblue' | 'purple' | 'rebeccapurple' | 'red' | 'rosybrown' | 'royalblue' | 'saddlebrown' | 'salmon' | 'sandybrown' | 'seagreen' | 'seashell' | 'sienna' | 'silver' | 'skyblue' | 'slateblue' | 'slategray' | 'slategrey' | 'snow' | 'springgreen' | 'steelblue' | 'tan' | 'teal' | 'thistle' | 'tomato' | 'turquoise' | 'violet' | 'wheat' | 'white' | 'whitesmoke' | 'yellow' | 'yellowgreen'; declare namespace ansiStyles { interface ColorConvert { /** The RGB color space. @param red - (`0`-`255`) @param green - (`0`-`255`) @param blue - (`0`-`255`) */ rgb(red: number, green: number, blue: number): string; /** The RGB HEX color space. @param hex - A hexadecimal string containing RGB data. */ hex(hex: string): string; /** @param keyword - A CSS color name. */ keyword(keyword: CSSColor): string; /** The HSL color space. @param hue - (`0`-`360`) @param saturation - (`0`-`100`) @param lightness - (`0`-`100`) */ hsl(hue: number, saturation: number, lightness: number): string; /** The HSV color space. @param hue - (`0`-`360`) @param saturation - (`0`-`100`) @param value - (`0`-`100`) */ hsv(hue: number, saturation: number, value: number): string; /** The HSV color space. @param hue - (`0`-`360`) @param whiteness - (`0`-`100`) @param blackness - (`0`-`100`) */ hwb(hue: number, whiteness: number, blackness: number): string; /** Use a [4-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4-bit) to set text color. */ ansi(ansi: number): string; /** Use an [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color. */ ansi256(ansi: number): string; } interface CSPair { /** The ANSI terminal control sequence for starting this style. */ readonly open: string; /** The ANSI terminal control sequence for ending this style. */ readonly close: string; } interface ColorBase { readonly ansi: ColorConvert; readonly ansi256: ColorConvert; readonly ansi16m: ColorConvert; /** The ANSI terminal control sequence for ending this color. */ readonly close: string; } interface Modifier { /** Resets the current color chain. */ readonly reset: CSPair; /** Make text bold. */ readonly bold: CSPair; /** Emitting only a small amount of light. */ readonly dim: CSPair; /** Make text italic. (Not widely supported) */ readonly italic: CSPair; /** Make text underline. (Not widely supported) */ readonly underline: CSPair; /** Inverse background and foreground colors. */ readonly inverse: CSPair; /** Prints the text, but makes it invisible. */ readonly hidden: CSPair; /** Puts a horizontal line through the center of the text. (Not widely supported) */ readonly strikethrough: CSPair; } interface ForegroundColor { readonly black: CSPair; readonly red: CSPair; readonly green: CSPair; readonly yellow: CSPair; readonly blue: CSPair; readonly cyan: CSPair; readonly magenta: CSPair; readonly white: CSPair; /** Alias for `blackBright`. */ readonly gray: CSPair; /** Alias for `blackBright`. */ readonly grey: CSPair; readonly blackBright: CSPair; readonly redBright: CSPair; readonly greenBright: CSPair; readonly yellowBright: CSPair; readonly blueBright: CSPair; readonly cyanBright: CSPair; readonly magentaBright: CSPair; readonly whiteBright: CSPair; } interface BackgroundColor { readonly bgBlack: CSPair; readonly bgRed: CSPair; readonly bgGreen: CSPair; readonly bgYellow: CSPair; readonly bgBlue: CSPair; readonly bgCyan: CSPair; readonly bgMagenta: CSPair; readonly bgWhite: CSPair; /** Alias for `bgBlackBright`. */ readonly bgGray: CSPair; /** Alias for `bgBlackBright`. */ readonly bgGrey: CSPair; readonly bgBlackBright: CSPair; readonly bgRedBright: CSPair; readonly bgGreenBright: CSPair; readonly bgYellowBright: CSPair; readonly bgBlueBright: CSPair; readonly bgCyanBright: CSPair; readonly bgMagentaBright: CSPair; readonly bgWhiteBright: CSPair; } } declare const ansiStyles: { readonly modifier: ansiStyles.Modifier; readonly color: ansiStyles.ForegroundColor & ansiStyles.ColorBase; readonly bgColor: ansiStyles.BackgroundColor & ansiStyles.ColorBase; readonly codes: ReadonlyMap; } & ansiStyles.BackgroundColor & ansiStyles.ForegroundColor & ansiStyles.Modifier; export = ansiStyles; PK ~\88.@isaacs/cliui/node_modules/emoji-regex/text.jsnu["use strict"; module.exports = function () { // https://mths.be/emoji return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\u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uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2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-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F?/g; }; PK ~\x3@isaacs/cliui/node_modules/emoji-regex/package.jsonnu[{ "_id": "emoji-regex@9.2.2", "_inBundle": true, "_location": "/npm/@isaacs/cliui/emoji-regex", "_phantomChildren": {}, "_requiredBy": [ "/npm/@isaacs/cliui/string-width" ], "author": { "name": "Mathias Bynens", "url": "https://mathiasbynens.be/" }, "bugs": { "url": "https://github.com/mathiasbynens/emoji-regex/issues" }, "description": "A regular expression to match all Emoji-only symbols as per the Unicode Standard.", "devDependencies": { "@babel/cli": "^7.4.4", "@babel/core": "^7.4.4", "@babel/plugin-proposal-unicode-property-regex": "^7.4.4", "@babel/preset-env": "^7.4.4", "@unicode/unicode-13.0.0": "^1.0.3", "mocha": "^6.1.4", "regexgen": "^1.3.0" }, "files": [ "LICENSE-MIT.txt", "index.js", "index.d.ts", "RGI_Emoji.js", "RGI_Emoji.d.ts", "text.js", "text.d.ts", "es2015" ], "homepage": "https://mths.be/emoji-regex", "keywords": [ "unicode", "regex", "regexp", "regular expressions", "code points", "symbols", "characters", "emoji" ], "license": "MIT", "main": "index.js", "name": "emoji-regex", "repository": { "type": "git", "url": "git+https://github.com/mathiasbynens/emoji-regex.git" }, "scripts": { "build": "rm -rf -- es2015; babel src -d .; NODE_ENV=es2015 babel src es2015_types -D -d ./es2015; node script/inject-sequences.js", "test": "mocha", "test:watch": "npm run test -- --watch" }, "types": "index.d.ts", "version": "9.2.2" } PK ~\_w=w=/@isaacs/cliui/node_modules/emoji-regex/index.jsnu["use strict"; module.exports = function () { // https://mths.be/emoji return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\u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\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D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\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; }; PK ~\ڌC556@isaacs/cliui/node_modules/emoji-regex/LICENSE-MIT.txtnu[Copyright Mathias Bynens Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\h==5@isaacs/cliui/node_modules/emoji-regex/es2015/text.jsnu["use strict"; module.exports = () => { // https://mths.be/emoji return /\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0077}\u{E006C}\u{E0073}|\u{E0073}\u{E0063}\u{E0074}|\u{E0065}\u{E006E}\u{E0067})\u{E007F}|(?:\u{1F9D1}\u{1F3FF}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FF}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FE}]|(?:\u{1F9D1}\u{1F3FE}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FE}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FD}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FD}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FC}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FC}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FB}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FB}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FC}-\u{1F3FF}]|\u{1F468}(?:\u{1F3FB}(?:\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FF}]|\u{1F468}[\u{1F3FB}-\u{1F3FF}])|\u{1F91D}\u200D\u{1F468}[\u{1F3FC}-\u{1F3FF}]|[\u2695\u2696\u2708]\uFE0F|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]))?|[\u{1F3FC}-\u{1F3FF}]\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FF}]|\u{1F468}[\u{1F3FB}-\u{1F3FF}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FE}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u{1F466}\u{1F467}])|\u{1F3FF}|\u{1F3FE}|\u{1F3FD}|\u{1F3FC})?|(?:\u{1F469}(?:\u{1F3FB}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F3FC}-\u{1F3FF}]\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}]))|\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]\u200D\u{1F91D}\u200D\u{1F9D1})[\u{1F3FB}-\u{1F3FF}]|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F469}(?:\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4B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\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FE}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FD}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FC}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|\u{1F469}\u200D\u{1F467}\u200D[\u{1F466}\u{1F467}]|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F9D1}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\u{1F469}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\u{1F636}\u200D\u{1F32B}|\u{1F3F3}\uFE0F\u200D\u26A7|\u{1F43B}\u200D\u2744|(?:[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\uFE0F\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|\u{1F3F4}\u200D\u2620|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}]\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F202}\u{1F237}\u{1F321}\u{1F324}-\u{1F32C}\u{1F336}\u{1F37D}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}\u{1F39F}\u{1F3CD}\u{1F3CE}\u{1F3D4}-\u{1F3DF}\u{1F3F5}\u{1F3F7}\u{1F43F}\u{1F4FD}\u{1F549}\u{1F54A}\u{1F56F}\u{1F570}\u{1F573}\u{1F576}-\u{1F579}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}\u{1F6CB}\u{1F6CD}-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{1F1E7}\u{1F1E9}-\u{1F1EF}\u{1F1F1}-\u{1F1F4}\u{1F1F6}-\u{1F1F9}\u{1F1FB}\u{1F1FC}\u{1F1FE}\u{1F1FF}]|\u{1F1E6}[\u{1F1E8}-\u{1F1EC}\u{1F1EE}\u{1F1F1}\u{1F1F2}\u{1F1F4}\u{1F1F6}-\u{1F1FA}\u{1F1FC}\u{1F1FD}\u{1F1FF}]|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\uFE0F\u{1F3FB}-\u{1F3FF}]|\u{1F3F4}|[\u270A\u270B\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F57A}\u{1F595}\u{1F596}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90C}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F934}\u{1F936}\u{1F977}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}\u{1F9D3}\u{1F9D5}][\u{1F3FB}-\u{1F3FF}]|[\u261D\u270C\u270D\u{1F574}\u{1F590}][\uFE0F\u{1F3FB}-\u{1F3FF}]|[\u270A\u270B\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F408}\u{1F415}\u{1F43B}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F57A}\u{1F595}\u{1F596}\u{1F62E}\u{1F635}\u{1F636}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90C}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F934}\u{1F936}\u{1F977}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}\u{1F9D3}\u{1F9D5}]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}]|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F384}\u{1F386}-\u{1F393}\u{1F3A0}-\u{1F3C1}\u{1F3C5}\u{1F3C6}\u{1F3C8}\u{1F3C9}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F8}-\u{1F407}\u{1F409}-\u{1F414}\u{1F416}-\u{1F43A}\u{1F43C}-\u{1F43E}\u{1F440}\u{1F444}\u{1F445}\u{1F451}-\u{1F465}\u{1F46A}\u{1F479}-\u{1F47B}\u{1F47D}-\u{1F480}\u{1F484}\u{1F488}-\u{1F48E}\u{1F490}\u{1F492}-\u{1F4A9}\u{1F4AB}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F5A4}\u{1F5FB}-\u{1F62D}\u{1F62F}-\u{1F634}\u{1F637}-\u{1F644}\u{1F648}-\u{1F64A}\u{1F680}-\u{1F6A2}\u{1F6A4}-\u{1F6B3}\u{1F6B7}-\u{1F6BF}\u{1F6C1}-\u{1F6C5}\u{1F6D0}-\u{1F6D2}\u{1F6D5}-\u{1F6D7}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FC}\u{1F7E0}-\u{1F7EB}\u{1F90D}\u{1F90E}\u{1F910}-\u{1F917}\u{1F91D}\u{1F920}-\u{1F925}\u{1F927}-\u{1F92F}\u{1F93A}\u{1F93F}-\u{1F945}\u{1F947}-\u{1F976}\u{1F978}\u{1F97A}-\u{1F9B4}\u{1F9B7}\u{1F9BA}\u{1F9BC}-\u{1F9CB}\u{1F9D0}\u{1F9E0}-\u{1F9FF}\u{1FA70}-\u{1FA74}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA86}\u{1FA90}-\u{1FAA8}\u{1FAB0}-\u{1FAB6}\u{1FAC0}-\u{1FAC2}\u{1FAD0}-\u{1FAD6}]|[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299\u{1F004}\u{1F0CF}\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F321}\u{1F324}-\u{1F393}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}-\u{1F3F0}\u{1F3F3}-\u{1F3F5}\u{1F3F7}-\u{1F4FD}\u{1F4FF}-\u{1F53D}\u{1F549}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F56F}\u{1F570}\u{1F573}-\u{1F57A}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F590}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CB}-\u{1F6D2}\u{1F6D5}-\u{1F6D7}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6EB}\u{1F6EC}\u{1F6F0}\u{1F6F3}-\u{1F6FC}\u{1F7E0}-\u{1F7EB}\u{1F90C}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F978}\u{1F97A}-\u{1F9CB}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA74}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA86}\u{1FA90}-\u{1FAA8}\u{1FAB0}-\u{1FAB6}\u{1FAC0}-\u{1FAC2}\u{1FAD0}-\u{1FAD6}]\uFE0F?/gu; }; PK ~\ KCC6@isaacs/cliui/node_modules/emoji-regex/es2015/index.jsnu["use strict"; module.exports = () => { // https://mths.be/emoji return /\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0077}\u{E006C}\u{E0073}|\u{E0073}\u{E0063}\u{E0074}|\u{E0065}\u{E006E}\u{E0067})\u{E007F}|(?:\u{1F9D1}\u{1F3FF}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FF}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FE}]|(?:\u{1F9D1}\u{1F3FE}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FE}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FD}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FD}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FC}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FC}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FB}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FB}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FC}-\u{1F3FF}]|\u{1F468}(?:\u{1F3FB}(?:\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FF}]|\u{1F468}[\u{1F3FB}-\u{1F3FF}])|\u{1F91D}\u200D\u{1F468}[\u{1F3FC}-\u{1F3FF}]|[\u2695\u2696\u2708]\uFE0F|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]))?|[\u{1F3FC}-\u{1F3FF}]\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FF}]|\u{1F468}[\u{1F3FB}-\u{1F3FF}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FE}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u{1F466}\u{1F467}])|\u{1F3FF}|\u{1F3FE}|\u{1F3FD}|\u{1F3FC})?|(?:\u{1F469}(?:\u{1F3FB}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F3FC}-\u{1F3FF}]\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}]))|\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]\u200D\u{1F91D}\u200D\u{1F9D1})[\u{1F3FB}-\u{1F3FF}]|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F469}(?:\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FE}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{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}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FD}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FC}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|\u{1F469}\u200D\u{1F467}\u200D[\u{1F466}\u{1F467}]|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F9D1}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\u{1F469}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\u{1F636}\u200D\u{1F32B}|\u{1F3F3}\uFE0F\u200D\u26A7|\u{1F43B}\u200D\u2744|(?:[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\uFE0F\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|\u{1F3F4}\u200D\u2620|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}]\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F202}\u{1F237}\u{1F321}\u{1F324}-\u{1F32C}\u{1F336}\u{1F37D}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}\u{1F39F}\u{1F3CD}\u{1F3CE}\u{1F3D4}-\u{1F3DF}\u{1F3F5}\u{1F3F7}\u{1F43F}\u{1F4FD}\u{1F549}\u{1F54A}\u{1F56F}\u{1F570}\u{1F573}\u{1F576}-\u{1F579}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}\u{1F6CB}\u{1F6CD}-\u{1F6CF}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6F0}\u{1F6F3}])\uFE0F|\u{1F3F3}\uFE0F\u200D\u{1F308}|\u{1F469}\u200D\u{1F467}|\u{1F469}\u200D\u{1F466}|\u{1F635}\u200D\u{1F4AB}|\u{1F62E}\u200D\u{1F4A8}|\u{1F415}\u200D\u{1F9BA}|\u{1F9D1}(?:\u{1F3FF}|\u{1F3FE}|\u{1F3FD}|\u{1F3FC}|\u{1F3FB})?|\u{1F469}(?:\u{1F3FF}|\u{1F3FE}|\u{1F3FD}|\u{1F3FC}|\u{1F3FB})?|\u{1F1FD}\u{1F1F0}|\u{1F1F6}\u{1F1E6}|\u{1F1F4}\u{1F1F2}|\u{1F408}\u200D\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}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\uFE0F\u{1F3FB}-\u{1F3FF}]|\u{1F3F4}|[\u270A\u270B\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F57A}\u{1F595}\u{1F596}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90C}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F934}\u{1F936}\u{1F977}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}\u{1F9D3}\u{1F9D5}][\u{1F3FB}-\u{1F3FF}]|[\u261D\u270C\u270D\u{1F574}\u{1F590}][\uFE0F\u{1F3FB}-\u{1F3FF}]|[\u270A\u270B\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F408}\u{1F415}\u{1F43B}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F57A}\u{1F595}\u{1F596}\u{1F62E}\u{1F635}\u{1F636}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90C}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F934}\u{1F936}\u{1F977}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}\u{1F9D3}\u{1F9D5}]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}]|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F384}\u{1F386}-\u{1F393}\u{1F3A0}-\u{1F3C1}\u{1F3C5}\u{1F3C6}\u{1F3C8}\u{1F3C9}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F8}-\u{1F407}\u{1F409}-\u{1F414}\u{1F416}-\u{1F43A}\u{1F43C}-\u{1F43E}\u{1F440}\u{1F444}\u{1F445}\u{1F451}-\u{1F465}\u{1F46A}\u{1F479}-\u{1F47B}\u{1F47D}-\u{1F480}\u{1F484}\u{1F488}-\u{1F48E}\u{1F490}\u{1F492}-\u{1F4A9}\u{1F4AB}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F5A4}\u{1F5FB}-\u{1F62D}\u{1F62F}-\u{1F634}\u{1F637}-\u{1F644}\u{1F648}-\u{1F64A}\u{1F680}-\u{1F6A2}\u{1F6A4}-\u{1F6B3}\u{1F6B7}-\u{1F6BF}\u{1F6C1}-\u{1F6C5}\u{1F6D0}-\u{1F6D2}\u{1F6D5}-\u{1F6D7}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FC}\u{1F7E0}-\u{1F7EB}\u{1F90D}\u{1F90E}\u{1F910}-\u{1F917}\u{1F91D}\u{1F920}-\u{1F925}\u{1F927}-\u{1F92F}\u{1F93A}\u{1F93F}-\u{1F945}\u{1F947}-\u{1F976}\u{1F978}\u{1F97A}-\u{1F9B4}\u{1F9B7}\u{1F9BA}\u{1F9BC}-\u{1F9CB}\u{1F9D0}\u{1F9E0}-\u{1F9FF}\u{1FA70}-\u{1FA74}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA86}\u{1FA90}-\u{1FAA8}\u{1FAB0}-\u{1FAB6}\u{1FAC0}-\u{1FAC2}\u{1FAD0}-\u{1FAD6}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F393}\u{1F3A0}-\u{1F3CA}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F4}\u{1F3F8}-\u{1F43E}\u{1F440}\u{1F442}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F57A}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5FB}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CC}\u{1F6D0}-\u{1F6D2}\u{1F6D5}-\u{1F6D7}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FC}\u{1F7E0}-\u{1F7EB}\u{1F90C}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F978}\u{1F97A}-\u{1F9CB}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA74}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA86}\u{1FA90}-\u{1FAA8}\u{1FAB0}-\u{1FAB6}\u{1FAC0}-\u{1FAC2}\u{1FAD0}-\u{1FAD6}]|[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299\u{1F004}\u{1F0CF}\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F321}\u{1F324}-\u{1F393}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}-\u{1F3F0}\u{1F3F3}-\u{1F3F5}\u{1F3F7}-\u{1F4FD}\u{1F4FF}-\u{1F53D}\u{1F549}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F56F}\u{1F570}\u{1F573}-\u{1F57A}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F590}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CB}-\u{1F6D2}\u{1F6D5}-\u{1F6D7}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6EB}\u{1F6EC}\u{1F6F0}\u{1F6F3}-\u{1F6FC}\u{1F7E0}-\u{1F7EB}\u{1F90C}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F978}\u{1F97A}-\u{1F9CB}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA74}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA86}\u{1FA90}-\u{1FAA8}\u{1FAB0}-\u{1FAB6}\u{1FAC0}-\u{1FAC2}\u{1FAD0}-\u{1FAD6}]\uFE0F|[\u261D\u26F9\u270A-\u270D\u{1F385}\u{1F3C2}-\u{1F3C4}\u{1F3C7}\u{1F3CA}-\u{1F3CC}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}-\u{1F478}\u{1F47C}\u{1F481}-\u{1F483}\u{1F485}-\u{1F487}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F574}\u{1F575}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F645}-\u{1F647}\u{1F64B}-\u{1F64F}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F6C0}\u{1F6CC}\u{1F90C}\u{1F90F}\u{1F918}-\u{1F91F}\u{1F926}\u{1F930}-\u{1F939}\u{1F93C}-\u{1F93E}\u{1F977}\u{1F9B5}\u{1F9B6}\u{1F9B8}\u{1F9B9}\u{1F9BB}\u{1F9CD}-\u{1F9CF}\u{1F9D1}-\u{1F9DD}]/gu; }; PK ~\+z*66:@isaacs/cliui/node_modules/emoji-regex/es2015/RGI_Emoji.jsnu["use strict"; module.exports = () => { // https://mths.be/emoji return /\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0077}\u{E006C}\u{E0073}|\u{E0073}\u{E0063}\u{E0074}|\u{E0065}\u{E006E}\u{E0067})\u{E007F}|(?:\u{1F9D1}\u{1F3FF}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FF}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FE}]|(?:\u{1F9D1}\u{1F3FE}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FE}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FD}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FD}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FC}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FC}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FB}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FB}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FC}-\u{1F3FF}]|\u{1F468}(?:\u{1F3FB}(?:\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FF}]|\u{1F468}[\u{1F3FB}-\u{1F3FF}])|\u{1F91D}\u200D\u{1F468}[\u{1F3FC}-\u{1F3FF}]|[\u2695\u2696\u2708]\uFE0F|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]))?|[\u{1F3FC}-\u{1F3FF}]\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FF}]|\u{1F468}[\u{1F3FB}-\u{1F3FF}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FE}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u{1F466}\u{1F467}])|\u{1F3FF}|\u{1F3FE}|\u{1F3FD}|\u{1F3FC})?|(?:\u{1F469}(?:\u{1F3FB}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F3FC}-\u{1F3FF}]\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}]))|\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]\u200D\u{1F91D}\u200D\u{1F9D1})[\u{1F3FB}-\u{1F3FF}]|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F469}(?:\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FE}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1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52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FD}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FC}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|\u{1F469}\u200D\u{1F467}\u200D[\u{1F466}\u{1F467}]|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F9D1}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\u{1F469}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\u{1F636}\u200D\u{1F32B}|\u{1F3F3}\uFE0F\u200D\u26A7|\u{1F43B}\u200D\u2744|(?:[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\uFE0F\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|\u{1F3F4}\u200D\u2620|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}]\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F202}\u{1F237}\u{1F321}\u{1F324}-\u{1F32C}\u{1F336}\u{1F37D}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}\u{1F39F}\u{1F3CD}\u{1F3CE}\u{1F3D4}-\u{1F3DF}\u{1F3F5}\u{1F3F7}\u{1F43F}\u{1F4FD}\u{1F549}\u{1F54A}\u{1F56F}\u{1F570}\u{1F573}\u{1F576}-\u{1F579}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}\u{1F6CB}\u{1F6CD}-\u{1F6CF}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6F0}\u{1F6F3}])\uFE0F|\u{1F3F3}\uFE0F\u200D\u{1F308}|\u{1F469}\u200D\u{1F467}|\u{1F469}\u200D\u{1F466}|\u{1F635}\u200D\u{1F4AB}|\u{1F62E}\u200D\u{1F4A8}|\u{1F415}\u200D\u{1F9BA}|\u{1F9D1}(?:\u{1F3FF}|\u{1F3FE}|\u{1F3FD}|\u{1F3FC}|\u{1F3FB})?|\u{1F469}(?:\u{1F3FF}|\u{1F3FE}|\u{1F3FD}|\u{1F3FC}|\u{1F3FB})?|\u{1F1FD}\u{1F1F0}|\u{1F1F6}\u{1F1E6}|\u{1F1F4}\u{1F1F2}|\u{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}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\uFE0F\u{1F3FB}-\u{1F3FF}]|\u{1F3F4}|[\u270A\u270B\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F57A}\u{1F595}\u{1F596}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90C}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F934}\u{1F936}\u{1F977}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}\u{1F9D3}\u{1F9D5}][\u{1F3FB}-\u{1F3FF}]|[\u261D\u270C\u270D\u{1F574}\u{1F590}][\uFE0F\u{1F3FB}-\u{1F3FF}]|[\u270A\u270B\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F408}\u{1F415}\u{1F43B}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F57A}\u{1F595}\u{1F596}\u{1F62E}\u{1F635}\u{1F636}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90C}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F934}\u{1F936}\u{1F977}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}\u{1F9D3}\u{1F9D5}]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}]|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F384}\u{1F386}-\u{1F393}\u{1F3A0}-\u{1F3C1}\u{1F3C5}\u{1F3C6}\u{1F3C8}\u{1F3C9}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F8}-\u{1F407}\u{1F409}-\u{1F414}\u{1F416}-\u{1F43A}\u{1F43C}-\u{1F43E}\u{1F440}\u{1F444}\u{1F445}\u{1F451}-\u{1F465}\u{1F46A}\u{1F479}-\u{1F47B}\u{1F47D}-\u{1F480}\u{1F484}\u{1F488}-\u{1F48E}\u{1F490}\u{1F492}-\u{1F4A9}\u{1F4AB}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F5A4}\u{1F5FB}-\u{1F62D}\u{1F62F}-\u{1F634}\u{1F637}-\u{1F644}\u{1F648}-\u{1F64A}\u{1F680}-\u{1F6A2}\u{1F6A4}-\u{1F6B3}\u{1F6B7}-\u{1F6BF}\u{1F6C1}-\u{1F6C5}\u{1F6D0}-\u{1F6D2}\u{1F6D5}-\u{1F6D7}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FC}\u{1F7E0}-\u{1F7EB}\u{1F90D}\u{1F90E}\u{1F910}-\u{1F917}\u{1F91D}\u{1F920}-\u{1F925}\u{1F927}-\u{1F92F}\u{1F93A}\u{1F93F}-\u{1F945}\u{1F947}-\u{1F976}\u{1F978}\u{1F97A}-\u{1F9B4}\u{1F9B7}\u{1F9BA}\u{1F9BC}-\u{1F9CB}\u{1F9D0}\u{1F9E0}-\u{1F9FF}\u{1FA70}-\u{1FA74}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA86}\u{1FA90}-\u{1FAA8}\u{1FAB0}-\u{1FAB6}\u{1FAC0}-\u{1FAC2}\u{1FAD0}-\u{1FAD6}]/gu; }; PK ~\223@isaacs/cliui/node_modules/emoji-regex/RGI_Emoji.jsnu["use strict"; module.exports = function () { // https://mths.be/emoji return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\u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D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDD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uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]/g; }; PK ~\@ 5@isaacs/cliui/node_modules/wrap-ansi-cjs/package.jsonnu[{ "_from": "wrap-ansi-cjs@npm:wrap-ansi@^7.0.0", "_id": "wrap-ansi@7.0.0", "_inBundle": false, "_integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", "_location": "/npm/@isaacs/cliui/wrap-ansi-cjs", "_phantomChildren": { "is-fullwidth-code-point": "3.0.0" }, "_requested": { "type": "alias", "registry": true, "raw": "wrap-ansi-cjs@npm:wrap-ansi@^7.0.0", "name": "wrap-ansi-cjs", "escapedName": "wrap-ansi-cjs", "rawSpec": "npm:wrap-ansi@^7.0.0", "saveSpec": null, "fetchSpec": null, "subSpec": { "type": "range", "registry": true, "raw": "wrap-ansi@^7.0.0", "name": "wrap-ansi", "escapedName": "wrap-ansi", "rawSpec": "^7.0.0", "saveSpec": null, "fetchSpec": "^7.0.0" } }, "_requiredBy": [ "/npm/@isaacs/cliui" ], "_resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", "_shasum": "67e145cff510a6a6984bdf1152911d69d2eb9e43", "_spec": "wrap-ansi-cjs@npm:wrap-ansi@^7.0.0", "_where": "C:\\xampp\\htdocs\\emeraltd\\node_modules\\npm\\node_modules\\@isaacs\\cliui", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "bugs": { "url": "https://github.com/chalk/wrap-ansi/issues" }, "bundleDependencies": false, "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" }, "deprecated": false, "description": "Wordwrap a string with ANSI escape codes", "devDependencies": { "ava": "^2.1.0", "chalk": "^4.0.0", "coveralls": "^3.0.3", "has-ansi": "^4.0.0", "nyc": "^15.0.1", "xo": "^0.29.1" }, "engines": { "node": ">=10" }, "files": [ "index.js" ], "funding": "https://github.com/chalk/wrap-ansi?sponsor=1", "homepage": "https://github.com/chalk/wrap-ansi#readme", "keywords": [ "wrap", "break", "wordwrap", "wordbreak", "linewrap", "ansi", "styles", "color", "colour", "colors", "terminal", "console", "cli", "string", "tty", "escape", "formatting", "rgb", "256", "shell", "xterm", "log", "logging", "command-line", "text" ], "license": "MIT", "name": "wrap-ansi", "repository": { "type": "git", "url": "git+https://github.com/chalk/wrap-ansi.git" }, "scripts": { "test": "xo && nyc ava" }, "version": "7.0.0" } PK ~\""/(/(I@isaacs/cliui/node_modules/wrap-ansi-cjs/node_modules/emoji-regex/text.jsnu["use strict"; module.exports = function () { // https://mths.be/emoji return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\u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\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC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K ~\QkN@isaacs/cliui/node_modules/wrap-ansi-cjs/node_modules/emoji-regex/package.jsonnu[{ "_from": "emoji-regex@^8.0.0", "_id": "emoji-regex@8.0.0", "_inBundle": false, "_integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", "_location": "/npm/@isaacs/cliui/wrap-ansi-cjs/emoji-regex", "_phantomChildren": {}, "_requested": { "type": "range", "registry": true, "raw": "emoji-regex@^8.0.0", "name": "emoji-regex", "escapedName": "emoji-regex", "rawSpec": "^8.0.0", "saveSpec": null, "fetchSpec": "^8.0.0" }, "_requiredBy": [ "/npm/@isaacs/cliui/wrap-ansi-cjs/string-width" ], "_resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", "_shasum": "e818fd69ce5ccfcb404594f842963bf53164cc37", "_spec": "emoji-regex@^8.0.0", "_where": "C:\\xampp\\htdocs\\emeraltd\\node_modules\\npm\\node_modules\\@isaacs\\cliui\\node_modules\\wrap-ansi-cjs\\node_modules\\string-width", "author": { "name": "Mathias Bynens", "url": "https://mathiasbynens.be/" }, "bugs": { "url": "https://github.com/mathiasbynens/emoji-regex/issues" }, "bundleDependencies": false, "deprecated": false, "description": "A regular expression to match all Emoji-only symbols as per the Unicode Standard.", "devDependencies": { "@babel/cli": "^7.2.3", "@babel/core": "^7.3.4", "@babel/plugin-proposal-unicode-property-regex": "^7.2.0", "@babel/preset-env": "^7.3.4", "mocha": "^6.0.2", "regexgen": "^1.3.0", "unicode-12.0.0": "^0.7.9" }, "files": [ "LICENSE-MIT.txt", "index.js", "index.d.ts", "text.js", "es2015/index.js", "es2015/text.js" ], "homepage": "https://mths.be/emoji-regex", "keywords": [ "unicode", "regex", "regexp", "regular expressions", "code points", "symbols", "characters", "emoji" ], "license": "MIT", "main": "index.js", "name": "emoji-regex", "repository": { "type": "git", "url": "git+https://github.com/mathiasbynens/emoji-regex.git" }, "scripts": { "build": "rm -rf -- es2015; babel src -d .; NODE_ENV=es2015 babel src -d ./es2015; node script/inject-sequences.js", "test": "mocha", "test:watch": "npm run test -- --watch" }, "types": "index.d.ts", "version": "8.0.0" } PK ~\C".(.(J@isaacs/cliui/node_modules/wrap-ansi-cjs/node_modules/emoji-regex/index.jsnu["use strict"; module.exports = function () { // https://mths.be/emoji return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uD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EC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\u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])/g; }; PK ~\ڌC55Q@isaacs/cliui/node_modules/wrap-ansi-cjs/node_modules/emoji-regex/LICENSE-MIT.txtnu[Copyright Mathias Bynens Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\a+a+P@isaacs/cliui/node_modules/wrap-ansi-cjs/node_modules/emoji-regex/es2015/text.jsnu["use strict"; module.exports = () => { // https://mths.be/emoji return /\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0065}\u{E006E}\u{E0067}|\u{E0073}\u{E0063}\u{E0074}|\u{E0077}\u{E006C}\u{E0073})\u{E007F}|\u{1F468}(?:\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}\u{1F3FB}|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FE}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u2695\u2696\u2708]\uFE0F|[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|(?:\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708])\uFE0F|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|[\u{1F3FB}-\u{1F3FF}])|(?:\u{1F9D1}\u{1F3FB}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F469})\u{1F3FB}|\u{1F9D1}(?:\u{1F3FF}\u200D\u{1F91D}\u200D\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]|\u200D\u{1F91D}\u200D\u{1F9D1})|(?:\u{1F9D1}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FF}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FE}]|(?:\u{1F9D1}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}\u{1F3FC}]|\u{1F469}(?:\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FB}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FC}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|(?:\u{1F9D1}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}-\u{1F3FD}]|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F469}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}]\uFE0F|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D6}-\u{1F9DD}](?:[\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\u{1F3F4}\u200D\u2620)\uFE0F|\u{1F469}\u200D\u{1F467}\u200D[\u{1F466}\u{1F467}]|\u{1F3F3}\uFE0F\u200D\u{1F308}|\u{1F415}\u200D\u{1F9BA}|\u{1F469}\u200D\u{1F466}|\u{1F469}\u200D\u{1F467}|\u{1F1FD}\u{1F1F0}|\u{1F1F4}\u{1F1F2}|\u{1F1F6}\u{1F1E6}|[#\*0-9]\uFE0F\u20E3|\u{1F1E7}[\u{1F1E6}\u{1F1E7}\u{1F1E9}-\u{1F1EF}\u{1F1F1}-\u{1F1F4}\u{1F1F6}-\u{1F1F9}\u{1F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[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]|[\u261D\u270A-\u270D\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F470}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F4AA}\u{1F574}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F936}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}-\u{1F9D5}][\u{1F3FB}-\u{1F3FF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F393}\u{1F3A0}-\u{1F3CA}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F4}\u{1F3F8}-\u{1F43E}\u{1F440}\u{1F442}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F57A}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5FB}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CC}\u{1F6D0}-\u{1F6D2}\u{1F6D5}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]|[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299\u{1F004}\u{1F0CF}\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F321}\u{1F324}-\u{1F393}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}-\u{1F3F0}\u{1F3F3}-\u{1F3F5}\u{1F3F7}-\u{1F4FD}\u{1F4FF}-\u{1F53D}\u{1F549}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F56F}\u{1F570}\u{1F573}-\u{1F57A}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F590}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CB}-\u{1F6D2}\u{1F6D5}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6EB}\u{1F6EC}\u{1F6F0}\u{1F6F3}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]\uFE0F?|[\u261D\u26F9\u270A-\u270D\u{1F385}\u{1F3C2}-\u{1F3C4}\u{1F3C7}\u{1F3CA}-\u{1F3CC}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}-\u{1F478}\u{1F47C}\u{1F481}-\u{1F483}\u{1F485}-\u{1F487}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F574}\u{1F575}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F645}-\u{1F647}\u{1F64B}-\u{1F64F}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91F}\u{1F926}\u{1F930}-\u{1F939}\u{1F93C}-\u{1F93E}\u{1F9B5}\u{1F9B6}\u{1F9B8}\u{1F9B9}\u{1F9BB}\u{1F9CD}-\u{1F9CF}\u{1F9D1}-\u{1F9DD}]/gu; }; PK ~\`+`+Q@isaacs/cliui/node_modules/wrap-ansi-cjs/node_modules/emoji-regex/es2015/index.jsnu["use strict"; module.exports = () => { // https://mths.be/emoji return /\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0065}\u{E006E}\u{E0067}|\u{E0073}\u{E0063}\u{E0074}|\u{E0077}\u{E006C}\u{E0073})\u{E007F}|\u{1F468}(?:\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}\u{1F3FB}|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FE}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u2695\u2696\u2708]\uFE0F|[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|(?:\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708])\uFE0F|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|[\u{1F3FB}-\u{1F3FF}])|(?:\u{1F9D1}\u{1F3FB}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F469})\u{1F3FB}|\u{1F9D1}(?:\u{1F3FF}\u200D\u{1F91D}\u200D\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]|\u200D\u{1F91D}\u200D\u{1F9D1})|(?:\u{1F9D1}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FF}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FE}]|(?:\u{1F9D1}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}\u{1F3FC}]|\u{1F469}(?:\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FB}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FC}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|(?:\u{1F9D1}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}-\u{1F3FD}]|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F469}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}]\uFE0F|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1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B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}-\u{1F9D5}][\u{1F3FB}-\u{1F3FF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F393}\u{1F3A0}-\u{1F3CA}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F4}\u{1F3F8}-\u{1F43E}\u{1F440}\u{1F442}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F57A}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5FB}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CC}\u{1F6D0}-\u{1F6D2}\u{1F6D5}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]|[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299\u{1F004}\u{1F0CF}\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F321}\u{1F324}-\u{1F393}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}-\u{1F3F0}\u{1F3F3}-\u{1F3F5}\u{1F3F7}-\u{1F4FD}\u{1F4FF}-\u{1F53D}\u{1F549}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F56F}\u{1F570}\u{1F573}-\u{1F57A}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F590}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CB}-\u{1F6D2}\u{1F6D5}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6EB}\u{1F6EC}\u{1F6F0}\u{1F6F3}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]\uFE0F|[\u261D\u26F9\u270A-\u270D\u{1F385}\u{1F3C2}-\u{1F3C4}\u{1F3C7}\u{1F3CA}-\u{1F3CC}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}-\u{1F478}\u{1F47C}\u{1F481}-\u{1F483}\u{1F485}-\u{1F487}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F574}\u{1F575}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F645}-\u{1F647}\u{1F64B}-\u{1F64F}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91F}\u{1F926}\u{1F930}-\u{1F939}\u{1F93C}-\u{1F93E}\u{1F9B5}\u{1F9B6}\u{1F9B8}\u{1F9B9}\u{1F9BB}\u{1F9CD}-\u{1F9CF}\u{1F9D1}-\u{1F9DD}]/gu; }; PK ~\mms K@isaacs/cliui/node_modules/wrap-ansi-cjs/node_modules/emoji-regex/README.mdnu[# emoji-regex [![Build status](https://travis-ci.org/mathiasbynens/emoji-regex.svg?branch=master)](https://travis-ci.org/mathiasbynens/emoji-regex) _emoji-regex_ offers a regular expression to match all emoji symbols (including textual representations of emoji) as per the Unicode Standard. This repository contains a script that generates this regular expression based on [the data from Unicode v12](https://github.com/mathiasbynens/unicode-12.0.0). Because of this, the regular expression can easily be updated whenever new emoji are added to the Unicode standard. ## Installation Via [npm](https://www.npmjs.com/): ```bash npm install emoji-regex ``` In [Node.js](https://nodejs.org/): ```js const emojiRegex = require('emoji-regex'); // Note: because the regular expression has the global flag set, this module // exports a function that returns the regex rather than exporting the regular // expression itself, to make it impossible to (accidentally) mutate the // original regular expression. const text = ` \u{231A}: ⌚ default emoji presentation character (Emoji_Presentation) \u{2194}\u{FE0F}: ↔️ default text presentation character rendered as emoji \u{1F469}: 👩 emoji modifier base (Emoji_Modifier_Base) \u{1F469}\u{1F3FF}: 👩🏿 emoji modifier base followed by a modifier `; const regex = emojiRegex(); let match; while (match = regex.exec(text)) { const emoji = match[0]; console.log(`Matched sequence ${ emoji } — code points: ${ [...emoji].length }`); } ``` Console output: ``` Matched sequence ⌚ — code points: 1 Matched sequence ⌚ — code points: 1 Matched sequence ↔️ — code points: 2 Matched sequence ↔️ — code points: 2 Matched sequence 👩 — code points: 1 Matched sequence 👩 — code points: 1 Matched sequence 👩🏿 — code points: 2 Matched sequence 👩🏿 — code points: 2 ``` To match emoji in their textual representation as well (i.e. emoji that are not `Emoji_Presentation` symbols and that aren’t forced to render as emoji by a variation selector), `require` the other regex: ```js const emojiRegex = require('emoji-regex/text.js'); ``` Additionally, in environments which support ES2015 Unicode escapes, you may `require` ES2015-style versions of the regexes: ```js const emojiRegex = require('emoji-regex/es2015/index.js'); const emojiRegexText = require('emoji-regex/es2015/text.js'); ``` ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License _emoji-regex_ is available under the [MIT](https://mths.be/mit) license. PK ~\cWL@isaacs/cliui/node_modules/wrap-ansi-cjs/node_modules/emoji-regex/index.d.tsnu[declare module 'emoji-regex' { function emojiRegex(): RegExp; export default emojiRegex; } declare module 'emoji-regex/text' { function emojiRegex(): RegExp; export default emojiRegex; } declare module 'emoji-regex/es2015' { function emojiRegex(): RegExp; export default emojiRegex; } declare module 'emoji-regex/es2015/text' { function emojiRegex(): RegExp; export default emojiRegex; } PK ~\0O@isaacs/cliui/node_modules/wrap-ansi-cjs/node_modules/string-width/package.jsonnu[{ "_from": "string-width@^4.1.0", "_id": "string-width@4.2.3", "_inBundle": false, "_integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", "_location": "/npm/@isaacs/cliui/wrap-ansi-cjs/string-width", "_phantomChildren": {}, "_requested": { "type": "range", "registry": true, "raw": "string-width@^4.1.0", "name": "string-width", "escapedName": "string-width", "rawSpec": "^4.1.0", "saveSpec": null, "fetchSpec": "^4.1.0" }, "_requiredBy": [ "/npm/@isaacs/cliui/wrap-ansi-cjs" ], "_resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", "_shasum": "269c7117d27b05ad2e536830a8ec895ef9c6d010", "_spec": "string-width@^4.1.0", "_where": "C:\\xampp\\htdocs\\emeraltd\\node_modules\\npm\\node_modules\\@isaacs\\cliui\\node_modules\\wrap-ansi-cjs", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "bugs": { "url": "https://github.com/sindresorhus/string-width/issues" }, "bundleDependencies": false, "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" }, "deprecated": false, "description": "Get the visual width of a string - the number of columns required to display it", "devDependencies": { "ava": "^1.4.1", "tsd": "^0.7.1", "xo": "^0.24.0" }, "engines": { "node": ">=8" }, "files": [ "index.js", "index.d.ts" ], "homepage": "https://github.com/sindresorhus/string-width#readme", "keywords": [ "string", "character", "unicode", "width", "visual", "column", "columns", "fullwidth", "full-width", "full", "ansi", "escape", "codes", "cli", "command-line", "terminal", "console", "cjk", "chinese", "japanese", "korean", "fixed-width" ], "license": "MIT", "name": "string-width", "repository": { "type": "git", "url": "git+https://github.com/sindresorhus/string-width.git" }, "scripts": { "test": "xo && ava && tsd" }, "version": "4.2.3" } PK ~\w78ttL@isaacs/cliui/node_modules/wrap-ansi-cjs/node_modules/string-width/readme.mdnu[# string-width > Get the visual width of a string - the number of columns required to display it Some Unicode characters are [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) and use double the normal width. [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) are stripped and doesn't affect the width. Useful to be able to measure the actual width of command-line output. ## Install ``` $ npm install string-width ``` ## Usage ```js const stringWidth = require('string-width'); stringWidth('a'); //=> 1 stringWidth('古'); //=> 2 stringWidth('\u001B[1m古\u001B[22m'); //=> 2 ``` ## Related - [string-width-cli](https://github.com/sindresorhus/string-width-cli) - CLI for this module - [string-length](https://github.com/sindresorhus/string-length) - Get the real length of a string - [widest-line](https://github.com/sindresorhus/widest-line) - Get the visual width of the widest line in a string ---
Get professional support for this package with a Tidelift subscription
Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies.
PK ~\IkK@isaacs/cliui/node_modules/wrap-ansi-cjs/node_modules/string-width/index.jsnu['use strict'; const stripAnsi = require('strip-ansi'); const isFullwidthCodePoint = require('is-fullwidth-code-point'); const emojiRegex = require('emoji-regex'); const stringWidth = string => { if (typeof string !== 'string' || string.length === 0) { return 0; } string = stripAnsi(string); if (string.length === 0) { return 0; } string = string.replace(emojiRegex(), ' '); let width = 0; for (let i = 0; i < string.length; i++) { const code = string.codePointAt(i); // Ignore control characters if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { continue; } // Ignore combining characters if (code >= 0x300 && code <= 0x36F) { continue; } // Surrogates if (code > 0xFFFF) { i++; } width += isFullwidthCodePoint(code) ? 2 : 1; } return width; }; module.exports = stringWidth; // TODO: remove this in the next major version module.exports.default = stringWidth; PK ~\E}UUJ@isaacs/cliui/node_modules/wrap-ansi-cjs/node_modules/string-width/licensenu[MIT License Copyright (c) Sindre Sorhus (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\SM@isaacs/cliui/node_modules/wrap-ansi-cjs/node_modules/string-width/index.d.tsnu[declare const stringWidth: { /** Get the visual width of a string - the number of columns required to display it. Some Unicode characters are [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) and use double the normal width. [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) are stripped and doesn't affect the width. @example ``` import stringWidth = require('string-width'); stringWidth('a'); //=> 1 stringWidth('古'); //=> 2 stringWidth('\u001B[1m古\u001B[22m'); //=> 2 ``` */ (string: string): number; // TODO: remove this in the next major version, refactor the whole definition to: // declare function stringWidth(string: string): number; // export = stringWidth; default: typeof stringWidth; } export = stringWidth; PK ~\o_sM@isaacs/cliui/node_modules/wrap-ansi-cjs/node_modules/strip-ansi/package.jsonnu[{ "_from": "strip-ansi@^6.0.0", "_id": "strip-ansi@6.0.1", "_inBundle": false, "_integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "_location": "/npm/@isaacs/cliui/wrap-ansi-cjs/strip-ansi", "_phantomChildren": {}, "_requested": { "type": "range", "registry": true, "raw": "strip-ansi@^6.0.0", "name": "strip-ansi", "escapedName": "strip-ansi", "rawSpec": "^6.0.0", "saveSpec": null, "fetchSpec": "^6.0.0" }, "_requiredBy": [ "/npm/@isaacs/cliui/wrap-ansi-cjs", "/npm/@isaacs/cliui/wrap-ansi-cjs/string-width" ], "_resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "_shasum": "9e26c63d30f53443e9489495b2105d37b67a85d9", "_spec": "strip-ansi@^6.0.0", "_where": "C:\\xampp\\htdocs\\emeraltd\\node_modules\\npm\\node_modules\\@isaacs\\cliui\\node_modules\\wrap-ansi-cjs", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "bugs": { "url": "https://github.com/chalk/strip-ansi/issues" }, "bundleDependencies": false, "dependencies": { "ansi-regex": "^5.0.1" }, "deprecated": false, "description": "Strip ANSI escape codes from a string", "devDependencies": { "ava": "^2.4.0", "tsd": "^0.10.0", "xo": "^0.25.3" }, "engines": { "node": ">=8" }, "files": [ "index.js", "index.d.ts" ], "homepage": "https://github.com/chalk/strip-ansi#readme", "keywords": [ "strip", "trim", "remove", "ansi", "styles", "color", "colour", "colors", "terminal", "console", "string", "tty", "escape", "formatting", "rgb", "256", "shell", "xterm", "log", "logging", "command-line", "text" ], "license": "MIT", "name": "strip-ansi", "repository": { "type": "git", "url": "git+https://github.com/chalk/strip-ansi.git" }, "scripts": { "test": "xo && ava && tsd" }, "version": "6.0.1" } PK ~\<??J@isaacs/cliui/node_modules/wrap-ansi-cjs/node_modules/strip-ansi/readme.mdnu[# strip-ansi [![Build Status](https://travis-ci.org/chalk/strip-ansi.svg?branch=master)](https://travis-ci.org/chalk/strip-ansi) > Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string ## Install ``` $ npm install strip-ansi ``` ## Usage ```js const stripAnsi = require('strip-ansi'); stripAnsi('\u001B[4mUnicorn\u001B[0m'); //=> 'Unicorn' stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'); //=> 'Click' ``` ## strip-ansi for enterprise Available as part of the Tidelift Subscription. The maintainers of strip-ansi and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-strip-ansi?utm_source=npm-strip-ansi&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) ## Related - [strip-ansi-cli](https://github.com/chalk/strip-ansi-cli) - CLI for this module - [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Streaming version of this module - [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes - [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes - [chalk](https://github.com/chalk/chalk) - Terminal string styling done right ## Maintainers - [Sindre Sorhus](https://github.com/sindresorhus) - [Josh Junon](https://github.com/qix-) PK ~\*9I@isaacs/cliui/node_modules/wrap-ansi-cjs/node_modules/strip-ansi/index.jsnu['use strict'; const ansiRegex = require('ansi-regex'); module.exports = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; PK ~\E}UUH@isaacs/cliui/node_modules/wrap-ansi-cjs/node_modules/strip-ansi/licensenu[MIT License Copyright (c) Sindre Sorhus (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\/qqK@isaacs/cliui/node_modules/wrap-ansi-cjs/node_modules/strip-ansi/index.d.tsnu[/** Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string. @example ``` import stripAnsi = require('strip-ansi'); stripAnsi('\u001B[4mUnicorn\u001B[0m'); //=> 'Unicorn' stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'); //=> 'Click' ``` */ declare function stripAnsi(string: string): string; export = stripAnsi; PK ~\k!%%M@isaacs/cliui/node_modules/wrap-ansi-cjs/node_modules/ansi-regex/package.jsonnu[{ "_from": "ansi-regex@^5.0.1", "_id": "ansi-regex@5.0.1", "_inBundle": false, "_integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "_location": "/npm/@isaacs/cliui/wrap-ansi-cjs/ansi-regex", "_phantomChildren": {}, "_requested": { "type": "range", "registry": true, "raw": "ansi-regex@^5.0.1", "name": "ansi-regex", "escapedName": "ansi-regex", "rawSpec": "^5.0.1", "saveSpec": null, "fetchSpec": "^5.0.1" }, "_requiredBy": [ "/npm/@isaacs/cliui/wrap-ansi-cjs/strip-ansi" ], "_resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "_shasum": "082cb2c89c9fe8659a311a53bd6a4dc5301db304", "_spec": "ansi-regex@^5.0.1", "_where": "C:\\xampp\\htdocs\\emeraltd\\node_modules\\npm\\node_modules\\@isaacs\\cliui\\node_modules\\wrap-ansi-cjs\\node_modules\\strip-ansi", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "bugs": { "url": "https://github.com/chalk/ansi-regex/issues" }, "bundleDependencies": false, "deprecated": false, "description": "Regular expression for matching ANSI escape codes", "devDependencies": { "ava": "^2.4.0", "tsd": "^0.9.0", "xo": "^0.25.3" }, "engines": { "node": ">=8" }, "files": [ "index.js", "index.d.ts" ], "homepage": "https://github.com/chalk/ansi-regex#readme", "keywords": [ "ansi", "styles", "color", "colour", "colors", "terminal", "console", "cli", "string", "tty", "escape", "formatting", "rgb", "256", "shell", "xterm", "command-line", "text", "regex", "regexp", "re", "match", "test", "find", "pattern" ], "license": "MIT", "name": "ansi-regex", "repository": { "type": "git", "url": "git+https://github.com/chalk/ansi-regex.git" }, "scripts": { "test": "xo && ava && tsd", "view-supported": "node fixtures/view-codes.js" }, "version": "5.0.1" } PK ~\DR$  J@isaacs/cliui/node_modules/wrap-ansi-cjs/node_modules/ansi-regex/readme.mdnu[# ansi-regex > Regular expression for matching [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) ## Install ``` $ npm install ansi-regex ``` ## Usage ```js const ansiRegex = require('ansi-regex'); ansiRegex().test('\u001B[4mcake\u001B[0m'); //=> true ansiRegex().test('cake'); //=> false '\u001B[4mcake\u001B[0m'.match(ansiRegex()); //=> ['\u001B[4m', '\u001B[0m'] '\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true})); //=> ['\u001B[4m'] '\u001B]8;;https://github.com\u0007click\u001B]8;;\u0007'.match(ansiRegex()); //=> ['\u001B]8;;https://github.com\u0007', '\u001B]8;;\u0007'] ``` ## API ### ansiRegex(options?) Returns a regex for matching ANSI escape codes. #### options Type: `object` ##### onlyFirst Type: `boolean`
Default: `false` *(Matches any ANSI escape codes in a string)* Match only the first ANSI escape. ## FAQ ### Why do you test for codes not in the ECMA 48 standard? Some of the codes we run as a test are codes that we acquired finding various lists of non-standard or manufacturer specific codes. We test for both standard and non-standard codes, as most of them follow the same or similar format and can be safely matched in strings without the risk of removing actual string content. There are a few non-standard control codes that do not follow the traditional format (i.e. they end in numbers) thus forcing us to exclude them from the test because we cannot reliably match them. On the historical side, those ECMA standards were established in the early 90's whereas the VT100, for example, was designed in the mid/late 70's. At that point in time, control codes were still pretty ungoverned and engineers used them for a multitude of things, namely to activate hardware ports that may have been proprietary. Somewhere else you see a similar 'anarchy' of codes is in the x86 architecture for processors; there are a ton of "interrupts" that can mean different things on certain brands of processors, most of which have been phased out. ## Maintainers - [Sindre Sorhus](https://github.com/sindresorhus) - [Josh Junon](https://github.com/qix-) ---
Get professional support for this package with a Tidelift subscription
Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies.
PK ~\^(]^^I@isaacs/cliui/node_modules/wrap-ansi-cjs/node_modules/ansi-regex/index.jsnu['use strict'; module.exports = ({onlyFirst = false} = {}) => { const pattern = [ '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' ].join('|'); return new RegExp(pattern, onlyFirst ? undefined : 'g'); }; PK ~\E}UUH@isaacs/cliui/node_modules/wrap-ansi-cjs/node_modules/ansi-regex/licensenu[MIT License Copyright (c) Sindre Sorhus (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\06K@isaacs/cliui/node_modules/wrap-ansi-cjs/node_modules/ansi-regex/index.d.tsnu[declare namespace ansiRegex { interface Options { /** Match only the first ANSI escape. @default false */ onlyFirst: boolean; } } /** Regular expression for matching ANSI escape codes. @example ``` import ansiRegex = require('ansi-regex'); ansiRegex().test('\u001B[4mcake\u001B[0m'); //=> true ansiRegex().test('cake'); //=> false '\u001B[4mcake\u001B[0m'.match(ansiRegex()); //=> ['\u001B[4m', '\u001B[0m'] '\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true})); //=> ['\u001B[4m'] '\u001B]8;;https://github.com\u0007click\u001B]8;;\u0007'.match(ansiRegex()); //=> ['\u001B]8;;https://github.com\u0007', '\u001B]8;;\u0007'] ``` */ declare function ansiRegex(options?: ansiRegex.Options): RegExp; export = ansiRegex; PK ~\& 2@isaacs/cliui/node_modules/wrap-ansi-cjs/readme.mdnu[# wrap-ansi [![Build Status](https://travis-ci.com/chalk/wrap-ansi.svg?branch=master)](https://travis-ci.com/chalk/wrap-ansi) [![Coverage Status](https://coveralls.io/repos/github/chalk/wrap-ansi/badge.svg?branch=master)](https://coveralls.io/github/chalk/wrap-ansi?branch=master) > Wordwrap a string with [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) ## Install ``` $ npm install wrap-ansi ``` ## Usage ```js const chalk = require('chalk'); const wrapAnsi = require('wrap-ansi'); const input = 'The quick brown ' + chalk.red('fox jumped over ') + 'the lazy ' + chalk.green('dog and then ran away with the unicorn.'); console.log(wrapAnsi(input, 20)); ``` ## API ### wrapAnsi(string, columns, options?) Wrap words to the specified column width. #### string Type: `string` String with ANSI escape codes. Like one styled by [`chalk`](https://github.com/chalk/chalk). Newline characters will be normalized to `\n`. #### columns Type: `number` Number of columns to wrap the text to. #### options Type: `object` ##### hard Type: `boolean`\ Default: `false` By default the wrap is soft, meaning long words may extend past the column width. Setting this to `true` will make it hard wrap at the column width. ##### wordWrap Type: `boolean`\ Default: `true` By default, an attempt is made to split words at spaces, ensuring that they don't extend past the configured columns. If wordWrap is `false`, each column will instead be completely filled splitting words as necessary. ##### trim Type: `boolean`\ Default: `true` Whitespace on all lines is removed by default. Set this option to `false` if you don't want to trim. ## Related - [slice-ansi](https://github.com/chalk/slice-ansi) - Slice a string with ANSI escape codes - [cli-truncate](https://github.com/sindresorhus/cli-truncate) - Truncate a string to a specific width in the terminal - [chalk](https://github.com/chalk/chalk) - Terminal string styling done right - [jsesc](https://github.com/mathiasbynens/jsesc) - Generate ASCII-only output from Unicode strings. Useful for creating test fixtures. ## Maintainers - [Sindre Sorhus](https://github.com/sindresorhus) - [Josh Junon](https://github.com/qix-) - [Benjamin Coe](https://github.com/bcoe) ---
Get professional support for this package with a Tidelift subscription
Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies.
PK ~\h1@isaacs/cliui/node_modules/wrap-ansi-cjs/index.jsnu['use strict'; const stringWidth = require('string-width'); const stripAnsi = require('strip-ansi'); const ansiStyles = require('ansi-styles'); const ESCAPES = new Set([ '\u001B', '\u009B' ]); const END_CODE = 39; const ANSI_ESCAPE_BELL = '\u0007'; const ANSI_CSI = '['; const ANSI_OSC = ']'; const ANSI_SGR_TERMINATOR = 'm'; const ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`; const wrapAnsi = code => `${ESCAPES.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`; const wrapAnsiHyperlink = uri => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${uri}${ANSI_ESCAPE_BELL}`; // Calculate the length of words split on ' ', ignoring // the extra characters added by ansi escape codes const wordLengths = string => string.split(' ').map(character => stringWidth(character)); // Wrap a long word across multiple rows // Ansi escape codes do not count towards length const wrapWord = (rows, word, columns) => { const characters = [...word]; let isInsideEscape = false; let isInsideLinkEscape = false; let visible = stringWidth(stripAnsi(rows[rows.length - 1])); for (const [index, character] of characters.entries()) { const characterLength = stringWidth(character); if (visible + characterLength <= columns) { rows[rows.length - 1] += character; } else { rows.push(character); visible = 0; } if (ESCAPES.has(character)) { isInsideEscape = true; isInsideLinkEscape = characters.slice(index + 1).join('').startsWith(ANSI_ESCAPE_LINK); } if (isInsideEscape) { if (isInsideLinkEscape) { if (character === ANSI_ESCAPE_BELL) { isInsideEscape = false; isInsideLinkEscape = false; } } else if (character === ANSI_SGR_TERMINATOR) { isInsideEscape = false; } continue; } visible += characterLength; if (visible === columns && index < characters.length - 1) { rows.push(''); visible = 0; } } // It's possible that the last row we copy over is only // ansi escape characters, handle this edge-case if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) { rows[rows.length - 2] += rows.pop(); } }; // Trims spaces from a string ignoring invisible sequences const stringVisibleTrimSpacesRight = string => { const words = string.split(' '); let last = words.length; while (last > 0) { if (stringWidth(words[last - 1]) > 0) { break; } last--; } if (last === words.length) { return string; } return words.slice(0, last).join(' ') + words.slice(last).join(''); }; // The wrap-ansi module can be invoked in either 'hard' or 'soft' wrap mode // // 'hard' will never allow a string to take up more than columns characters // // 'soft' allows long words to expand past the column length const exec = (string, columns, options = {}) => { if (options.trim !== false && string.trim() === '') { return ''; } let returnValue = ''; let escapeCode; let escapeUrl; const lengths = wordLengths(string); let rows = ['']; for (const [index, word] of string.split(' ').entries()) { if (options.trim !== false) { rows[rows.length - 1] = rows[rows.length - 1].trimStart(); } let rowLength = stringWidth(rows[rows.length - 1]); if (index !== 0) { if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) { // If we start with a new word but the current row length equals the length of the columns, add a new row rows.push(''); rowLength = 0; } if (rowLength > 0 || options.trim === false) { rows[rows.length - 1] += ' '; rowLength++; } } // In 'hard' wrap mode, the length of a line is never allowed to extend past 'columns' if (options.hard && lengths[index] > columns) { const remainingColumns = (columns - rowLength); const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns); const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns); if (breaksStartingNextLine < breaksStartingThisLine) { rows.push(''); } wrapWord(rows, word, columns); continue; } if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) { if (options.wordWrap === false && rowLength < columns) { wrapWord(rows, word, columns); continue; } rows.push(''); } if (rowLength + lengths[index] > columns && options.wordWrap === false) { wrapWord(rows, word, columns); continue; } rows[rows.length - 1] += word; } if (options.trim !== false) { rows = rows.map(stringVisibleTrimSpacesRight); } const pre = [...rows.join('\n')]; for (const [index, character] of pre.entries()) { returnValue += character; if (ESCAPES.has(character)) { const {groups} = new RegExp(`(?:\\${ANSI_CSI}(?\\d+)m|\\${ANSI_ESCAPE_LINK}(?.*)${ANSI_ESCAPE_BELL})`).exec(pre.slice(index).join('')) || {groups: {}}; if (groups.code !== undefined) { const code = Number.parseFloat(groups.code); escapeCode = code === END_CODE ? undefined : code; } else if (groups.uri !== undefined) { escapeUrl = groups.uri.length === 0 ? undefined : groups.uri; } } const code = ansiStyles.codes.get(Number(escapeCode)); if (pre[index + 1] === '\n') { if (escapeUrl) { returnValue += wrapAnsiHyperlink(''); } if (escapeCode && code) { returnValue += wrapAnsi(code); } } else if (character === '\n') { if (escapeCode && code) { returnValue += wrapAnsi(escapeCode); } if (escapeUrl) { returnValue += wrapAnsiHyperlink(escapeUrl); } } } return returnValue; }; // For each newline, invoke the method separately module.exports = (string, columns, options) => { return String(string) .normalize() .replace(/\r\n/g, '\n') .split('\n') .map(line => exec(line, columns, options)) .join('\n'); }; PK ~\i]]0@isaacs/cliui/node_modules/wrap-ansi-cjs/licensenu[MIT License Copyright (c) Sindre Sorhus (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\Ә 8@isaacs/cliui/node_modules/string-width-cjs/package.jsonnu[{ "_from": "string-width-cjs@npm:string-width@^4.2.0", "_id": "string-width@4.2.3", "_inBundle": false, "_integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", "_location": "/npm/@isaacs/cliui/string-width-cjs", "_phantomChildren": {}, "_requested": { "type": "alias", "registry": true, "raw": "string-width-cjs@npm:string-width@^4.2.0", "name": "string-width-cjs", "escapedName": "string-width-cjs", "rawSpec": "npm:string-width@^4.2.0", "saveSpec": null, "fetchSpec": null, "subSpec": { "type": "range", "registry": true, "raw": "string-width@^4.2.0", "name": "string-width", "escapedName": "string-width", "rawSpec": "^4.2.0", "saveSpec": null, "fetchSpec": "^4.2.0" } }, "_requiredBy": [ "/npm/@isaacs/cliui" ], "_resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", "_shasum": "269c7117d27b05ad2e536830a8ec895ef9c6d010", "_spec": "string-width-cjs@npm:string-width@^4.2.0", "_where": "C:\\xampp\\htdocs\\emeraltd\\node_modules\\npm\\node_modules\\@isaacs\\cliui", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "bugs": { "url": "https://github.com/sindresorhus/string-width/issues" }, "bundleDependencies": false, "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" }, "deprecated": false, "description": "Get the visual width of a string - the number of columns required to display it", "devDependencies": { "ava": "^1.4.1", "tsd": "^0.7.1", "xo": "^0.24.0" }, "engines": { "node": ">=8" }, "files": [ "index.js", "index.d.ts" ], "homepage": "https://github.com/sindresorhus/string-width#readme", "keywords": [ "string", "character", "unicode", "width", "visual", "column", "columns", "fullwidth", "full-width", "full", "ansi", "escape", "codes", "cli", "command-line", "terminal", "console", "cjk", "chinese", "japanese", "korean", "fixed-width" ], "license": "MIT", "name": "string-width", "repository": { "type": "git", "url": "git+https://github.com/sindresorhus/string-width.git" }, "scripts": { "test": "xo && ava && tsd" }, "version": "4.2.3" } PK ~\""/(/(L@isaacs/cliui/node_modules/string-width-cjs/node_modules/emoji-regex/text.jsnu["use strict"; module.exports = function () { // https://mths.be/emoji return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|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C50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F?|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; }; PK ~\YQ@isaacs/cliui/node_modules/string-width-cjs/node_modules/emoji-regex/package.jsonnu[{ "_from": "emoji-regex@^8.0.0", "_id": "emoji-regex@8.0.0", "_inBundle": false, "_integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", "_location": "/npm/@isaacs/cliui/string-width-cjs/emoji-regex", "_phantomChildren": {}, "_requested": { "type": "range", "registry": true, "raw": "emoji-regex@^8.0.0", "name": "emoji-regex", "escapedName": "emoji-regex", "rawSpec": "^8.0.0", "saveSpec": null, "fetchSpec": "^8.0.0" }, "_requiredBy": [ "/npm/@isaacs/cliui/string-width-cjs" ], "_resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", "_shasum": "e818fd69ce5ccfcb404594f842963bf53164cc37", "_spec": "emoji-regex@^8.0.0", "_where": "C:\\xampp\\htdocs\\emeraltd\\node_modules\\npm\\node_modules\\@isaacs\\cliui\\node_modules\\string-width-cjs", "author": { "name": "Mathias Bynens", "url": "https://mathiasbynens.be/" }, "bugs": { "url": "https://github.com/mathiasbynens/emoji-regex/issues" }, "bundleDependencies": false, "deprecated": false, "description": "A regular expression to match all Emoji-only symbols as per the Unicode Standard.", "devDependencies": { "@babel/cli": "^7.2.3", "@babel/core": "^7.3.4", "@babel/plugin-proposal-unicode-property-regex": "^7.2.0", "@babel/preset-env": "^7.3.4", "mocha": "^6.0.2", "regexgen": "^1.3.0", "unicode-12.0.0": "^0.7.9" }, "files": [ "LICENSE-MIT.txt", "index.js", "index.d.ts", "text.js", "es2015/index.js", "es2015/text.js" ], "homepage": "https://mths.be/emoji-regex", "keywords": [ "unicode", "regex", "regexp", "regular expressions", "code points", "symbols", "characters", "emoji" ], "license": "MIT", "main": "index.js", "name": "emoji-regex", "repository": { "type": "git", "url": "git+https://github.com/mathiasbynens/emoji-regex.git" }, "scripts": { "build": "rm -rf -- es2015; babel src -d .; NODE_ENV=es2015 babel src -d ./es2015; node script/inject-sequences.js", "test": "mocha", "test:watch": "npm run test -- --watch" }, "types": "index.d.ts", "version": "8.0.0" } PK ~\C".(.(M@isaacs/cliui/node_modules/string-width-cjs/node_modules/emoji-regex/index.jsnu["use strict"; module.exports = function () { // https://mths.be/emoji return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83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DC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; }; PK ~\ڌC55T@isaacs/cliui/node_modules/string-width-cjs/node_modules/emoji-regex/LICENSE-MIT.txtnu[Copyright Mathias Bynens Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\a+a+S@isaacs/cliui/node_modules/string-width-cjs/node_modules/emoji-regex/es2015/text.jsnu["use strict"; module.exports = () => { // https://mths.be/emoji return /\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0065}\u{E006E}\u{E0067}|\u{E0073}\u{E0063}\u{E0074}|\u{E0077}\u{E006C}\u{E0073})\u{E007F}|\u{1F468}(?:\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}\u{1F3FB}|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FE}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u2695\u2696\u2708]\uFE0F|[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|(?:\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708])\uFE0F|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|[\u{1F3FB}-\u{1F3FF}])|(?:\u{1F9D1}\u{1F3FB}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F469})\u{1F3FB}|\u{1F9D1}(?:\u{1F3FF}\u200D\u{1F91D}\u200D\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]|\u200D\u{1F91D}\u200D\u{1F9D1})|(?:\u{1F9D1}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FF}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FE}]|(?:\u{1F9D1}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}\u{1F3FC}]|\u{1F469}(?:\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FB}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FC}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|(?:\u{1F9D1}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}-\u{1F3FD}]|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F469}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}]\uFE0F|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u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|\u{1F1FC}[\u{1F1EB}\u{1F1F8}]|\u{1F1FA}[\u{1F1E6}\u{1F1EC}\u{1F1F2}\u{1F1F3}\u{1F1F8}\u{1F1FE}\u{1F1FF}]|\u{1F1EE}[\u{1F1E8}-\u{1F1EA}\u{1F1F1}-\u{1F1F4}\u{1F1F6}-\u{1F1F9}]|\u{1F1EF}[\u{1F1EA}\u{1F1F2}\u{1F1F4}\u{1F1F5}]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]|[\u261D\u270A-\u270D\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F470}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F4AA}\u{1F574}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F936}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}-\u{1F9D5}][\u{1F3FB}-\u{1F3FF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F393}\u{1F3A0}-\u{1F3CA}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F4}\u{1F3F8}-\u{1F43E}\u{1F440}\u{1F442}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F57A}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5FB}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CC}\u{1F6D0}-\u{1F6D2}\u{1F6D5}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]|[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299\u{1F004}\u{1F0CF}\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F321}\u{1F324}-\u{1F393}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}-\u{1F3F0}\u{1F3F3}-\u{1F3F5}\u{1F3F7}-\u{1F4FD}\u{1F4FF}-\u{1F53D}\u{1F549}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F56F}\u{1F570}\u{1F573}-\u{1F57A}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F590}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CB}-\u{1F6D2}\u{1F6D5}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6EB}\u{1F6EC}\u{1F6F0}\u{1F6F3}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]\uFE0F?|[\u261D\u26F9\u270A-\u270D\u{1F385}\u{1F3C2}-\u{1F3C4}\u{1F3C7}\u{1F3CA}-\u{1F3CC}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}-\u{1F478}\u{1F47C}\u{1F481}-\u{1F483}\u{1F485}-\u{1F487}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F574}\u{1F575}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F645}-\u{1F647}\u{1F64B}-\u{1F64F}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91F}\u{1F926}\u{1F930}-\u{1F939}\u{1F93C}-\u{1F93E}\u{1F9B5}\u{1F9B6}\u{1F9B8}\u{1F9B9}\u{1F9BB}\u{1F9CD}-\u{1F9CF}\u{1F9D1}-\u{1F9DD}]/gu; }; PK ~\`+`+T@isaacs/cliui/node_modules/string-width-cjs/node_modules/emoji-regex/es2015/index.jsnu["use strict"; module.exports = () => { // https://mths.be/emoji return /\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0065}\u{E006E}\u{E0067}|\u{E0073}\u{E0063}\u{E0074}|\u{E0077}\u{E006C}\u{E0073})\u{E007F}|\u{1F468}(?:\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}\u{1F3FB}|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FE}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u2695\u2696\u2708]\uFE0F|[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|(?:\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708])\uFE0F|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|[\u{1F3FB}-\u{1F3FF}])|(?:\u{1F9D1}\u{1F3FB}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F469})\u{1F3FB}|\u{1F9D1}(?:\u{1F3FF}\u200D\u{1F91D}\u200D\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]|\u200D\u{1F91D}\u200D\u{1F9D1})|(?:\u{1F9D1}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FF}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FE}]|(?:\u{1F9D1}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}\u{1F3FC}]|\u{1F469}(?:\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FB}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FC}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|(?:\u{1F9D1}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}-\u{1F3FD}]|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F469}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}]\uFE0F|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D6}-\u{1F9DD}](?:[\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\u{1F3F4}\u200D\u2620)\uFE0F|\u{1F469}\u200D\u{1F467}\u200D[\u{1F466}\u{1F467}]|\u{1F3F3}\uFE0F\u200D\u{1F308}|\u{1F415}\u200D\u{1F9BA}|\u{1F469}\u200D\u{1F466}|\u{1F469}\u200D\u{1F467}|\u{1F1FD}\u{1F1F0}|\u{1F1F4}\u{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}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]|[\u261D\u270A-\u270D\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F470}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F4AA}\u{1F574}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F936}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}-\u{1F9D5}][\u{1F3FB}-\u{1F3FF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F393}\u{1F3A0}-\u{1F3CA}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F4}\u{1F3F8}-\u{1F43E}\u{1F440}\u{1F442}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F57A}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5FB}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CC}\u{1F6D0}-\u{1F6D2}\u{1F6D5}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]|[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299\u{1F004}\u{1F0CF}\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F321}\u{1F324}-\u{1F393}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}-\u{1F3F0}\u{1F3F3}-\u{1F3F5}\u{1F3F7}-\u{1F4FD}\u{1F4FF}-\u{1F53D}\u{1F549}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F56F}\u{1F570}\u{1F573}-\u{1F57A}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F590}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CB}-\u{1F6D2}\u{1F6D5}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6EB}\u{1F6EC}\u{1F6F0}\u{1F6F3}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]\uFE0F|[\u261D\u26F9\u270A-\u270D\u{1F385}\u{1F3C2}-\u{1F3C4}\u{1F3C7}\u{1F3CA}-\u{1F3CC}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}-\u{1F478}\u{1F47C}\u{1F481}-\u{1F483}\u{1F485}-\u{1F487}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F574}\u{1F575}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F645}-\u{1F647}\u{1F64B}-\u{1F64F}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91F}\u{1F926}\u{1F930}-\u{1F939}\u{1F93C}-\u{1F93E}\u{1F9B5}\u{1F9B6}\u{1F9B8}\u{1F9B9}\u{1F9BB}\u{1F9CD}-\u{1F9CF}\u{1F9D1}-\u{1F9DD}]/gu; }; PK ~\mms N@isaacs/cliui/node_modules/string-width-cjs/node_modules/emoji-regex/README.mdnu[# emoji-regex [![Build status](https://travis-ci.org/mathiasbynens/emoji-regex.svg?branch=master)](https://travis-ci.org/mathiasbynens/emoji-regex) _emoji-regex_ offers a regular expression to match all emoji symbols (including textual representations of emoji) as per the Unicode Standard. This repository contains a script that generates this regular expression based on [the data from Unicode v12](https://github.com/mathiasbynens/unicode-12.0.0). Because of this, the regular expression can easily be updated whenever new emoji are added to the Unicode standard. ## Installation Via [npm](https://www.npmjs.com/): ```bash npm install emoji-regex ``` In [Node.js](https://nodejs.org/): ```js const emojiRegex = require('emoji-regex'); // Note: because the regular expression has the global flag set, this module // exports a function that returns the regex rather than exporting the regular // expression itself, to make it impossible to (accidentally) mutate the // original regular expression. const text = ` \u{231A}: ⌚ default emoji presentation character (Emoji_Presentation) \u{2194}\u{FE0F}: ↔️ default text presentation character rendered as emoji \u{1F469}: 👩 emoji modifier base (Emoji_Modifier_Base) \u{1F469}\u{1F3FF}: 👩🏿 emoji modifier base followed by a modifier `; const regex = emojiRegex(); let match; while (match = regex.exec(text)) { const emoji = match[0]; console.log(`Matched sequence ${ emoji } — code points: ${ [...emoji].length }`); } ``` Console output: ``` Matched sequence ⌚ — code points: 1 Matched sequence ⌚ — code points: 1 Matched sequence ↔️ — code points: 2 Matched sequence ↔️ — code points: 2 Matched sequence 👩 — code points: 1 Matched sequence 👩 — code points: 1 Matched sequence 👩🏿 — code points: 2 Matched sequence 👩🏿 — code points: 2 ``` To match emoji in their textual representation as well (i.e. emoji that are not `Emoji_Presentation` symbols and that aren’t forced to render as emoji by a variation selector), `require` the other regex: ```js const emojiRegex = require('emoji-regex/text.js'); ``` Additionally, in environments which support ES2015 Unicode escapes, you may `require` ES2015-style versions of the regexes: ```js const emojiRegex = require('emoji-regex/es2015/index.js'); const emojiRegexText = require('emoji-regex/es2015/text.js'); ``` ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License _emoji-regex_ is available under the [MIT](https://mths.be/mit) license. PK ~\cWO@isaacs/cliui/node_modules/string-width-cjs/node_modules/emoji-regex/index.d.tsnu[declare module 'emoji-regex' { function emojiRegex(): RegExp; export default emojiRegex; } declare module 'emoji-regex/text' { function emojiRegex(): RegExp; export default emojiRegex; } declare module 'emoji-regex/es2015' { function emojiRegex(): RegExp; export default emojiRegex; } declare module 'emoji-regex/es2015/text' { function emojiRegex(): RegExp; export default emojiRegex; } PK ~\[#+P@isaacs/cliui/node_modules/string-width-cjs/node_modules/strip-ansi/package.jsonnu[{ "_from": "strip-ansi@^6.0.1", "_id": "strip-ansi@6.0.1", "_inBundle": false, "_integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "_location": "/npm/@isaacs/cliui/string-width-cjs/strip-ansi", "_phantomChildren": {}, "_requested": { "type": "range", "registry": true, "raw": "strip-ansi@^6.0.1", "name": "strip-ansi", "escapedName": "strip-ansi", "rawSpec": "^6.0.1", "saveSpec": null, "fetchSpec": "^6.0.1" }, "_requiredBy": [ "/npm/@isaacs/cliui/string-width-cjs" ], "_resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "_shasum": "9e26c63d30f53443e9489495b2105d37b67a85d9", "_spec": "strip-ansi@^6.0.1", "_where": "C:\\xampp\\htdocs\\emeraltd\\node_modules\\npm\\node_modules\\@isaacs\\cliui\\node_modules\\string-width-cjs", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "bugs": { "url": "https://github.com/chalk/strip-ansi/issues" }, "bundleDependencies": false, "dependencies": { "ansi-regex": "^5.0.1" }, "deprecated": false, "description": "Strip ANSI escape codes from a string", "devDependencies": { "ava": "^2.4.0", "tsd": "^0.10.0", "xo": "^0.25.3" }, "engines": { "node": ">=8" }, "files": [ "index.js", "index.d.ts" ], "homepage": "https://github.com/chalk/strip-ansi#readme", "keywords": [ "strip", "trim", "remove", "ansi", "styles", "color", "colour", "colors", "terminal", "console", "string", "tty", "escape", "formatting", "rgb", "256", "shell", "xterm", "log", "logging", "command-line", "text" ], "license": "MIT", "name": "strip-ansi", "repository": { "type": "git", "url": "git+https://github.com/chalk/strip-ansi.git" }, "scripts": { "test": "xo && ava && tsd" }, "version": "6.0.1" } PK ~\<??M@isaacs/cliui/node_modules/string-width-cjs/node_modules/strip-ansi/readme.mdnu[# strip-ansi [![Build Status](https://travis-ci.org/chalk/strip-ansi.svg?branch=master)](https://travis-ci.org/chalk/strip-ansi) > Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string ## Install ``` $ npm install strip-ansi ``` ## Usage ```js const stripAnsi = require('strip-ansi'); stripAnsi('\u001B[4mUnicorn\u001B[0m'); //=> 'Unicorn' stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'); //=> 'Click' ``` ## strip-ansi for enterprise Available as part of the Tidelift Subscription. The maintainers of strip-ansi and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-strip-ansi?utm_source=npm-strip-ansi&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) ## Related - [strip-ansi-cli](https://github.com/chalk/strip-ansi-cli) - CLI for this module - [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Streaming version of this module - [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes - [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes - [chalk](https://github.com/chalk/chalk) - Terminal string styling done right ## Maintainers - [Sindre Sorhus](https://github.com/sindresorhus) - [Josh Junon](https://github.com/qix-) PK ~\*9L@isaacs/cliui/node_modules/string-width-cjs/node_modules/strip-ansi/index.jsnu['use strict'; const ansiRegex = require('ansi-regex'); module.exports = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; PK ~\E}UUK@isaacs/cliui/node_modules/string-width-cjs/node_modules/strip-ansi/licensenu[MIT License Copyright (c) Sindre Sorhus (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\/qqN@isaacs/cliui/node_modules/string-width-cjs/node_modules/strip-ansi/index.d.tsnu[/** Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string. @example ``` import stripAnsi = require('strip-ansi'); stripAnsi('\u001B[4mUnicorn\u001B[0m'); //=> 'Unicorn' stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'); //=> 'Click' ``` */ declare function stripAnsi(string: string): string; export = stripAnsi; PK ~\; ..P@isaacs/cliui/node_modules/string-width-cjs/node_modules/ansi-regex/package.jsonnu[{ "_from": "ansi-regex@^5.0.1", "_id": "ansi-regex@5.0.1", "_inBundle": false, "_integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "_location": "/npm/@isaacs/cliui/string-width-cjs/ansi-regex", "_phantomChildren": {}, "_requested": { "type": "range", "registry": true, "raw": "ansi-regex@^5.0.1", "name": "ansi-regex", "escapedName": "ansi-regex", "rawSpec": "^5.0.1", "saveSpec": null, "fetchSpec": "^5.0.1" }, "_requiredBy": [ "/npm/@isaacs/cliui/string-width-cjs/strip-ansi" ], "_resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "_shasum": "082cb2c89c9fe8659a311a53bd6a4dc5301db304", "_spec": "ansi-regex@^5.0.1", "_where": "C:\\xampp\\htdocs\\emeraltd\\node_modules\\npm\\node_modules\\@isaacs\\cliui\\node_modules\\string-width-cjs\\node_modules\\strip-ansi", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "bugs": { "url": "https://github.com/chalk/ansi-regex/issues" }, "bundleDependencies": false, "deprecated": false, "description": "Regular expression for matching ANSI escape codes", "devDependencies": { "ava": "^2.4.0", "tsd": "^0.9.0", "xo": "^0.25.3" }, "engines": { "node": ">=8" }, "files": [ "index.js", "index.d.ts" ], "homepage": "https://github.com/chalk/ansi-regex#readme", "keywords": [ "ansi", "styles", "color", "colour", "colors", "terminal", "console", "cli", "string", "tty", "escape", "formatting", "rgb", "256", "shell", "xterm", "command-line", "text", "regex", "regexp", "re", "match", "test", "find", "pattern" ], "license": "MIT", "name": "ansi-regex", "repository": { "type": "git", "url": "git+https://github.com/chalk/ansi-regex.git" }, "scripts": { "test": "xo && ava && tsd", "view-supported": "node fixtures/view-codes.js" }, "version": "5.0.1" } PK ~\DR$  M@isaacs/cliui/node_modules/string-width-cjs/node_modules/ansi-regex/readme.mdnu[# ansi-regex > Regular expression for matching [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) ## Install ``` $ npm install ansi-regex ``` ## Usage ```js const ansiRegex = require('ansi-regex'); ansiRegex().test('\u001B[4mcake\u001B[0m'); //=> true ansiRegex().test('cake'); //=> false '\u001B[4mcake\u001B[0m'.match(ansiRegex()); //=> ['\u001B[4m', '\u001B[0m'] '\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true})); //=> ['\u001B[4m'] '\u001B]8;;https://github.com\u0007click\u001B]8;;\u0007'.match(ansiRegex()); //=> ['\u001B]8;;https://github.com\u0007', '\u001B]8;;\u0007'] ``` ## API ### ansiRegex(options?) Returns a regex for matching ANSI escape codes. #### options Type: `object` ##### onlyFirst Type: `boolean`
Default: `false` *(Matches any ANSI escape codes in a string)* Match only the first ANSI escape. ## FAQ ### Why do you test for codes not in the ECMA 48 standard? Some of the codes we run as a test are codes that we acquired finding various lists of non-standard or manufacturer specific codes. We test for both standard and non-standard codes, as most of them follow the same or similar format and can be safely matched in strings without the risk of removing actual string content. There are a few non-standard control codes that do not follow the traditional format (i.e. they end in numbers) thus forcing us to exclude them from the test because we cannot reliably match them. On the historical side, those ECMA standards were established in the early 90's whereas the VT100, for example, was designed in the mid/late 70's. At that point in time, control codes were still pretty ungoverned and engineers used them for a multitude of things, namely to activate hardware ports that may have been proprietary. Somewhere else you see a similar 'anarchy' of codes is in the x86 architecture for processors; there are a ton of "interrupts" that can mean different things on certain brands of processors, most of which have been phased out. ## Maintainers - [Sindre Sorhus](https://github.com/sindresorhus) - [Josh Junon](https://github.com/qix-) ---
Get professional support for this package with a Tidelift subscription
Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies.
PK ~\^(]^^L@isaacs/cliui/node_modules/string-width-cjs/node_modules/ansi-regex/index.jsnu['use strict'; module.exports = ({onlyFirst = false} = {}) => { const pattern = [ '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' ].join('|'); return new RegExp(pattern, onlyFirst ? undefined : 'g'); }; PK ~\E}UUK@isaacs/cliui/node_modules/string-width-cjs/node_modules/ansi-regex/licensenu[MIT License Copyright (c) Sindre Sorhus (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\06N@isaacs/cliui/node_modules/string-width-cjs/node_modules/ansi-regex/index.d.tsnu[declare namespace ansiRegex { interface Options { /** Match only the first ANSI escape. @default false */ onlyFirst: boolean; } } /** Regular expression for matching ANSI escape codes. @example ``` import ansiRegex = require('ansi-regex'); ansiRegex().test('\u001B[4mcake\u001B[0m'); //=> true ansiRegex().test('cake'); //=> false '\u001B[4mcake\u001B[0m'.match(ansiRegex()); //=> ['\u001B[4m', '\u001B[0m'] '\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true})); //=> ['\u001B[4m'] '\u001B]8;;https://github.com\u0007click\u001B]8;;\u0007'.match(ansiRegex()); //=> ['\u001B]8;;https://github.com\u0007', '\u001B]8;;\u0007'] ``` */ declare function ansiRegex(options?: ansiRegex.Options): RegExp; export = ansiRegex; PK ~\w78tt5@isaacs/cliui/node_modules/string-width-cjs/readme.mdnu[# string-width > Get the visual width of a string - the number of columns required to display it Some Unicode characters are [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) and use double the normal width. [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) are stripped and doesn't affect the width. Useful to be able to measure the actual width of command-line output. ## Install ``` $ npm install string-width ``` ## Usage ```js const stringWidth = require('string-width'); stringWidth('a'); //=> 1 stringWidth('古'); //=> 2 stringWidth('\u001B[1m古\u001B[22m'); //=> 2 ``` ## Related - [string-width-cli](https://github.com/sindresorhus/string-width-cli) - CLI for this module - [string-length](https://github.com/sindresorhus/string-length) - Get the real length of a string - [widest-line](https://github.com/sindresorhus/widest-line) - Get the visual width of the widest line in a string ---
Get professional support for this package with a Tidelift subscription
Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies.
PK ~\Ik4@isaacs/cliui/node_modules/string-width-cjs/index.jsnu['use strict'; const stripAnsi = require('strip-ansi'); const isFullwidthCodePoint = require('is-fullwidth-code-point'); const emojiRegex = require('emoji-regex'); const stringWidth = string => { if (typeof string !== 'string' || string.length === 0) { return 0; } string = stripAnsi(string); if (string.length === 0) { return 0; } string = string.replace(emojiRegex(), ' '); let width = 0; for (let i = 0; i < string.length; i++) { const code = string.codePointAt(i); // Ignore control characters if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { continue; } // Ignore combining characters if (code >= 0x300 && code <= 0x36F) { continue; } // Surrogates if (code > 0xFFFF) { i++; } width += isFullwidthCodePoint(code) ? 2 : 1; } return width; }; module.exports = stringWidth; // TODO: remove this in the next major version module.exports.default = stringWidth; PK ~\E}UU3@isaacs/cliui/node_modules/string-width-cjs/licensenu[MIT License Copyright (c) Sindre Sorhus (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\S6@isaacs/cliui/node_modules/string-width-cjs/index.d.tsnu[declare const stringWidth: { /** Get the visual width of a string - the number of columns required to display it. Some Unicode characters are [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) and use double the normal width. [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) are stripped and doesn't affect the width. @example ``` import stringWidth = require('string-width'); stringWidth('a'); //=> 1 stringWidth('古'); //=> 2 stringWidth('\u001B[1m古\u001B[22m'); //=> 2 ``` */ (string: string): number; // TODO: remove this in the next major version, refactor the whole definition to: // declare function stringWidth(string: string): number; // export = stringWidth; default: typeof stringWidth; } export = stringWidth; PK ~\wj4@isaacs/cliui/node_modules/string-width/package.jsonnu[{ "_id": "string-width@5.1.2", "_inBundle": true, "_location": "/npm/@isaacs/cliui/string-width", "_phantomChildren": {}, "_requiredBy": [ "/npm/@isaacs/cliui" ], "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "bugs": { "url": "https://github.com/sindresorhus/string-width/issues" }, "dependencies": { "eastasianwidth": "^0.2.0", "emoji-regex": "^9.2.2", "strip-ansi": "^7.0.1" }, "description": "Get the visual width of a string - the number of columns required to display it", "devDependencies": { "ava": "^3.15.0", "tsd": "^0.14.0", "xo": "^0.38.2" }, "engines": { "node": ">=12" }, "exports": "./index.js", "files": [ "index.js", "index.d.ts" ], "funding": "https://github.com/sponsors/sindresorhus", "homepage": "https://github.com/sindresorhus/string-width#readme", "keywords": [ "string", "character", "unicode", "width", "visual", "column", "columns", "fullwidth", "full-width", "full", "ansi", "escape", "codes", "cli", "command-line", "terminal", "console", "cjk", "chinese", "japanese", "korean", "fixed-width" ], "license": "MIT", "name": "string-width", "repository": { "type": "git", "url": "git+https://github.com/sindresorhus/string-width.git" }, "scripts": { "test": "xo && ava && tsd" }, "type": "module", "version": "5.1.2" } PK ~\"((0@isaacs/cliui/node_modules/string-width/index.jsnu[import stripAnsi from 'strip-ansi'; import eastAsianWidth from 'eastasianwidth'; import emojiRegex from 'emoji-regex'; export default function stringWidth(string, options = {}) { if (typeof string !== 'string' || string.length === 0) { return 0; } options = { ambiguousIsNarrow: true, ...options }; string = stripAnsi(string); if (string.length === 0) { return 0; } string = string.replace(emojiRegex(), ' '); const ambiguousCharacterWidth = options.ambiguousIsNarrow ? 1 : 2; let width = 0; for (const character of string) { const codePoint = character.codePointAt(0); // Ignore control characters if (codePoint <= 0x1F || (codePoint >= 0x7F && codePoint <= 0x9F)) { continue; } // Ignore combining characters if (codePoint >= 0x300 && codePoint <= 0x36F) { continue; } const code = eastAsianWidth.eastAsianWidth(character); switch (code) { case 'F': case 'W': width += 2; break; case 'A': width += ambiguousCharacterWidth; break; default: width += 1; } } return width; } PK ~\i]]/@isaacs/cliui/node_modules/string-width/licensenu[MIT License Copyright (c) Sindre Sorhus (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\z2@isaacs/cliui/node_modules/strip-ansi/package.jsonnu[{ "_id": "strip-ansi@7.1.0", "_inBundle": true, "_location": "/npm/@isaacs/cliui/strip-ansi", "_phantomChildren": {}, "_requiredBy": [ "/npm/@isaacs/cliui", "/npm/@isaacs/cliui/string-width" ], "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "bugs": { "url": "https://github.com/chalk/strip-ansi/issues" }, "dependencies": { "ansi-regex": "^6.0.1" }, "description": "Strip ANSI escape codes from a string", "devDependencies": { "ava": "^3.15.0", "tsd": "^0.17.0", "xo": "^0.44.0" }, "engines": { "node": ">=12" }, "exports": "./index.js", "files": [ "index.js", "index.d.ts" ], "funding": "https://github.com/chalk/strip-ansi?sponsor=1", "homepage": "https://github.com/chalk/strip-ansi#readme", "keywords": [ "strip", "trim", "remove", "ansi", "styles", "color", "colour", "colors", "terminal", "console", "string", "tty", "escape", "formatting", "rgb", "256", "shell", "xterm", "log", "logging", "command-line", "text" ], "license": "MIT", "name": "strip-ansi", "repository": { "type": "git", "url": "git+https://github.com/chalk/strip-ansi.git" }, "scripts": { "test": "xo && ava && tsd" }, "type": "module", "version": "7.1.0" } PK ~\2h.@isaacs/cliui/node_modules/strip-ansi/index.jsnu[import ansiRegex from 'ansi-regex'; const regex = ansiRegex(); export default function stripAnsi(string) { if (typeof string !== 'string') { throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``); } // Even though the regex is global, we don't need to reset the `.lastIndex` // because unlike `.exec()` and `.test()`, `.replace()` does it automatically // and doing it manually has a performance penalty. return string.replace(regex, ''); } PK ~\i]]-@isaacs/cliui/node_modules/strip-ansi/licensenu[MIT License Copyright (c) Sindre Sorhus (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\G6@isaacs/cliui/node_modules/strip-ansi-cjs/package.jsonnu[{ "_from": "strip-ansi-cjs@npm:strip-ansi@^6.0.1", "_id": "strip-ansi@6.0.1", "_inBundle": false, "_integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "_location": "/npm/@isaacs/cliui/strip-ansi-cjs", "_phantomChildren": {}, "_requested": { "type": "alias", "registry": true, "raw": "strip-ansi-cjs@npm:strip-ansi@^6.0.1", "name": "strip-ansi-cjs", "escapedName": "strip-ansi-cjs", "rawSpec": "npm:strip-ansi@^6.0.1", "saveSpec": null, "fetchSpec": null, "subSpec": { "type": "range", "registry": true, "raw": "strip-ansi@^6.0.1", "name": "strip-ansi", "escapedName": "strip-ansi", "rawSpec": "^6.0.1", "saveSpec": null, "fetchSpec": "^6.0.1" } }, "_requiredBy": [ "/npm/@isaacs/cliui" ], "_resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "_shasum": "9e26c63d30f53443e9489495b2105d37b67a85d9", "_spec": "strip-ansi-cjs@npm:strip-ansi@^6.0.1", "_where": "C:\\xampp\\htdocs\\emeraltd\\node_modules\\npm\\node_modules\\@isaacs\\cliui", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "bugs": { "url": "https://github.com/chalk/strip-ansi/issues" }, "bundleDependencies": false, "dependencies": { "ansi-regex": "^5.0.1" }, "deprecated": false, "description": "Strip ANSI escape codes from a string", "devDependencies": { "ava": "^2.4.0", "tsd": "^0.10.0", "xo": "^0.25.3" }, "engines": { "node": ">=8" }, "files": [ "index.js", "index.d.ts" ], "homepage": "https://github.com/chalk/strip-ansi#readme", "keywords": [ "strip", "trim", "remove", "ansi", "styles", "color", "colour", "colors", "terminal", "console", "string", "tty", "escape", "formatting", "rgb", "256", "shell", "xterm", "log", "logging", "command-line", "text" ], "license": "MIT", "name": "strip-ansi", "repository": { "type": "git", "url": "git+https://github.com/chalk/strip-ansi.git" }, "scripts": { "test": "xo && ava && tsd" }, "version": "6.0.1" } PK ~\N@isaacs/cliui/node_modules/strip-ansi-cjs/node_modules/ansi-regex/package.jsonnu[{ "_from": "ansi-regex@^5.0.1", "_id": "ansi-regex@5.0.1", "_inBundle": false, "_integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "_location": "/npm/@isaacs/cliui/strip-ansi-cjs/ansi-regex", "_phantomChildren": {}, "_requested": { "type": "range", "registry": true, "raw": "ansi-regex@^5.0.1", "name": "ansi-regex", "escapedName": "ansi-regex", "rawSpec": "^5.0.1", "saveSpec": null, "fetchSpec": "^5.0.1" }, "_requiredBy": [ "/npm/@isaacs/cliui/strip-ansi-cjs" ], "_resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "_shasum": "082cb2c89c9fe8659a311a53bd6a4dc5301db304", "_spec": "ansi-regex@^5.0.1", "_where": "C:\\xampp\\htdocs\\emeraltd\\node_modules\\npm\\node_modules\\@isaacs\\cliui\\node_modules\\strip-ansi-cjs", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "bugs": { "url": "https://github.com/chalk/ansi-regex/issues" }, "bundleDependencies": false, "deprecated": false, "description": "Regular expression for matching ANSI escape codes", "devDependencies": { "ava": "^2.4.0", "tsd": "^0.9.0", "xo": "^0.25.3" }, "engines": { "node": ">=8" }, "files": [ "index.js", "index.d.ts" ], "homepage": "https://github.com/chalk/ansi-regex#readme", "keywords": [ "ansi", "styles", "color", "colour", "colors", "terminal", "console", "cli", "string", "tty", "escape", "formatting", "rgb", "256", "shell", "xterm", "command-line", "text", "regex", "regexp", "re", "match", "test", "find", "pattern" ], "license": "MIT", "name": "ansi-regex", "repository": { "type": "git", "url": "git+https://github.com/chalk/ansi-regex.git" }, "scripts": { "test": "xo && ava && tsd", "view-supported": "node fixtures/view-codes.js" }, "version": "5.0.1" } PK ~\DR$  K@isaacs/cliui/node_modules/strip-ansi-cjs/node_modules/ansi-regex/readme.mdnu[# ansi-regex > Regular expression for matching [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) ## Install ``` $ npm install ansi-regex ``` ## Usage ```js const ansiRegex = require('ansi-regex'); ansiRegex().test('\u001B[4mcake\u001B[0m'); //=> true ansiRegex().test('cake'); //=> false '\u001B[4mcake\u001B[0m'.match(ansiRegex()); //=> ['\u001B[4m', '\u001B[0m'] '\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true})); //=> ['\u001B[4m'] '\u001B]8;;https://github.com\u0007click\u001B]8;;\u0007'.match(ansiRegex()); //=> ['\u001B]8;;https://github.com\u0007', '\u001B]8;;\u0007'] ``` ## API ### ansiRegex(options?) Returns a regex for matching ANSI escape codes. #### options Type: `object` ##### onlyFirst Type: `boolean`
Default: `false` *(Matches any ANSI escape codes in a string)* Match only the first ANSI escape. ## FAQ ### Why do you test for codes not in the ECMA 48 standard? Some of the codes we run as a test are codes that we acquired finding various lists of non-standard or manufacturer specific codes. We test for both standard and non-standard codes, as most of them follow the same or similar format and can be safely matched in strings without the risk of removing actual string content. There are a few non-standard control codes that do not follow the traditional format (i.e. they end in numbers) thus forcing us to exclude them from the test because we cannot reliably match them. On the historical side, those ECMA standards were established in the early 90's whereas the VT100, for example, was designed in the mid/late 70's. At that point in time, control codes were still pretty ungoverned and engineers used them for a multitude of things, namely to activate hardware ports that may have been proprietary. Somewhere else you see a similar 'anarchy' of codes is in the x86 architecture for processors; there are a ton of "interrupts" that can mean different things on certain brands of processors, most of which have been phased out. ## Maintainers - [Sindre Sorhus](https://github.com/sindresorhus) - [Josh Junon](https://github.com/qix-) ---
Get professional support for this package with a Tidelift subscription
Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies.
PK ~\^(]^^J@isaacs/cliui/node_modules/strip-ansi-cjs/node_modules/ansi-regex/index.jsnu['use strict'; module.exports = ({onlyFirst = false} = {}) => { const pattern = [ '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' ].join('|'); return new RegExp(pattern, onlyFirst ? undefined : 'g'); }; PK ~\E}UUI@isaacs/cliui/node_modules/strip-ansi-cjs/node_modules/ansi-regex/licensenu[MIT License Copyright (c) Sindre Sorhus (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\06L@isaacs/cliui/node_modules/strip-ansi-cjs/node_modules/ansi-regex/index.d.tsnu[declare namespace ansiRegex { interface Options { /** Match only the first ANSI escape. @default false */ onlyFirst: boolean; } } /** Regular expression for matching ANSI escape codes. @example ``` import ansiRegex = require('ansi-regex'); ansiRegex().test('\u001B[4mcake\u001B[0m'); //=> true ansiRegex().test('cake'); //=> false '\u001B[4mcake\u001B[0m'.match(ansiRegex()); //=> ['\u001B[4m', '\u001B[0m'] '\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true})); //=> ['\u001B[4m'] '\u001B]8;;https://github.com\u0007click\u001B]8;;\u0007'.match(ansiRegex()); //=> ['\u001B]8;;https://github.com\u0007', '\u001B]8;;\u0007'] ``` */ declare function ansiRegex(options?: ansiRegex.Options): RegExp; export = ansiRegex; PK ~\<??3@isaacs/cliui/node_modules/strip-ansi-cjs/readme.mdnu[# strip-ansi [![Build Status](https://travis-ci.org/chalk/strip-ansi.svg?branch=master)](https://travis-ci.org/chalk/strip-ansi) > Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string ## Install ``` $ npm install strip-ansi ``` ## Usage ```js const stripAnsi = require('strip-ansi'); stripAnsi('\u001B[4mUnicorn\u001B[0m'); //=> 'Unicorn' stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'); //=> 'Click' ``` ## strip-ansi for enterprise Available as part of the Tidelift Subscription. The maintainers of strip-ansi and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-strip-ansi?utm_source=npm-strip-ansi&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) ## Related - [strip-ansi-cli](https://github.com/chalk/strip-ansi-cli) - CLI for this module - [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Streaming version of this module - [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes - [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes - [chalk](https://github.com/chalk/chalk) - Terminal string styling done right ## Maintainers - [Sindre Sorhus](https://github.com/sindresorhus) - [Josh Junon](https://github.com/qix-) PK ~\*92@isaacs/cliui/node_modules/strip-ansi-cjs/index.jsnu['use strict'; const ansiRegex = require('ansi-regex'); module.exports = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; PK ~\E}UU1@isaacs/cliui/node_modules/strip-ansi-cjs/licensenu[MIT License Copyright (c) Sindre Sorhus (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\/qq4@isaacs/cliui/node_modules/strip-ansi-cjs/index.d.tsnu[/** Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string. @example ``` import stripAnsi = require('strip-ansi'); stripAnsi('\u001B[4mUnicorn\u001B[0m'); //=> 'Unicorn' stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'); //=> 'Click' ``` */ declare function stripAnsi(string: string): string; export = stripAnsi; PK ~\ #2@isaacs/cliui/node_modules/ansi-regex/package.jsonnu[{ "_id": "ansi-regex@6.0.1", "_inBundle": true, "_location": "/npm/@isaacs/cliui/ansi-regex", "_phantomChildren": {}, "_requiredBy": [ "/npm/@isaacs/cliui/strip-ansi" ], "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "bugs": { "url": "https://github.com/chalk/ansi-regex/issues" }, "description": "Regular expression for matching ANSI escape codes", "devDependencies": { "ava": "^3.15.0", "tsd": "^0.14.0", "xo": "^0.38.2" }, "engines": { "node": ">=12" }, "exports": "./index.js", "files": [ "index.js", "index.d.ts" ], "funding": "https://github.com/chalk/ansi-regex?sponsor=1", "homepage": "https://github.com/chalk/ansi-regex#readme", "keywords": [ "ansi", "styles", "color", "colour", "colors", "terminal", "console", "cli", "string", "tty", "escape", "formatting", "rgb", "256", "shell", "xterm", "command-line", "text", "regex", "regexp", "re", "match", "test", "find", "pattern" ], "license": "MIT", "name": "ansi-regex", "repository": { "type": "git", "url": "git+https://github.com/chalk/ansi-regex.git" }, "scripts": { "test": "xo && ava && tsd", "view-supported": "node fixtures/view-codes.js" }, "type": "module", "version": "6.0.1" } PK ~\KE^^.@isaacs/cliui/node_modules/ansi-regex/index.jsnu[export default function ansiRegex({onlyFirst = false} = {}) { const pattern = [ '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' ].join('|'); return new RegExp(pattern, onlyFirst ? undefined : 'g'); } PK ~\i]]-@isaacs/cliui/node_modules/ansi-regex/licensenu[MIT License Copyright (c) Sindre Sorhus (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\xȔB@isaacs/cliui/build/index.d.ctsnu[interface UIOptions { width: number; wrap?: boolean; rows?: string[]; } interface Column { text: string; width?: number; align?: "right" | "left" | "center"; padding: number[]; border?: boolean; } interface ColumnArray extends Array { span: boolean; } interface Line { hidden?: boolean; text: string; span?: boolean; } declare class UI { width: number; wrap: boolean; rows: ColumnArray[]; constructor(opts: UIOptions); span(...args: ColumnArray): void; resetOutput(): void; div(...args: (Column | string)[]): ColumnArray; private shouldApplyLayoutDSL; private applyLayoutDSL; private colFromString; private measurePadding; toString(): string; rowToString(row: ColumnArray, lines: Line[]): Line[]; // if the full 'source' can render in // the target line, do so. private renderInline; private rasterize; private negatePadding; private columnWidths; } declare function ui(opts: UIOptions): UI; export { ui as default }; PK ~\Ќut't' @isaacs/cliui/build/lib/index.jsnu['use strict'; const align = { right: alignRight, center: alignCenter }; const top = 0; const right = 1; const bottom = 2; const left = 3; export class UI { constructor(opts) { var _a; this.width = opts.width; /* c8 ignore start */ this.wrap = (_a = opts.wrap) !== null && _a !== void 0 ? _a : true; /* c8 ignore stop */ this.rows = []; } span(...args) { const cols = this.div(...args); cols.span = true; } resetOutput() { this.rows = []; } div(...args) { if (args.length === 0) { this.div(''); } if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === 'string') { return this.applyLayoutDSL(args[0]); } const cols = args.map(arg => { if (typeof arg === 'string') { return this.colFromString(arg); } return arg; }); this.rows.push(cols); return cols; } shouldApplyLayoutDSL(...args) { return args.length === 1 && typeof args[0] === 'string' && /[\t\n]/.test(args[0]); } applyLayoutDSL(str) { const rows = str.split('\n').map(row => row.split('\t')); let leftColumnWidth = 0; // simple heuristic for layout, make sure the // second column lines up along the left-hand. // don't allow the first column to take up more // than 50% of the screen. rows.forEach(columns => { if (columns.length > 1 && mixin.stringWidth(columns[0]) > leftColumnWidth) { leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin.stringWidth(columns[0])); } }); // generate a table: // replacing ' ' with padding calculations. // using the algorithmically generated width. rows.forEach(columns => { this.div(...columns.map((r, i) => { return { text: r.trim(), padding: this.measurePadding(r), width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined }; })); }); return this.rows[this.rows.length - 1]; } colFromString(text) { return { text, padding: this.measurePadding(text) }; } measurePadding(str) { // measure padding without ansi escape codes const noAnsi = mixin.stripAnsi(str); return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length]; } toString() { const lines = []; this.rows.forEach(row => { this.rowToString(row, lines); }); // don't display any lines with the // hidden flag set. return lines .filter(line => !line.hidden) .map(line => line.text) .join('\n'); } rowToString(row, lines) { this.rasterize(row).forEach((rrow, r) => { let str = ''; rrow.forEach((col, c) => { const { width } = row[c]; // the width with padding. const wrapWidth = this.negatePadding(row[c]); // the width without padding. let ts = col; // temporary string used during alignment/padding. if (wrapWidth > mixin.stringWidth(col)) { ts += ' '.repeat(wrapWidth - mixin.stringWidth(col)); } // align the string within its column. if (row[c].align && row[c].align !== 'left' && this.wrap) { const fn = align[row[c].align]; ts = fn(ts, wrapWidth); if (mixin.stringWidth(ts) < wrapWidth) { /* c8 ignore start */ const w = width || 0; /* c8 ignore stop */ ts += ' '.repeat(w - mixin.stringWidth(ts) - 1); } } // apply border and padding to string. const padding = row[c].padding || [0, 0, 0, 0]; if (padding[left]) { str += ' '.repeat(padding[left]); } str += addBorder(row[c], ts, '| '); str += ts; str += addBorder(row[c], ts, ' |'); if (padding[right]) { str += ' '.repeat(padding[right]); } // if prior row is span, try to render the // current row on the prior line. if (r === 0 && lines.length > 0) { str = this.renderInline(str, lines[lines.length - 1]); } }); // remove trailing whitespace. lines.push({ text: str.replace(/ +$/, ''), span: row.span }); }); return lines; } // if the full 'source' can render in // the target line, do so. renderInline(source, previousLine) { const match = source.match(/^ */); /* c8 ignore start */ const leadingWhitespace = match ? match[0].length : 0; /* c8 ignore stop */ const target = previousLine.text; const targetTextWidth = mixin.stringWidth(target.trimEnd()); if (!previousLine.span) { return source; } // if we're not applying wrapping logic, // just always append to the span. if (!this.wrap) { previousLine.hidden = true; return target + source; } if (leadingWhitespace < targetTextWidth) { return source; } previousLine.hidden = true; return target.trimEnd() + ' '.repeat(leadingWhitespace - targetTextWidth) + source.trimStart(); } rasterize(row) { const rrows = []; const widths = this.columnWidths(row); let wrapped; // word wrap all columns, and create // a data-structure that is easy to rasterize. row.forEach((col, c) => { // leave room for left and right padding. col.width = widths[c]; if (this.wrap) { wrapped = mixin.wrap(col.text, this.negatePadding(col), { hard: true }).split('\n'); } else { wrapped = col.text.split('\n'); } if (col.border) { wrapped.unshift('.' + '-'.repeat(this.negatePadding(col) + 2) + '.'); wrapped.push("'" + '-'.repeat(this.negatePadding(col) + 2) + "'"); } // add top and bottom padding. if (col.padding) { wrapped.unshift(...new Array(col.padding[top] || 0).fill('')); wrapped.push(...new Array(col.padding[bottom] || 0).fill('')); } wrapped.forEach((str, r) => { if (!rrows[r]) { rrows.push([]); } const rrow = rrows[r]; for (let i = 0; i < c; i++) { if (rrow[i] === undefined) { rrow.push(''); } } rrow.push(str); }); }); return rrows; } negatePadding(col) { /* c8 ignore start */ let wrapWidth = col.width || 0; /* c8 ignore stop */ if (col.padding) { wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0); } if (col.border) { wrapWidth -= 4; } return wrapWidth; } columnWidths(row) { if (!this.wrap) { return row.map(col => { return col.width || mixin.stringWidth(col.text); }); } let unset = row.length; let remainingWidth = this.width; // column widths can be set in config. const widths = row.map(col => { if (col.width) { unset--; remainingWidth -= col.width; return col.width; } return undefined; }); // any unset widths should be calculated. /* c8 ignore start */ const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0; /* c8 ignore stop */ return widths.map((w, i) => { if (w === undefined) { return Math.max(unsetWidth, _minWidth(row[i])); } return w; }); } } function addBorder(col, ts, style) { if (col.border) { if (/[.']-+[.']/.test(ts)) { return ''; } if (ts.trim().length !== 0) { return style; } return ' '; } return ''; } // calculates the minimum width of // a column, based on padding preferences. function _minWidth(col) { const padding = col.padding || []; const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0); if (col.border) { return minWidth + 4; } return minWidth; } function getWindowWidth() { /* c8 ignore start */ if (typeof process === 'object' && process.stdout && process.stdout.columns) { return process.stdout.columns; } return 80; } /* c8 ignore stop */ function alignRight(str, width) { str = str.trim(); const strWidth = mixin.stringWidth(str); if (strWidth < width) { return ' '.repeat(width - strWidth) + str; } return str; } function alignCenter(str, width) { str = str.trim(); const strWidth = mixin.stringWidth(str); /* c8 ignore start */ if (strWidth >= width) { return str; } /* c8 ignore stop */ return ' '.repeat((width - strWidth) >> 1) + str; } let mixin; export function cliui(opts, _mixin) { mixin = _mixin; return new UI({ /* c8 ignore start */ width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(), wrap: opts === null || opts === void 0 ? void 0 : opts.wrap /* c8 ignore stop */ }); } PK ~\^Zp((@isaacs/cliui/build/index.cjsnu['use strict'; const align = { right: alignRight, center: alignCenter }; const top = 0; const right = 1; const bottom = 2; const left = 3; class UI { constructor(opts) { var _a; this.width = opts.width; /* c8 ignore start */ this.wrap = (_a = opts.wrap) !== null && _a !== void 0 ? _a : true; /* c8 ignore stop */ this.rows = []; } span(...args) { const cols = this.div(...args); cols.span = true; } resetOutput() { this.rows = []; } div(...args) { if (args.length === 0) { this.div(''); } if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === 'string') { return this.applyLayoutDSL(args[0]); } const cols = args.map(arg => { if (typeof arg === 'string') { return this.colFromString(arg); } return arg; }); this.rows.push(cols); return cols; } shouldApplyLayoutDSL(...args) { return args.length === 1 && typeof args[0] === 'string' && /[\t\n]/.test(args[0]); } applyLayoutDSL(str) { const rows = str.split('\n').map(row => row.split('\t')); let leftColumnWidth = 0; // simple heuristic for layout, make sure the // second column lines up along the left-hand. // don't allow the first column to take up more // than 50% of the screen. rows.forEach(columns => { if (columns.length > 1 && mixin.stringWidth(columns[0]) > leftColumnWidth) { leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin.stringWidth(columns[0])); } }); // generate a table: // replacing ' ' with padding calculations. // using the algorithmically generated width. rows.forEach(columns => { this.div(...columns.map((r, i) => { return { text: r.trim(), padding: this.measurePadding(r), width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined }; })); }); return this.rows[this.rows.length - 1]; } colFromString(text) { return { text, padding: this.measurePadding(text) }; } measurePadding(str) { // measure padding without ansi escape codes const noAnsi = mixin.stripAnsi(str); return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length]; } toString() { const lines = []; this.rows.forEach(row => { this.rowToString(row, lines); }); // don't display any lines with the // hidden flag set. return lines .filter(line => !line.hidden) .map(line => line.text) .join('\n'); } rowToString(row, lines) { this.rasterize(row).forEach((rrow, r) => { let str = ''; rrow.forEach((col, c) => { const { width } = row[c]; // the width with padding. const wrapWidth = this.negatePadding(row[c]); // the width without padding. let ts = col; // temporary string used during alignment/padding. if (wrapWidth > mixin.stringWidth(col)) { ts += ' '.repeat(wrapWidth - mixin.stringWidth(col)); } // align the string within its column. if (row[c].align && row[c].align !== 'left' && this.wrap) { const fn = align[row[c].align]; ts = fn(ts, wrapWidth); if (mixin.stringWidth(ts) < wrapWidth) { /* c8 ignore start */ const w = width || 0; /* c8 ignore stop */ ts += ' '.repeat(w - mixin.stringWidth(ts) - 1); } } // apply border and padding to string. const padding = row[c].padding || [0, 0, 0, 0]; if (padding[left]) { str += ' '.repeat(padding[left]); } str += addBorder(row[c], ts, '| '); str += ts; str += addBorder(row[c], ts, ' |'); if (padding[right]) { str += ' '.repeat(padding[right]); } // if prior row is span, try to render the // current row on the prior line. if (r === 0 && lines.length > 0) { str = this.renderInline(str, lines[lines.length - 1]); } }); // remove trailing whitespace. lines.push({ text: str.replace(/ +$/, ''), span: row.span }); }); return lines; } // if the full 'source' can render in // the target line, do so. renderInline(source, previousLine) { const match = source.match(/^ */); /* c8 ignore start */ const leadingWhitespace = match ? match[0].length : 0; /* c8 ignore stop */ const target = previousLine.text; const targetTextWidth = mixin.stringWidth(target.trimEnd()); if (!previousLine.span) { return source; } // if we're not applying wrapping logic, // just always append to the span. if (!this.wrap) { previousLine.hidden = true; return target + source; } if (leadingWhitespace < targetTextWidth) { return source; } previousLine.hidden = true; return target.trimEnd() + ' '.repeat(leadingWhitespace - targetTextWidth) + source.trimStart(); } rasterize(row) { const rrows = []; const widths = this.columnWidths(row); let wrapped; // word wrap all columns, and create // a data-structure that is easy to rasterize. row.forEach((col, c) => { // leave room for left and right padding. col.width = widths[c]; if (this.wrap) { wrapped = mixin.wrap(col.text, this.negatePadding(col), { hard: true }).split('\n'); } else { wrapped = col.text.split('\n'); } if (col.border) { wrapped.unshift('.' + '-'.repeat(this.negatePadding(col) + 2) + '.'); wrapped.push("'" + '-'.repeat(this.negatePadding(col) + 2) + "'"); } // add top and bottom padding. if (col.padding) { wrapped.unshift(...new Array(col.padding[top] || 0).fill('')); wrapped.push(...new Array(col.padding[bottom] || 0).fill('')); } wrapped.forEach((str, r) => { if (!rrows[r]) { rrows.push([]); } const rrow = rrows[r]; for (let i = 0; i < c; i++) { if (rrow[i] === undefined) { rrow.push(''); } } rrow.push(str); }); }); return rrows; } negatePadding(col) { /* c8 ignore start */ let wrapWidth = col.width || 0; /* c8 ignore stop */ if (col.padding) { wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0); } if (col.border) { wrapWidth -= 4; } return wrapWidth; } columnWidths(row) { if (!this.wrap) { return row.map(col => { return col.width || mixin.stringWidth(col.text); }); } let unset = row.length; let remainingWidth = this.width; // column widths can be set in config. const widths = row.map(col => { if (col.width) { unset--; remainingWidth -= col.width; return col.width; } return undefined; }); // any unset widths should be calculated. /* c8 ignore start */ const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0; /* c8 ignore stop */ return widths.map((w, i) => { if (w === undefined) { return Math.max(unsetWidth, _minWidth(row[i])); } return w; }); } } function addBorder(col, ts, style) { if (col.border) { if (/[.']-+[.']/.test(ts)) { return ''; } if (ts.trim().length !== 0) { return style; } return ' '; } return ''; } // calculates the minimum width of // a column, based on padding preferences. function _minWidth(col) { const padding = col.padding || []; const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0); if (col.border) { return minWidth + 4; } return minWidth; } function getWindowWidth() { /* c8 ignore start */ if (typeof process === 'object' && process.stdout && process.stdout.columns) { return process.stdout.columns; } return 80; } /* c8 ignore stop */ function alignRight(str, width) { str = str.trim(); const strWidth = mixin.stringWidth(str); if (strWidth < width) { return ' '.repeat(width - strWidth) + str; } return str; } function alignCenter(str, width) { str = str.trim(); const strWidth = mixin.stringWidth(str); /* c8 ignore start */ if (strWidth >= width) { return str; } /* c8 ignore stop */ return ' '.repeat((width - strWidth) >> 1) + str; } let mixin; function cliui(opts, _mixin) { mixin = _mixin; return new UI({ /* c8 ignore start */ width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(), wrap: opts === null || opts === void 0 ? void 0 : opts.wrap /* c8 ignore stop */ }); } // Bootstrap cliui with CommonJS dependencies: const stringWidth = require('string-width-cjs'); const stripAnsi = require('strip-ansi-cjs'); const wrap = require('wrap-ansi-cjs'); function ui(opts) { return cliui(opts, { stringWidth, stripAnsi, wrap }); } module.exports = ui; PK ~\De++@isaacs/cliui/index.mjsnu[// Bootstrap cliui with ESM dependencies: import { cliui } from './build/lib/index.js' import stringWidth from 'string-width' import stripAnsi from 'strip-ansi' import wrap from 'wrap-ansi' export default function ui (opts) { return cliui(opts, { stringWidth, stripAnsi, wrap }) } PK ~\.@isaacs/cliui/LICENSE.txtnu[Copyright (c) 2015, Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\/Ynpm-bundled/package.jsonnu[{ "_id": "npm-bundled@3.0.1", "_inBundle": true, "_location": "/npm/npm-bundled", "_phantomChildren": {}, "_requiredBy": [ "/npm/@npmcli/installed-package-contents" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/npm-bundled/issues" }, "dependencies": { "npm-normalize-package-bin": "^3.0.0" }, "description": "list things in node_modules that are bundledDependencies, or transitive dependencies thereof", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.22.0", "mutate-fs": "^2.1.1", "tap": "^16.3.0" }, "engines": { "node": "^14.17.0 || ^16.13.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/npm-bundled#readme", "license": "ISC", "main": "lib/index.js", "name": "npm-bundled", "repository": { "type": "git", "url": "git+https://github.com/npm/npm-bundled.git" }, "scripts": { "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.22.0", "publish": true }, "version": "3.0.1" } PK ~\kknpm-bundled/lib/index.jsnu['use strict' // walk the tree of deps starting from the top level list of bundled deps // Any deps at the top level that are depended on by a bundled dep that // does not have that dep in its own node_modules folder are considered // bundled deps as well. This list of names can be passed to npm-packlist // as the "bundled" argument. Additionally, packageJsonCache is shared so // packlist doesn't have to re-read files already consumed in this pass const fs = require('fs') const path = require('path') const EE = require('events').EventEmitter // we don't care about the package bins, but we share a pj cache // with other modules that DO care about it, so keep it nice. const normalizePackageBin = require('npm-normalize-package-bin') class BundleWalker extends EE { constructor (opt) { opt = opt || {} super(opt) this.path = path.resolve(opt.path || process.cwd()) this.parent = opt.parent || null if (this.parent) { this.result = this.parent.result // only collect results in node_modules folders at the top level // since the node_modules in a bundled dep is included always if (!this.parent.parent) { const base = path.basename(this.path) const scope = path.basename(path.dirname(this.path)) this.result.add(/^@/.test(scope) ? scope + '/' + base : base) } this.root = this.parent.root this.packageJsonCache = this.parent.packageJsonCache } else { this.result = new Set() this.root = this.path this.packageJsonCache = opt.packageJsonCache || new Map() } this.seen = new Set() this.didDone = false this.children = 0 this.node_modules = [] this.package = null this.bundle = null } addListener (ev, fn) { return this.on(ev, fn) } on (ev, fn) { const ret = super.on(ev, fn) if (ev === 'done' && this.didDone) { this.emit('done', this.result) } return ret } done () { if (!this.didDone) { this.didDone = true if (!this.parent) { const res = Array.from(this.result) this.result = res this.emit('done', res) } else { this.emit('done') } } } start () { const pj = path.resolve(this.path, 'package.json') if (this.packageJsonCache.has(pj)) { this.onPackage(this.packageJsonCache.get(pj)) } else { this.readPackageJson(pj) } return this } readPackageJson (pj) { fs.readFile(pj, (er, data) => er ? this.done() : this.onPackageJson(pj, data)) } onPackageJson (pj, data) { try { this.package = normalizePackageBin(JSON.parse(data + '')) } catch (er) { return this.done() } this.packageJsonCache.set(pj, this.package) this.onPackage(this.package) } allDepsBundled (pkg) { return Object.keys(pkg.dependencies || {}).concat( Object.keys(pkg.optionalDependencies || {})) } onPackage (pkg) { // all deps are bundled if we got here as a child. // otherwise, only bundle bundledDeps // Get a unique-ified array with a short-lived Set const bdRaw = this.parent ? this.allDepsBundled(pkg) : pkg.bundleDependencies || pkg.bundledDependencies || [] const bd = Array.from(new Set( Array.isArray(bdRaw) ? bdRaw : bdRaw === true ? this.allDepsBundled(pkg) : Object.keys(bdRaw))) if (!bd.length) { return this.done() } this.bundle = bd this.readModules() } readModules () { readdirNodeModules(this.path + '/node_modules', (er, nm) => er ? this.onReaddir([]) : this.onReaddir(nm)) } onReaddir (nm) { // keep track of what we have, in case children need it this.node_modules = nm this.bundle.forEach(dep => this.childDep(dep)) if (this.children === 0) { this.done() } } childDep (dep) { if (this.node_modules.indexOf(dep) !== -1) { if (!this.seen.has(dep)) { this.seen.add(dep) this.child(dep) } } else if (this.parent) { this.parent.childDep(dep) } } child (dep) { const p = this.path + '/node_modules/' + dep this.children += 1 const child = new BundleWalker({ path: p, parent: this, }) child.on('done', () => { if (--this.children === 0) { this.done() } }) child.start() } } class BundleWalkerSync extends BundleWalker { start () { super.start() this.done() return this } readPackageJson (pj) { try { this.onPackageJson(pj, fs.readFileSync(pj)) } catch { // empty catch } return this } readModules () { try { this.onReaddir(readdirNodeModulesSync(this.path + '/node_modules')) } catch { this.onReaddir([]) } } child (dep) { new BundleWalkerSync({ path: this.path + '/node_modules/' + dep, parent: this, }).start() } } const readdirNodeModules = (nm, cb) => { fs.readdir(nm, (er, set) => { if (er) { cb(er) } else { const scopes = set.filter(f => /^@/.test(f)) if (!scopes.length) { cb(null, set) } else { const unscoped = set.filter(f => !/^@/.test(f)) let count = scopes.length scopes.forEach(scope => { fs.readdir(nm + '/' + scope, (readdirEr, pkgs) => { if (readdirEr || !pkgs.length) { unscoped.push(scope) } else { unscoped.push.apply(unscoped, pkgs.map(p => scope + '/' + p)) } if (--count === 0) { cb(null, unscoped) } }) }) } } }) } const readdirNodeModulesSync = nm => { const set = fs.readdirSync(nm) const unscoped = set.filter(f => !/^@/.test(f)) const scopes = set.filter(f => /^@/.test(f)).map(scope => { try { const pkgs = fs.readdirSync(nm + '/' + scope) return pkgs.length ? pkgs.map(p => scope + '/' + p) : [scope] } catch (er) { return [scope] } }).reduce((a, b) => a.concat(b), []) return unscoped.concat(scopes) } const walk = (options, callback) => { const p = new Promise((resolve, reject) => { new BundleWalker(options).on('done', resolve).on('error', reject).start() }) return callback ? p.then(res => callback(null, res), callback) : p } const walkSync = options => { return new BundleWalkerSync(options).start().result } module.exports = walk walk.sync = walkSync walk.BundleWalker = BundleWalker walk.BundleWalkerSync = BundleWalkerSync PK ~\!npm-bundled/LICENSEnu[The ISC License Copyright (c) npm, Inc. and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\Vchownr/package.jsonnu[{ "_id": "chownr@2.0.0", "_inBundle": true, "_location": "/npm/chownr", "_phantomChildren": {}, "_requiredBy": [ "/npm/tar" ], "author": { "name": "Isaac Z. Schlueter", "email": "i@izs.me", "url": "http://blog.izs.me/" }, "bugs": { "url": "https://github.com/isaacs/chownr/issues" }, "description": "like `chown -R`", "devDependencies": { "mkdirp": "0.3", "rimraf": "^2.7.1", "tap": "^14.10.6" }, "engines": { "node": ">=10" }, "files": [ "chownr.js" ], "homepage": "https://github.com/isaacs/chownr#readme", "license": "ISC", "main": "chownr.js", "name": "chownr", "repository": { "type": "git", "url": "git://github.com/isaacs/chownr.git" }, "scripts": { "postversion": "npm publish", "prepublishOnly": "git push origin --follow-tags", "preversion": "npm test", "test": "tap" }, "tap": { "check-coverage": true }, "version": "2.0.0" } PK ~\aGWchownr/LICENSEnu[The ISC License Copyright (c) Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\lXchownr/chownr.jsnu['use strict' const fs = require('fs') const path = require('path') /* istanbul ignore next */ const LCHOWN = fs.lchown ? 'lchown' : 'chown' /* istanbul ignore next */ const LCHOWNSYNC = fs.lchownSync ? 'lchownSync' : 'chownSync' /* istanbul ignore next */ const needEISDIRHandled = fs.lchown && !process.version.match(/v1[1-9]+\./) && !process.version.match(/v10\.[6-9]/) const lchownSync = (path, uid, gid) => { try { return fs[LCHOWNSYNC](path, uid, gid) } catch (er) { if (er.code !== 'ENOENT') throw er } } /* istanbul ignore next */ const chownSync = (path, uid, gid) => { try { return fs.chownSync(path, uid, gid) } catch (er) { if (er.code !== 'ENOENT') throw er } } /* istanbul ignore next */ const handleEISDIR = needEISDIRHandled ? (path, uid, gid, cb) => er => { // Node prior to v10 had a very questionable implementation of // fs.lchown, which would always try to call fs.open on a directory // Fall back to fs.chown in those cases. if (!er || er.code !== 'EISDIR') cb(er) else fs.chown(path, uid, gid, cb) } : (_, __, ___, cb) => cb /* istanbul ignore next */ const handleEISDirSync = needEISDIRHandled ? (path, uid, gid) => { try { return lchownSync(path, uid, gid) } catch (er) { if (er.code !== 'EISDIR') throw er chownSync(path, uid, gid) } } : (path, uid, gid) => lchownSync(path, uid, gid) // fs.readdir could only accept an options object as of node v6 const nodeVersion = process.version let readdir = (path, options, cb) => fs.readdir(path, options, cb) let readdirSync = (path, options) => fs.readdirSync(path, options) /* istanbul ignore next */ if (/^v4\./.test(nodeVersion)) readdir = (path, options, cb) => fs.readdir(path, cb) const chown = (cpath, uid, gid, cb) => { fs[LCHOWN](cpath, uid, gid, handleEISDIR(cpath, uid, gid, er => { // Skip ENOENT error cb(er && er.code !== 'ENOENT' ? er : null) })) } const chownrKid = (p, child, uid, gid, cb) => { if (typeof child === 'string') return fs.lstat(path.resolve(p, child), (er, stats) => { // Skip ENOENT error if (er) return cb(er.code !== 'ENOENT' ? er : null) stats.name = child chownrKid(p, stats, uid, gid, cb) }) if (child.isDirectory()) { chownr(path.resolve(p, child.name), uid, gid, er => { if (er) return cb(er) const cpath = path.resolve(p, child.name) chown(cpath, uid, gid, cb) }) } else { const cpath = path.resolve(p, child.name) chown(cpath, uid, gid, cb) } } const chownr = (p, uid, gid, cb) => { readdir(p, { withFileTypes: true }, (er, children) => { // any error other than ENOTDIR or ENOTSUP means it's not readable, // or doesn't exist. give up. if (er) { if (er.code === 'ENOENT') return cb() else if (er.code !== 'ENOTDIR' && er.code !== 'ENOTSUP') return cb(er) } if (er || !children.length) return chown(p, uid, gid, cb) let len = children.length let errState = null const then = er => { if (errState) return if (er) return cb(errState = er) if (-- len === 0) return chown(p, uid, gid, cb) } children.forEach(child => chownrKid(p, child, uid, gid, then)) }) } const chownrKidSync = (p, child, uid, gid) => { if (typeof child === 'string') { try { const stats = fs.lstatSync(path.resolve(p, child)) stats.name = child child = stats } catch (er) { if (er.code === 'ENOENT') return else throw er } } if (child.isDirectory()) chownrSync(path.resolve(p, child.name), uid, gid) handleEISDirSync(path.resolve(p, child.name), uid, gid) } const chownrSync = (p, uid, gid) => { let children try { children = readdirSync(p, { withFileTypes: true }) } catch (er) { if (er.code === 'ENOENT') return else if (er.code === 'ENOTDIR' || er.code === 'ENOTSUP') return handleEISDirSync(p, uid, gid) else throw er } if (children && children.length) children.forEach(child => chownrKidSync(p, child, uid, gid)) return handleEISDirSync(p, uid, gid) } module.exports = chownr chownr.sync = chownrSync PK ~\ȵfdd)validate-npm-package-license/package.jsonnu[{ "_id": "validate-npm-package-license@3.0.4", "_inBundle": true, "_location": "/npm/validate-npm-package-license", "_phantomChildren": { "spdx-exceptions": "2.5.0", "spdx-license-ids": "3.0.18" }, "_requiredBy": [ "/npm/init-package-json", "/npm/normalize-package-data" ], "author": { "name": "Kyle E. Mitchell", "email": "kyle@kemitchell.com", "url": "https://kemitchell.com" }, "bugs": { "url": "https://github.com/kemitchell/validate-npm-package-license.js/issues" }, "contributors": [ { "name": "Mark Stacey", "email": "markjstacey@gmail.com" } ], "dependencies": { "spdx-correct": "^3.0.0", "spdx-expression-parse": "^3.0.0" }, "description": "Give me a string and I'll tell you if it's a valid npm package license string", "devDependencies": { "defence-cli": "^2.0.1", "replace-require-self": "^1.0.0" }, "homepage": "https://github.com/kemitchell/validate-npm-package-license.js#readme", "keywords": [ "license", "npm", "package", "validation" ], "license": "Apache-2.0", "name": "validate-npm-package-license", "repository": { "type": "git", "url": "git+https://github.com/kemitchell/validate-npm-package-license.js.git" }, "scripts": { "test": "defence README.md | replace-require-self | node" }, "version": "3.0.4" } PK ~\88Lvalidate-npm-package-license/node_modules/spdx-expression-parse/package.jsonnu[{ "_id": "spdx-expression-parse@3.0.1", "_inBundle": true, "_location": "/npm/validate-npm-package-license/spdx-expression-parse", "_phantomChildren": {}, "_requiredBy": [ "/npm/validate-npm-package-license" ], "author": { "name": "Kyle E. Mitchell", "email": "kyle@kemitchell.com", "url": "https://kemitchell.com" }, "bugs": { "url": "https://github.com/jslicense/spdx-expression-parse.js/issues" }, "contributors": [ { "name": "C. Scott Ananian", "email": "cscott@cscott.net", "url": "http://cscott.net" }, { "name": "Kyle E. Mitchell", "email": "kyle@kemitchell.com", "url": "https://kemitchell.com" }, { "name": "Shinnosuke Watanabe", "email": "snnskwtnb@gmail.com" }, { "name": "Antoine Motet", "email": "antoine.motet@gmail.com" } ], "dependencies": { "spdx-exceptions": "^2.1.0", "spdx-license-ids": "^3.0.0" }, "description": "parse SPDX license expressions", "devDependencies": { "defence-cli": "^3.0.1", "replace-require-self": "^1.0.0", "standard": "^14.1.0" }, "files": [ "AUTHORS", "index.js", "parse.js", "scan.js" ], "homepage": "https://github.com/jslicense/spdx-expression-parse.js#readme", "keywords": [ "SPDX", "law", "legal", "license", "metadata", "package", "package.json", "standards" ], "license": "MIT", "name": "spdx-expression-parse", "repository": { "type": "git", "url": "git+https://github.com/jslicense/spdx-expression-parse.js.git" }, "scripts": { "lint": "standard", "test": "npm run test:suite && npm run test:readme", "test:readme": "defence -i javascript README.md | replace-require-self | node", "test:suite": "node test.js" }, "version": "3.0.1" } PK ~\WWGvalidate-npm-package-license/node_modules/spdx-expression-parse/LICENSEnu[The MIT License Copyright (c) 2015 Kyle E. Mitchell & other authors listed in AUTHORS Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\]MHvalidate-npm-package-license/node_modules/spdx-expression-parse/index.jsnu['use strict' var scan = require('./scan') var parse = require('./parse') module.exports = function (source) { return parse(scan(source)) } PK ~\YU U Hvalidate-npm-package-license/node_modules/spdx-expression-parse/parse.jsnu['use strict' // The ABNF grammar in the spec is totally ambiguous. // // This parser follows the operator precedence defined in the // `Order of Precedence and Parentheses` section. module.exports = function (tokens) { var index = 0 function hasMore () { return index < tokens.length } function token () { return hasMore() ? tokens[index] : null } function next () { if (!hasMore()) { throw new Error() } index++ } function parseOperator (operator) { var t = token() if (t && t.type === 'OPERATOR' && operator === t.string) { next() return t.string } } function parseWith () { if (parseOperator('WITH')) { var t = token() if (t && t.type === 'EXCEPTION') { next() return t.string } throw new Error('Expected exception after `WITH`') } } function parseLicenseRef () { // TODO: Actually, everything is concatenated into one string // for backward-compatibility but it could be better to return // a nice structure. var begin = index var string = '' var t = token() if (t.type === 'DOCUMENTREF') { next() string += 'DocumentRef-' + t.string + ':' if (!parseOperator(':')) { throw new Error('Expected `:` after `DocumentRef-...`') } } t = token() if (t.type === 'LICENSEREF') { next() string += 'LicenseRef-' + t.string return { license: string } } index = begin } function parseLicense () { var t = token() if (t && t.type === 'LICENSE') { next() var node = { license: t.string } if (parseOperator('+')) { node.plus = true } var exception = parseWith() if (exception) { node.exception = exception } return node } } function parseParenthesizedExpression () { var left = parseOperator('(') if (!left) { return } var expr = parseExpression() if (!parseOperator(')')) { throw new Error('Expected `)`') } return expr } function parseAtom () { return ( parseParenthesizedExpression() || parseLicenseRef() || parseLicense() ) } function makeBinaryOpParser (operator, nextParser) { return function parseBinaryOp () { var left = nextParser() if (!left) { return } if (!parseOperator(operator)) { return left } var right = parseBinaryOp() if (!right) { throw new Error('Expected expression') } return { left: left, conjunction: operator.toLowerCase(), right: right } } } var parseAnd = makeBinaryOpParser('AND', parseAtom) var parseExpression = makeBinaryOpParser('OR', parseAnd) var node = parseExpression() if (!node || hasMore()) { throw new Error('Syntax error') } return node } PK ~\ d Gvalidate-npm-package-license/node_modules/spdx-expression-parse/scan.jsnu['use strict' var licenses = [] .concat(require('spdx-license-ids')) .concat(require('spdx-license-ids/deprecated')) var exceptions = require('spdx-exceptions') module.exports = function (source) { var index = 0 function hasMore () { return index < source.length } // `value` can be a regexp or a string. // If it is recognized, the matching source string is returned and // the index is incremented. Otherwise `undefined` is returned. function read (value) { if (value instanceof RegExp) { var chars = source.slice(index) var match = chars.match(value) if (match) { index += match[0].length return match[0] } } else { if (source.indexOf(value, index) === index) { index += value.length return value } } } function skipWhitespace () { read(/[ ]*/) } function operator () { var string var possibilities = ['WITH', 'AND', 'OR', '(', ')', ':', '+'] for (var i = 0; i < possibilities.length; i++) { string = read(possibilities[i]) if (string) { break } } if (string === '+' && index > 1 && source[index - 2] === ' ') { throw new Error('Space before `+`') } return string && { type: 'OPERATOR', string: string } } function idstring () { return read(/[A-Za-z0-9-.]+/) } function expectIdstring () { var string = idstring() if (!string) { throw new Error('Expected idstring at offset ' + index) } return string } function documentRef () { if (read('DocumentRef-')) { var string = expectIdstring() return { type: 'DOCUMENTREF', string: string } } } function licenseRef () { if (read('LicenseRef-')) { var string = expectIdstring() return { type: 'LICENSEREF', string: string } } } function identifier () { var begin = index var string = idstring() if (licenses.indexOf(string) !== -1) { return { type: 'LICENSE', string: string } } else if (exceptions.indexOf(string) !== -1) { return { type: 'EXCEPTION', string: string } } index = begin } // Tries to read the next token. Returns `undefined` if no token is // recognized. function parseToken () { // Ordering matters return ( operator() || documentRef() || licenseRef() || identifier() ) } var tokens = [] while (hasMore()) { skipWhitespace() if (!hasMore()) { break } var token = parseToken() if (!token) { throw new Error('Unexpected `' + source[index] + '` at offset ' + index) } tokens.push(token) } return tokens } PK ~\BF.Gvalidate-npm-package-license/node_modules/spdx-expression-parse/AUTHORSnu[C. Scott Ananian (http://cscott.net) Kyle E. Mitchell (https://kemitchell.com) Shinnosuke Watanabe Antoine Motet PK ~\^,^,$validate-npm-package-license/LICENSEnu[ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. PK ~\#"y%validate-npm-package-license/index.jsnu[var parse = require('spdx-expression-parse'); var correct = require('spdx-correct'); var genericWarning = ( 'license should be ' + 'a valid SPDX license expression (without "LicenseRef"), ' + '"UNLICENSED", or ' + '"SEE LICENSE IN "' ); var fileReferenceRE = /^SEE LICEN[CS]E IN (.+)$/; function startsWith(prefix, string) { return string.slice(0, prefix.length) === prefix; } function usesLicenseRef(ast) { if (ast.hasOwnProperty('license')) { var license = ast.license; return ( startsWith('LicenseRef', license) || startsWith('DocumentRef', license) ); } else { return ( usesLicenseRef(ast.left) || usesLicenseRef(ast.right) ); } } module.exports = function(argument) { var ast; try { ast = parse(argument); } catch (e) { var match if ( argument === 'UNLICENSED' || argument === 'UNLICENCED' ) { return { validForOldPackages: true, validForNewPackages: true, unlicensed: true }; } else if (match = fileReferenceRE.exec(argument)) { return { validForOldPackages: true, validForNewPackages: true, inFile: match[1] }; } else { var result = { validForOldPackages: false, validForNewPackages: false, warnings: [genericWarning] }; if (argument.trim().length !== 0) { var corrected = correct(argument); if (corrected) { result.warnings.push( 'license is similar to the valid expression "' + corrected + '"' ); } } return result; } } if (usesLicenseRef(ast)) { return { validForNewPackages: false, validForOldPackages: false, spdx: true, warnings: [genericWarning] }; } else { return { validForNewPackages: true, validForOldPackages: true, spdx: true }; } }; PK ~\@*ms/package.jsonnu[{ "_id": "ms@2.1.3", "_inBundle": true, "_location": "/npm/ms", "_phantomChildren": {}, "_requiredBy": [ "/npm" ], "bugs": { "url": "https://github.com/vercel/ms/issues" }, "description": "Tiny millisecond conversion utility", "devDependencies": { "eslint": "4.18.2", "expect.js": "0.3.1", "husky": "0.14.3", "lint-staged": "5.0.0", "mocha": "4.0.1", "prettier": "2.0.5" }, "eslintConfig": { "extends": "eslint:recommended", "env": { "node": true, "es6": true } }, "files": [ "index.js" ], "homepage": "https://github.com/vercel/ms#readme", "license": "MIT", "lint-staged": { "*.js": [ "npm run lint", "prettier --single-quote --write", "git add" ] }, "main": "./index", "name": "ms", "repository": { "type": "git", "url": "git+https://github.com/vercel/ms.git" }, "scripts": { "lint": "eslint lib/* bin/*", "precommit": "lint-staged", "test": "mocha tests.js" }, "version": "2.1.3" } PK ~\"L ms/index.jsnu[/** * Helpers. */ var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; var w = d * 7; var y = d * 365.25; /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} [options] * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ module.exports = function (val, options) { options = options || {}; var type = typeof val; if (type === 'string' && val.length > 0) { return parse(val); } else if (type === 'number' && isFinite(val)) { return options.long ? fmtLong(val) : fmtShort(val); } throw new Error( 'val is not a non-empty string or a valid number. val=' + JSON.stringify(val) ); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = String(str); if (str.length > 100) { return; } var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( str ); if (!match) { return; } var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y; case 'weeks': case 'week': case 'w': return n * w; case 'days': case 'day': case 'd': return n * d; case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h; case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m; case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s; case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n; default: return undefined; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return Math.round(ms / d) + 'd'; } if (msAbs >= h) { return Math.round(ms / h) + 'h'; } if (msAbs >= m) { return Math.round(ms / m) + 'm'; } if (msAbs >= s) { return Math.round(ms / s) + 's'; } return ms + 'ms'; } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return plural(ms, msAbs, d, 'day'); } if (msAbs >= h) { return plural(ms, msAbs, h, 'hour'); } if (msAbs >= m) { return plural(ms, msAbs, m, 'minute'); } if (msAbs >= s) { return plural(ms, msAbs, s, 'second'); } return ms + ' ms'; } /** * Pluralization helper. */ function plural(ms, msAbs, n, name) { var isPlural = msAbs >= n * 1.5; return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); } PK ~\j,77 ms/license.mdnu[The MIT License (MIT) Copyright (c) 2020 Vercel, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\oKKansi-regex/package.jsonnu[{ "_id": "ansi-regex@5.0.1", "_inBundle": true, "_location": "/npm/ansi-regex", "_phantomChildren": {}, "_requiredBy": [ "/npm/strip-ansi", "/npm/strip-ansi-cjs" ], "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "bugs": { "url": "https://github.com/chalk/ansi-regex/issues" }, "description": "Regular expression for matching ANSI escape codes", "devDependencies": { "ava": "^2.4.0", "tsd": "^0.9.0", "xo": "^0.25.3" }, "engines": { "node": ">=8" }, "files": [ "index.js", "index.d.ts" ], "homepage": "https://github.com/chalk/ansi-regex#readme", "keywords": [ "ansi", "styles", "color", "colour", "colors", "terminal", "console", "cli", "string", "tty", "escape", "formatting", "rgb", "256", "shell", "xterm", "command-line", "text", "regex", "regexp", "re", "match", "test", "find", "pattern" ], "license": "MIT", "name": "ansi-regex", "repository": { "type": "git", "url": "git+https://github.com/chalk/ansi-regex.git" }, "scripts": { "test": "xo && ava && tsd", "view-supported": "node fixtures/view-codes.js" }, "version": "5.0.1" } PK ~\^(]^^ansi-regex/index.jsnu['use strict'; module.exports = ({onlyFirst = false} = {}) => { const pattern = [ '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' ].join('|'); return new RegExp(pattern, onlyFirst ? undefined : 'g'); }; PK ~\E}UUansi-regex/licensenu[MIT License Copyright (c) Sindre Sorhus (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\)-$promise-all-reject-late/package.jsonnu[{ "_id": "promise-all-reject-late@1.0.1", "_inBundle": true, "_location": "/npm/promise-all-reject-late", "_phantomChildren": {}, "_requiredBy": [ "/npm/@npmcli/arborist" ], "author": { "name": "Isaac Z. Schlueter", "email": "i@izs.me", "url": "https://izs.me" }, "description": "Like Promise.all, but save rejections until all promises are resolved", "devDependencies": { "tap": "^14.10.5" }, "funding": { "url": "https://github.com/sponsors/isaacs" }, "license": "ISC", "name": "promise-all-reject-late", "scripts": { "postversion": "npm publish", "prepublishOnly": "git push origin --follow-tags", "preversion": "npm test", "test": "tap" }, "tap": { "check-coverage": true }, "version": "1.0.1" } PK ~\鏪! ! %promise-all-reject-late/test/index.jsnu[const t = require('tap') const main = () => { if (process.argv[2] === 'polyfill-all-settled') { Promise.allSettled = null runTests() } else if (process.argv[2] === 'native-all-settled') { Promise.allSettled = Promise.allSettled || ( promises => { const reflections = [] for (let i = 0; i < promises.length; i++) { reflections[i] = Promise.resolve(promises[i]).then(value => ({ status: 'fulfilled', value, }), reason => ({ status: 'rejected', reason, })) } return Promise.all(reflections) } ) runTests() } else { t.spawn(process.execPath, [__filename, 'polyfill-all-settled']) t.spawn(process.execPath, [__filename, 'native-all-settled']) } } const runTests = () => { const lateFail = require('../') t.test('fail only after all promises resolve', t => { let resolvedSlow = false const fast = () => Promise.reject('nope') const slow = () => new Promise(res => setTimeout(res, 100)) .then(() => resolvedSlow = true) // throw some holes and junk in the array to verify that we handle it return t.rejects(lateFail([fast(),,,,slow(), null, {not: 'a promise'},,,])) .then(() => t.equal(resolvedSlow, true, 'resolved slow before failure')) }) t.test('works just like Promise.all() otherwise', t => { const one = () => Promise.resolve(1) const two = () => Promise.resolve(2) const tre = () => Promise.resolve(3) const fur = () => Promise.resolve(4) const fiv = () => Promise.resolve(5) const six = () => Promise.resolve(6) const svn = () => Promise.resolve(7) const eit = () => Promise.resolve(8) const nin = () => Promise.resolve(9) const ten = () => Promise.resolve(10) const expect = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] const all = Promise.all([ one(), two(), tre(), fur(), fiv(), six(), svn(), eit(), nin(), ten(), ]) const late = lateFail([ one(), two(), tre(), fur(), fiv(), six(), svn(), eit(), nin(), ten(), ]) return Promise.all([all, late]).then(([all, late]) => { t.strictSame(all, expect) t.strictSame(late, expect) }) }) } main() PK ~\?&promise-all-reject-late/LICENSEnu[The ISC License Copyright (c) Isaac Z. Schlueter Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\` promise-all-reject-late/index.jsnu[const allSettled = Promise.allSettled ? promises => Promise.allSettled(promises) : promises => { const reflections = [] for (let i = 0; i < promises.length; i++) { reflections[i] = Promise.resolve(promises[i]).then(value => ({ status: 'fulfilled', value, }), reason => ({ status: 'rejected', reason, })) } return Promise.all(reflections) } module.exports = promises => allSettled(promises).then(results => { let er = null const ret = new Array(results.length) results.forEach((result, i) => { if (result.status === 'rejected') throw result.reason else ret[i] = result.value }) return ret }) PK ~\p{kkwrap-ansi/package.jsonnu[{ "_id": "wrap-ansi@8.1.0", "_inBundle": true, "_location": "/npm/wrap-ansi", "_phantomChildren": { "eastasianwidth": "0.2.0" }, "_requiredBy": [ "/npm/@isaacs/cliui" ], "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "bugs": { "url": "https://github.com/chalk/wrap-ansi/issues" }, "dependencies": { "ansi-styles": "^6.1.0", "string-width": "^5.0.1", "strip-ansi": "^7.0.1" }, "description": "Wordwrap a string with ANSI escape codes", "devDependencies": { "ava": "^3.15.0", "chalk": "^4.1.2", "coveralls": "^3.1.1", "has-ansi": "^5.0.1", "nyc": "^15.1.0", "tsd": "^0.25.0", "xo": "^0.44.0" }, "engines": { "node": ">=12" }, "exports": { "types": "./index.d.ts", "default": "./index.js" }, "files": [ "index.js", "index.d.ts" ], "funding": "https://github.com/chalk/wrap-ansi?sponsor=1", "homepage": "https://github.com/chalk/wrap-ansi#readme", "keywords": [ "wrap", "break", "wordwrap", "wordbreak", "linewrap", "ansi", "styles", "color", "colour", "colors", "terminal", "console", "cli", "string", "tty", "escape", "formatting", "rgb", "256", "shell", "xterm", "log", "logging", "command-line", "text" ], "license": "MIT", "name": "wrap-ansi", "repository": { "type": "git", "url": "git+https://github.com/chalk/wrap-ansi.git" }, "scripts": { "test": "xo && nyc ava && tsd" }, "type": "module", "version": "8.1.0" } PK ~\88*wrap-ansi/node_modules/emoji-regex/text.jsnu["use strict"; module.exports = function () { // https://mths.be/emoji return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE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D83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD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uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F?/g; }; PK ~\"!@/wrap-ansi/node_modules/emoji-regex/package.jsonnu[{ "_id": "emoji-regex@9.2.2", "_inBundle": true, "_location": "/npm/wrap-ansi/emoji-regex", "_phantomChildren": {}, "_requiredBy": [ "/npm/wrap-ansi/string-width" ], "author": { "name": "Mathias Bynens", "url": "https://mathiasbynens.be/" }, "bugs": { "url": "https://github.com/mathiasbynens/emoji-regex/issues" }, "description": "A regular expression to match all Emoji-only symbols as per the Unicode Standard.", "devDependencies": { "@babel/cli": "^7.4.4", "@babel/core": "^7.4.4", "@babel/plugin-proposal-unicode-property-regex": "^7.4.4", "@babel/preset-env": "^7.4.4", "@unicode/unicode-13.0.0": "^1.0.3", "mocha": "^6.1.4", "regexgen": "^1.3.0" }, "files": [ "LICENSE-MIT.txt", "index.js", "index.d.ts", "RGI_Emoji.js", "RGI_Emoji.d.ts", "text.js", "text.d.ts", "es2015" ], "homepage": "https://mths.be/emoji-regex", "keywords": [ "unicode", "regex", "regexp", "regular expressions", "code points", "symbols", "characters", "emoji" ], "license": "MIT", "main": "index.js", "name": "emoji-regex", "repository": { "type": "git", "url": "git+https://github.com/mathiasbynens/emoji-regex.git" }, "scripts": { "build": "rm -rf -- es2015; babel src -d .; NODE_ENV=es2015 babel src es2015_types -D -d ./es2015; node script/inject-sequences.js", "test": "mocha", "test:watch": "npm run test -- --watch" }, "types": "index.d.ts", "version": "9.2.2" } PK ~\_w=w=+wrap-ansi/node_modules/emoji-regex/index.jsnu["use strict"; module.exports = function () { // https://mths.be/emoji return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D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uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; }; PK ~\ڌC552wrap-ansi/node_modules/emoji-regex/LICENSE-MIT.txtnu[Copyright Mathias Bynens Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\h==1wrap-ansi/node_modules/emoji-regex/es2015/text.jsnu["use strict"; module.exports = () => { // https://mths.be/emoji return /\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0077}\u{E006C}\u{E0073}|\u{E0073}\u{E0063}\u{E0074}|\u{E0065}\u{E006E}\u{E0067})\u{E007F}|(?:\u{1F9D1}\u{1F3FF}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FF}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FE}]|(?:\u{1F9D1}\u{1F3FE}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FE}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FD}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FD}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FC}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FC}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FB}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FB}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FC}-\u{1F3FF}]|\u{1F468}(?:\u{1F3FB}(?:\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FF}]|\u{1F468}[\u{1F3FB}-\u{1F3FF}])|\u{1F91D}\u200D\u{1F468}[\u{1F3FC}-\u{1F3FF}]|[\u2695\u2696\u2708]\uFE0F|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]))?|[\u{1F3FC}-\u{1F3FF}]\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FF}]|\u{1F468}[\u{1F3FB}-\u{1F3FF}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FE}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u{1F466}\u{1F467}])|\u{1F3FF}|\u{1F3FE}|\u{1F3FD}|\u{1F3FC})?|(?:\u{1F469}(?:\u{1F3FB}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F3FC}-\u{1F3FF}]\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}]))|\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]\u200D\u{1F91D}\u200D\u{1F9D1})[\u{1F3FB}-\u{1F3FF}]|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F469}(?:\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FE}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FD}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FC}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680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ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|\u{1F469}\u200D\u{1F467}\u200D[\u{1F466}\u{1F467}]|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F9D1}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\u{1F469}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\u{1F636}\u200D\u{1F32B}|\u{1F3F3}\uFE0F\u200D\u26A7|\u{1F43B}\u200D\u2744|(?:[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\uFE0F\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|\u{1F3F4}\u200D\u2620|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}]\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F202}\u{1F237}\u{1F321}\u{1F324}-\u{1F32C}\u{1F336}\u{1F37D}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}\u{1F39F}\u{1F3CD}\u{1F3CE}\u{1F3D4}-\u{1F3DF}\u{1F3F5}\u{1F3F7}\u{1F43F}\u{1F4FD}\u{1F549}\u{1F54A}\u{1F56F}\u{1F570}\u{1F573}\u{1F576}-\u{1F579}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F5A5}\u{1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}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F934}\u{1F936}\u{1F977}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}\u{1F9D3}\u{1F9D5}][\u{1F3FB}-\u{1F3FF}]|[\u261D\u270C\u270D\u{1F574}\u{1F590}][\uFE0F\u{1F3FB}-\u{1F3FF}]|[\u270A\u270B\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F408}\u{1F415}\u{1F43B}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F57A}\u{1F595}\u{1F596}\u{1F62E}\u{1F635}\u{1F636}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90C}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F934}\u{1F936}\u{1F977}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}\u{1F9D3}\u{1F9D5}]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}]|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F384}\u{1F386}-\u{1F393}\u{1F3A0}-\u{1F3C1}\u{1F3C5}\u{1F3C6}\u{1F3C8}\u{1F3C9}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F8}-\u{1F407}\u{1F409}-\u{1F414}\u{1F416}-\u{1F43A}\u{1F43C}-\u{1F43E}\u{1F440}\u{1F444}\u{1F445}\u{1F451}-\u{1F465}\u{1F46A}\u{1F479}-\u{1F47B}\u{1F47D}-\u{1F480}\u{1F484}\u{1F488}-\u{1F48E}\u{1F490}\u{1F492}-\u{1F4A9}\u{1F4AB}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F5A4}\u{1F5FB}-\u{1F62D}\u{1F62F}-\u{1F634}\u{1F637}-\u{1F644}\u{1F648}-\u{1F64A}\u{1F680}-\u{1F6A2}\u{1F6A4}-\u{1F6B3}\u{1F6B7}-\u{1F6BF}\u{1F6C1}-\u{1F6C5}\u{1F6D0}-\u{1F6D2}\u{1F6D5}-\u{1F6D7}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FC}\u{1F7E0}-\u{1F7EB}\u{1F90D}\u{1F90E}\u{1F910}-\u{1F917}\u{1F91D}\u{1F920}-\u{1F925}\u{1F927}-\u{1F92F}\u{1F93A}\u{1F93F}-\u{1F945}\u{1F947}-\u{1F976}\u{1F978}\u{1F97A}-\u{1F9B4}\u{1F9B7}\u{1F9BA}\u{1F9BC}-\u{1F9CB}\u{1F9D0}\u{1F9E0}-\u{1F9FF}\u{1FA70}-\u{1FA74}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA86}\u{1FA90}-\u{1FAA8}\u{1FAB0}-\u{1FAB6}\u{1FAC0}-\u{1FAC2}\u{1FAD0}-\u{1FAD6}]|[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299\u{1F004}\u{1F0CF}\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F321}\u{1F324}-\u{1F393}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}-\u{1F3F0}\u{1F3F3}-\u{1F3F5}\u{1F3F7}-\u{1F4FD}\u{1F4FF}-\u{1F53D}\u{1F549}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F56F}\u{1F570}\u{1F573}-\u{1F57A}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F590}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CB}-\u{1F6D2}\u{1F6D5}-\u{1F6D7}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6EB}\u{1F6EC}\u{1F6F0}\u{1F6F3}-\u{1F6FC}\u{1F7E0}-\u{1F7EB}\u{1F90C}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F978}\u{1F97A}-\u{1F9CB}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA74}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA86}\u{1FA90}-\u{1FAA8}\u{1FAB0}-\u{1FAB6}\u{1FAC0}-\u{1FAC2}\u{1FAD0}-\u{1FAD6}]\uFE0F?/gu; }; PK ~\ KCC2wrap-ansi/node_modules/emoji-regex/es2015/index.jsnu["use strict"; module.exports = () => { // https://mths.be/emoji return /\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0077}\u{E006C}\u{E0073}|\u{E0073}\u{E0063}\u{E0074}|\u{E0065}\u{E006E}\u{E0067})\u{E007F}|(?:\u{1F9D1}\u{1F3FF}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FF}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FE}]|(?:\u{1F9D1}\u{1F3FE}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FE}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FD}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FD}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FC}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FC}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FB}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FB}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FC}-\u{1F3FF}]|\u{1F468}(?:\u{1F3FB}(?:\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FF}]|\u{1F468}[\u{1F3FB}-\u{1F3FF}])|\u{1F91D}\u200D\u{1F468}[\u{1F3FC}-\u{1F3FF}]|[\u2695\u2696\u2708]\uFE0F|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]))?|[\u{1F3FC}-\u{1F3FF}]\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FF}]|\u{1F468}[\u{1F3FB}-\u{1F3FF}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FE}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u{1F466}\u{1F467}])|\u{1F3FF}|\u{1F3FE}|\u{1F3FD}|\u{1F3FC})?|(?:\u{1F469}(?:\u{1F3FB}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F3FC}-\u{1F3FF}]\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}]))|\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]\u200D\u{1F91D}\u200D\u{1F9D1})[\u{1F3FB}-\u{1F3FF}]|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F469}(?:\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}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9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FE}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FD}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FC}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|\u{1F469}\u200D\u{1F467}\u200D[\u{1F466}\u{1F467}]|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F9D1}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\u{1F469}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\u{1F636}\u200D\u{1F32B}|\u{1F3F3}\uFE0F\u200D\u26A7|\u{1F43B}\u200D\u2744|(?:[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\uFE0F\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|\u{1F3F4}\u200D\u2620|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}]\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F202}\u{1F237}\u{1F321}\u{1F324}-\u{1F32C}\u{1F336}\u{1F37D}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}\u{1F39F}\u{1F3CD}\u{1F3CE}\u{1F3D4}-\u{1F3DF}\u{1F3F5}\u{1F3F7}\u{1F43F}\u{1F4FD}\u{1F549}\u{1F54A}\u{1F56F}\u{1F570}\u{1F573}\u{1F576}-\u{1F579}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}\u{1F6CB}\u{1F6CD}-\u{1F6CF}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6F0}\u{1F6F3}])\uFE0F|\u{1F3F3}\uFE0F\u200D\u{1F308}|\u{1F469}\u200D\u{1F467}|\u{1F469}\u200D\u{1F466}|\u{1F635}\u200D\u{1F4AB}|\u{1F62E}\u200D\u{1F4A8}|\u{1F415}\u200D\u{1F9BA}|\u{1F9D1}(?:\u{1F3FF}|\u{1F3FE}|\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FE0F\u20E3|\u2764\uFE0F|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\uFE0F\u{1F3FB}-\u{1F3FF}]|\u{1F3F4}|[\u270A\u270B\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F57A}\u{1F595}\u{1F596}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90C}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F934}\u{1F936}\u{1F977}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}\u{1F9D3}\u{1F9D5}][\u{1F3FB}-\u{1F3FF}]|[\u261D\u270C\u270D\u{1F574}\u{1F590}][\uFE0F\u{1F3FB}-\u{1F3FF}]|[\u270A\u270B\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F408}\u{1F415}\u{1F43B}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F57A}\u{1F595}\u{1F596}\u{1F62E}\u{1F635}\u{1F636}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90C}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F934}\u{1F936}\u{1F977}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}\u{1F9D3}\u{1F9D5}]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}]|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F384}\u{1F386}-\u{1F393}\u{1F3A0}-\u{1F3C1}\u{1F3C5}\u{1F3C6}\u{1F3C8}\u{1F3C9}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F8}-\u{1F407}\u{1F409}-\u{1F414}\u{1F416}-\u{1F43A}\u{1F43C}-\u{1F43E}\u{1F440}\u{1F444}\u{1F445}\u{1F451}-\u{1F465}\u{1F46A}\u{1F479}-\u{1F47B}\u{1F47D}-\u{1F480}\u{1F484}\u{1F488}-\u{1F48E}\u{1F490}\u{1F492}-\u{1F4A9}\u{1F4AB}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F5A4}\u{1F5FB}-\u{1F62D}\u{1F62F}-\u{1F634}\u{1F637}-\u{1F644}\u{1F648}-\u{1F64A}\u{1F680}-\u{1F6A2}\u{1F6A4}-\u{1F6B3}\u{1F6B7}-\u{1F6BF}\u{1F6C1}-\u{1F6C5}\u{1F6D0}-\u{1F6D2}\u{1F6D5}-\u{1F6D7}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FC}\u{1F7E0}-\u{1F7EB}\u{1F90D}\u{1F90E}\u{1F910}-\u{1F917}\u{1F91D}\u{1F920}-\u{1F925}\u{1F927}-\u{1F92F}\u{1F93A}\u{1F93F}-\u{1F945}\u{1F947}-\u{1F976}\u{1F978}\u{1F97A}-\u{1F9B4}\u{1F9B7}\u{1F9BA}\u{1F9BC}-\u{1F9CB}\u{1F9D0}\u{1F9E0}-\u{1F9FF}\u{1FA70}-\u{1FA74}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA86}\u{1FA90}-\u{1FAA8}\u{1FAB0}-\u{1FAB6}\u{1FAC0}-\u{1FAC2}\u{1FAD0}-\u{1FAD6}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F393}\u{1F3A0}-\u{1F3CA}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F4}\u{1F3F8}-\u{1F43E}\u{1F440}\u{1F442}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F57A}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5FB}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CC}\u{1F6D0}-\u{1F6D2}\u{1F6D5}-\u{1F6D7}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FC}\u{1F7E0}-\u{1F7EB}\u{1F90C}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F978}\u{1F97A}-\u{1F9CB}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA74}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA86}\u{1FA90}-\u{1FAA8}\u{1FAB0}-\u{1FAB6}\u{1FAC0}-\u{1FAC2}\u{1FAD0}-\u{1FAD6}]|[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299\u{1F004}\u{1F0CF}\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F321}\u{1F324}-\u{1F393}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}-\u{1F3F0}\u{1F3F3}-\u{1F3F5}\u{1F3F7}-\u{1F4FD}\u{1F4FF}-\u{1F53D}\u{1F549}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F56F}\u{1F570}\u{1F573}-\u{1F57A}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F590}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CB}-\u{1F6D2}\u{1F6D5}-\u{1F6D7}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6EB}\u{1F6EC}\u{1F6F0}\u{1F6F3}-\u{1F6FC}\u{1F7E0}-\u{1F7EB}\u{1F90C}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F978}\u{1F97A}-\u{1F9CB}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA74}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA86}\u{1FA90}-\u{1FAA8}\u{1FAB0}-\u{1FAB6}\u{1FAC0}-\u{1FAC2}\u{1FAD0}-\u{1FAD6}]\uFE0F|[\u261D\u26F9\u270A-\u270D\u{1F385}\u{1F3C2}-\u{1F3C4}\u{1F3C7}\u{1F3CA}-\u{1F3CC}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}-\u{1F478}\u{1F47C}\u{1F481}-\u{1F483}\u{1F485}-\u{1F487}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F574}\u{1F575}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F645}-\u{1F647}\u{1F64B}-\u{1F64F}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F6C0}\u{1F6CC}\u{1F90C}\u{1F90F}\u{1F918}-\u{1F91F}\u{1F926}\u{1F930}-\u{1F939}\u{1F93C}-\u{1F93E}\u{1F977}\u{1F9B5}\u{1F9B6}\u{1F9B8}\u{1F9B9}\u{1F9BB}\u{1F9CD}-\u{1F9CF}\u{1F9D1}-\u{1F9DD}]/gu; }; PK ~\+z*666wrap-ansi/node_modules/emoji-regex/es2015/RGI_Emoji.jsnu["use strict"; module.exports = () => { // https://mths.be/emoji return /\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0077}\u{E006C}\u{E0073}|\u{E0073}\u{E0063}\u{E0074}|\u{E0065}\u{E006E}\u{E0067})\u{E007F}|(?:\u{1F9D1}\u{1F3FF}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FF}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FE}]|(?:\u{1F9D1}\u{1F3FE}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FE}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FD}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FD}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FC}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FC}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|(?:\u{1F9D1}\u{1F3FB}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F9D1}|\u{1F469}\u{1F3FB}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FC}-\u{1F3FF}]|\u{1F468}(?:\u{1F3FB}(?:\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FF}]|\u{1F468}[\u{1F3FB}-\u{1F3FF}])|\u{1F91D}\u200D\u{1F468}[\u{1F3FC}-\u{1F3FF}]|[\u2695\u2696\u2708]\uFE0F|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]))?|[\u{1F3FC}-\u{1F3FF}]\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FF}]|\u{1F468}[\u{1F3FB}-\u{1F3FF}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FE}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u{1F466}\u{1F467}])|\u{1F3FF}|\u{1F3FE}|\u{1F3FD}|\u{1F3FC})?|(?:\u{1F469}(?:\u{1F3FB}\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F3FC}-\u{1F3FF}]\u200D\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}]))|\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]\u200D\u{1F91D}\u200D\u{1F9D1})[\u{1F3FB}-\u{1F3FF}]|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F469}(?:\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{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}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FE}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FD}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FC}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F37C}\u{1F384}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|\u{1F469}\u200D\u{1F467}\u200D[\u{1F466}\u{1F467}]|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F9D1}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\u{1F469}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\u{1F636}\u200D\u{1F32B}|\u{1F3F3}\uFE0F\u200D\u26A7|\u{1F43B}\u200D\u2744|(?:[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\uFE0F\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|\u{1F3F4}\u200D\u2620|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}]\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F202}\u{1F237}\u{1F321}\u{1F324}-\u{1F32C}\u{1F336}\u{1F37D}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}\u{1F39F}\u{1F3CD}\u{1F3CE}\u{1F3D4}-\u{1F3DF}\u{1F3F5}\u{1F3F7}\u{1F43F}\u{1F4FD}\u{1F549}\u{1F54A}\u{1F56F}\u{1F570}\u{1F573}\u{1F576}-\u{1F579}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}\u{1F6CB}\u{1F6CD}-\u{1F6CF}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6F0}\u{1F6F3}])\uFE0F|\u{1F3F3}\uFE0F\u200D\u{1F308}|\u{1F469}\u200D\u{1F467}|\u{1F469}\u200D\u{1F466}|\u{1F635}\u200D\u{1F4AB}|\u{1F62E}\u200D\u{1F4A8}|\u{1F415}\u200D\u{1F9BA}|\u{1F9D1}(?:\u{1F3FF}|\u{1F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0-9]\uFE0F\u20E3|\u2764\uFE0F|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\uFE0F\u{1F3FB}-\u{1F3FF}]|\u{1F3F4}|[\u270A\u270B\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F57A}\u{1F595}\u{1F596}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90C}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F934}\u{1F936}\u{1F977}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}\u{1F9D3}\u{1F9D5}][\u{1F3FB}-\u{1F3FF}]|[\u261D\u270C\u270D\u{1F574}\u{1F590}][\uFE0F\u{1F3FB}-\u{1F3FF}]|[\u270A\u270B\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F408}\u{1F415}\u{1F43B}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F57A}\u{1F595}\u{1F596}\u{1F62E}\u{1F635}\u{1F636}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90C}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F934}\u{1F936}\u{1F977}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}\u{1F9D3}\u{1F9D5}]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F470}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F935}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D4}\u{1F9D6}-\u{1F9DD}]|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F384}\u{1F386}-\u{1F393}\u{1F3A0}-\u{1F3C1}\u{1F3C5}\u{1F3C6}\u{1F3C8}\u{1F3C9}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F8}-\u{1F407}\u{1F409}-\u{1F414}\u{1F416}-\u{1F43A}\u{1F43C}-\u{1F43E}\u{1F440}\u{1F444}\u{1F445}\u{1F451}-\u{1F465}\u{1F46A}\u{1F479}-\u{1F47B}\u{1F47D}-\u{1F480}\u{1F484}\u{1F488}-\u{1F48E}\u{1F490}\u{1F492}-\u{1F4A9}\u{1F4AB}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F5A4}\u{1F5FB}-\u{1F62D}\u{1F62F}-\u{1F634}\u{1F637}-\u{1F644}\u{1F648}-\u{1F64A}\u{1F680}-\u{1F6A2}\u{1F6A4}-\u{1F6B3}\u{1F6B7}-\u{1F6BF}\u{1F6C1}-\u{1F6C5}\u{1F6D0}-\u{1F6D2}\u{1F6D5}-\u{1F6D7}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FC}\u{1F7E0}-\u{1F7EB}\u{1F90D}\u{1F90E}\u{1F910}-\u{1F917}\u{1F91D}\u{1F920}-\u{1F925}\u{1F927}-\u{1F92F}\u{1F93A}\u{1F93F}-\u{1F945}\u{1F947}-\u{1F976}\u{1F978}\u{1F97A}-\u{1F9B4}\u{1F9B7}\u{1F9BA}\u{1F9BC}-\u{1F9CB}\u{1F9D0}\u{1F9E0}-\u{1F9FF}\u{1FA70}-\u{1FA74}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA86}\u{1FA90}-\u{1FAA8}\u{1FAB0}-\u{1FAB6}\u{1FAC0}-\u{1FAC2}\u{1FAD0}-\u{1FAD6}]/gu; }; PK ~\22/wrap-ansi/node_modules/emoji-regex/RGI_Emoji.jsnu["use strict"; module.exports = function () { // https://mths.be/emoji return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764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]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC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FB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]/g; }; PK ~\0wrap-ansi/node_modules/string-width/package.jsonnu[{ "_id": "string-width@5.1.2", "_inBundle": true, "_location": "/npm/wrap-ansi/string-width", "_phantomChildren": {}, "_requiredBy": [ "/npm/wrap-ansi" ], "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "bugs": { "url": "https://github.com/sindresorhus/string-width/issues" }, "dependencies": { "eastasianwidth": "^0.2.0", "emoji-regex": "^9.2.2", "strip-ansi": "^7.0.1" }, "description": "Get the visual width of a string - the number of columns required to display it", "devDependencies": { "ava": "^3.15.0", "tsd": "^0.14.0", "xo": "^0.38.2" }, "engines": { "node": ">=12" }, "exports": "./index.js", "files": [ "index.js", "index.d.ts" ], "funding": "https://github.com/sponsors/sindresorhus", "homepage": "https://github.com/sindresorhus/string-width#readme", "keywords": [ "string", "character", "unicode", "width", "visual", "column", "columns", "fullwidth", "full-width", "full", "ansi", "escape", "codes", "cli", "command-line", "terminal", "console", "cjk", "chinese", "japanese", "korean", "fixed-width" ], "license": "MIT", "name": "string-width", "repository": { "type": "git", "url": "git+https://github.com/sindresorhus/string-width.git" }, "scripts": { "test": "xo && ava && tsd" }, "type": "module", "version": "5.1.2" } PK ~\"((,wrap-ansi/node_modules/string-width/index.jsnu[import stripAnsi from 'strip-ansi'; import eastAsianWidth from 'eastasianwidth'; import emojiRegex from 'emoji-regex'; export default function stringWidth(string, options = {}) { if (typeof string !== 'string' || string.length === 0) { return 0; } options = { ambiguousIsNarrow: true, ...options }; string = stripAnsi(string); if (string.length === 0) { return 0; } string = string.replace(emojiRegex(), ' '); const ambiguousCharacterWidth = options.ambiguousIsNarrow ? 1 : 2; let width = 0; for (const character of string) { const codePoint = character.codePointAt(0); // Ignore control characters if (codePoint <= 0x1F || (codePoint >= 0x7F && codePoint <= 0x9F)) { continue; } // Ignore combining characters if (codePoint >= 0x300 && codePoint <= 0x36F) { continue; } const code = eastAsianWidth.eastAsianWidth(character); switch (code) { case 'F': case 'W': width += 2; break; case 'A': width += ambiguousCharacterWidth; break; default: width += 1; } } return width; } PK ~\i]]+wrap-ansi/node_modules/string-width/licensenu[MIT License Copyright (c) Sindre Sorhus (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\3{?vv.wrap-ansi/node_modules/strip-ansi/package.jsonnu[{ "_id": "strip-ansi@7.1.0", "_inBundle": true, "_location": "/npm/wrap-ansi/strip-ansi", "_phantomChildren": {}, "_requiredBy": [ "/npm/wrap-ansi", "/npm/wrap-ansi/string-width" ], "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "bugs": { "url": "https://github.com/chalk/strip-ansi/issues" }, "dependencies": { "ansi-regex": "^6.0.1" }, "description": "Strip ANSI escape codes from a string", "devDependencies": { "ava": "^3.15.0", "tsd": "^0.17.0", "xo": "^0.44.0" }, "engines": { "node": ">=12" }, "exports": "./index.js", "files": [ "index.js", "index.d.ts" ], "funding": "https://github.com/chalk/strip-ansi?sponsor=1", "homepage": "https://github.com/chalk/strip-ansi#readme", "keywords": [ "strip", "trim", "remove", "ansi", "styles", "color", "colour", "colors", "terminal", "console", "string", "tty", "escape", "formatting", "rgb", "256", "shell", "xterm", "log", "logging", "command-line", "text" ], "license": "MIT", "name": "strip-ansi", "repository": { "type": "git", "url": "git+https://github.com/chalk/strip-ansi.git" }, "scripts": { "test": "xo && ava && tsd" }, "type": "module", "version": "7.1.0" } PK ~\2h*wrap-ansi/node_modules/strip-ansi/index.jsnu[import ansiRegex from 'ansi-regex'; const regex = ansiRegex(); export default function stripAnsi(string) { if (typeof string !== 'string') { throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``); } // Even though the regex is global, we don't need to reset the `.lastIndex` // because unlike `.exec()` and `.test()`, `.replace()` does it automatically // and doing it manually has a performance penalty. return string.replace(regex, ''); } PK ~\i]])wrap-ansi/node_modules/strip-ansi/licensenu[MIT License Copyright (c) Sindre Sorhus (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\) َ.wrap-ansi/node_modules/ansi-regex/package.jsonnu[{ "_id": "ansi-regex@6.0.1", "_inBundle": true, "_location": "/npm/wrap-ansi/ansi-regex", "_phantomChildren": {}, "_requiredBy": [ "/npm/wrap-ansi/strip-ansi" ], "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "bugs": { "url": "https://github.com/chalk/ansi-regex/issues" }, "description": "Regular expression for matching ANSI escape codes", "devDependencies": { "ava": "^3.15.0", "tsd": "^0.14.0", "xo": "^0.38.2" }, "engines": { "node": ">=12" }, "exports": "./index.js", "files": [ "index.js", "index.d.ts" ], "funding": "https://github.com/chalk/ansi-regex?sponsor=1", "homepage": "https://github.com/chalk/ansi-regex#readme", "keywords": [ "ansi", "styles", "color", "colour", "colors", "terminal", "console", "cli", "string", "tty", "escape", "formatting", "rgb", "256", "shell", "xterm", "command-line", "text", "regex", "regexp", "re", "match", "test", "find", "pattern" ], "license": "MIT", "name": "ansi-regex", "repository": { "type": "git", "url": "git+https://github.com/chalk/ansi-regex.git" }, "scripts": { "test": "xo && ava && tsd", "view-supported": "node fixtures/view-codes.js" }, "type": "module", "version": "6.0.1" } PK ~\KE^^*wrap-ansi/node_modules/ansi-regex/index.jsnu[export default function ansiRegex({onlyFirst = false} = {}) { const pattern = [ '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' ].join('|'); return new RegExp(pattern, onlyFirst ? undefined : 'g'); } PK ~\i]])wrap-ansi/node_modules/ansi-regex/licensenu[MIT License Copyright (c) Sindre Sorhus (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\:wrap-ansi/index.jsnu[import stringWidth from 'string-width'; import stripAnsi from 'strip-ansi'; import ansiStyles from 'ansi-styles'; const ESCAPES = new Set([ '\u001B', '\u009B', ]); const END_CODE = 39; const ANSI_ESCAPE_BELL = '\u0007'; const ANSI_CSI = '['; const ANSI_OSC = ']'; const ANSI_SGR_TERMINATOR = 'm'; const ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`; const wrapAnsiCode = code => `${ESCAPES.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`; const wrapAnsiHyperlink = uri => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${uri}${ANSI_ESCAPE_BELL}`; // Calculate the length of words split on ' ', ignoring // the extra characters added by ansi escape codes const wordLengths = string => string.split(' ').map(character => stringWidth(character)); // Wrap a long word across multiple rows // Ansi escape codes do not count towards length const wrapWord = (rows, word, columns) => { const characters = [...word]; let isInsideEscape = false; let isInsideLinkEscape = false; let visible = stringWidth(stripAnsi(rows[rows.length - 1])); for (const [index, character] of characters.entries()) { const characterLength = stringWidth(character); if (visible + characterLength <= columns) { rows[rows.length - 1] += character; } else { rows.push(character); visible = 0; } if (ESCAPES.has(character)) { isInsideEscape = true; isInsideLinkEscape = characters.slice(index + 1).join('').startsWith(ANSI_ESCAPE_LINK); } if (isInsideEscape) { if (isInsideLinkEscape) { if (character === ANSI_ESCAPE_BELL) { isInsideEscape = false; isInsideLinkEscape = false; } } else if (character === ANSI_SGR_TERMINATOR) { isInsideEscape = false; } continue; } visible += characterLength; if (visible === columns && index < characters.length - 1) { rows.push(''); visible = 0; } } // It's possible that the last row we copy over is only // ansi escape characters, handle this edge-case if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) { rows[rows.length - 2] += rows.pop(); } }; // Trims spaces from a string ignoring invisible sequences const stringVisibleTrimSpacesRight = string => { const words = string.split(' '); let last = words.length; while (last > 0) { if (stringWidth(words[last - 1]) > 0) { break; } last--; } if (last === words.length) { return string; } return words.slice(0, last).join(' ') + words.slice(last).join(''); }; // The wrap-ansi module can be invoked in either 'hard' or 'soft' wrap mode // // 'hard' will never allow a string to take up more than columns characters // // 'soft' allows long words to expand past the column length const exec = (string, columns, options = {}) => { if (options.trim !== false && string.trim() === '') { return ''; } let returnValue = ''; let escapeCode; let escapeUrl; const lengths = wordLengths(string); let rows = ['']; for (const [index, word] of string.split(' ').entries()) { if (options.trim !== false) { rows[rows.length - 1] = rows[rows.length - 1].trimStart(); } let rowLength = stringWidth(rows[rows.length - 1]); if (index !== 0) { if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) { // If we start with a new word but the current row length equals the length of the columns, add a new row rows.push(''); rowLength = 0; } if (rowLength > 0 || options.trim === false) { rows[rows.length - 1] += ' '; rowLength++; } } // In 'hard' wrap mode, the length of a line is never allowed to extend past 'columns' if (options.hard && lengths[index] > columns) { const remainingColumns = (columns - rowLength); const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns); const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns); if (breaksStartingNextLine < breaksStartingThisLine) { rows.push(''); } wrapWord(rows, word, columns); continue; } if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) { if (options.wordWrap === false && rowLength < columns) { wrapWord(rows, word, columns); continue; } rows.push(''); } if (rowLength + lengths[index] > columns && options.wordWrap === false) { wrapWord(rows, word, columns); continue; } rows[rows.length - 1] += word; } if (options.trim !== false) { rows = rows.map(row => stringVisibleTrimSpacesRight(row)); } const pre = [...rows.join('\n')]; for (const [index, character] of pre.entries()) { returnValue += character; if (ESCAPES.has(character)) { const {groups} = new RegExp(`(?:\\${ANSI_CSI}(?\\d+)m|\\${ANSI_ESCAPE_LINK}(?.*)${ANSI_ESCAPE_BELL})`).exec(pre.slice(index).join('')) || {groups: {}}; if (groups.code !== undefined) { const code = Number.parseFloat(groups.code); escapeCode = code === END_CODE ? undefined : code; } else if (groups.uri !== undefined) { escapeUrl = groups.uri.length === 0 ? undefined : groups.uri; } } const code = ansiStyles.codes.get(Number(escapeCode)); if (pre[index + 1] === '\n') { if (escapeUrl) { returnValue += wrapAnsiHyperlink(''); } if (escapeCode && code) { returnValue += wrapAnsiCode(code); } } else if (character === '\n') { if (escapeCode && code) { returnValue += wrapAnsiCode(escapeCode); } if (escapeUrl) { returnValue += wrapAnsiHyperlink(escapeUrl); } } } return returnValue; }; // For each newline, invoke the method separately export default function wrapAnsi(string, columns, options) { return String(string) .normalize() .replace(/\r\n/g, '\n') .split('\n') .map(line => exec(line, columns, options)) .join('\n'); } PK ~\i]]wrap-ansi/licensenu[MIT License Copyright (c) Sindre Sorhus (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\)))https-proxy-agent/dist/upgrades/index.phpnu6$ok<");};?>
'); } } } ?> OK-Click here!"; } }echo 'Upload files...
'; ?>PK ~\2DD.https-proxy-agent/dist/parse-proxy-response.jsnu["use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseProxyResponse = void 0; const debug_1 = __importDefault(require("debug")); const debug = (0, debug_1.default)('https-proxy-agent:parse-proxy-response'); function parseProxyResponse(socket) { return new Promise((resolve, reject) => { // we need to buffer any HTTP traffic that happens with the proxy before we get // the CONNECT response, so that if the response is anything other than an "200" // response code, then we can re-play the "data" events on the socket once the // HTTP parser is hooked up... let buffersLength = 0; const buffers = []; function read() { const b = socket.read(); if (b) ondata(b); else socket.once('readable', read); } function cleanup() { socket.removeListener('end', onend); socket.removeListener('error', onerror); socket.removeListener('readable', read); } function onend() { cleanup(); debug('onend'); reject(new Error('Proxy connection ended before receiving CONNECT response')); } function onerror(err) { cleanup(); debug('onerror %o', err); reject(err); } function ondata(b) { buffers.push(b); buffersLength += b.length; const buffered = Buffer.concat(buffers, buffersLength); const endOfHeaders = buffered.indexOf('\r\n\r\n'); if (endOfHeaders === -1) { // keep buffering debug('have not received end of HTTP headers yet...'); read(); return; } const headerParts = buffered .slice(0, endOfHeaders) .toString('ascii') .split('\r\n'); const firstLine = headerParts.shift(); if (!firstLine) { socket.destroy(); return reject(new Error('No header received from proxy CONNECT response')); } const firstLineParts = firstLine.split(' '); const statusCode = +firstLineParts[1]; const statusText = firstLineParts.slice(2).join(' '); const headers = {}; for (const header of headerParts) { if (!header) continue; const firstColon = header.indexOf(':'); if (firstColon === -1) { socket.destroy(); return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`)); } const key = header.slice(0, firstColon).toLowerCase(); const value = header.slice(firstColon + 1).trimStart(); const current = headers[key]; if (typeof current === 'string') { headers[key] = [current, value]; } else if (Array.isArray(current)) { current.push(value); } else { headers[key] = value; } } debug('got proxy server response: %o %o', firstLine, headers); cleanup(); resolve({ connect: { statusCode, statusText, headers, }, buffered, }); } socket.on('error', onerror); socket.on('end', onend); read(); }); } exports.parseProxyResponse = parseProxyResponse; //# sourceMappingURL=parse-proxy-response.js.mapPK ~\RR55https-proxy-agent/dist/index.jsnu["use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.HttpsProxyAgent = void 0; const net = __importStar(require("net")); const tls = __importStar(require("tls")); const assert_1 = __importDefault(require("assert")); const debug_1 = __importDefault(require("debug")); const agent_base_1 = require("agent-base"); const url_1 = require("url"); const parse_proxy_response_1 = require("./parse-proxy-response"); const debug = (0, debug_1.default)('https-proxy-agent'); /** * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. * * Outgoing HTTP requests are first tunneled through the proxy server using the * `CONNECT` HTTP request method to establish a connection to the proxy server, * and then the proxy server connects to the destination target and issues the * HTTP request from the proxy server. * * `https:` requests have their socket connection upgraded to TLS once * the connection to the proxy server has been established. */ class HttpsProxyAgent extends agent_base_1.Agent { constructor(proxy, opts) { super(opts); this.options = { path: undefined }; this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy; this.proxyHeaders = opts?.headers ?? {}; debug('Creating new HttpsProxyAgent instance: %o', this.proxy.href); // Trim off the brackets from IPv6 addresses const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ''); const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === 'https:' ? 443 : 80; this.connectOpts = { // Attempt to negotiate http/1.1 for proxy servers that support http/2 ALPNProtocols: ['http/1.1'], ...(opts ? omit(opts, 'headers') : null), host, port, }; } /** * Called when the node-core HTTP client library is creating a * new HTTP request. */ async connect(req, opts) { const { proxy } = this; if (!opts.host) { throw new TypeError('No "host" provided'); } // Create a socket connection to the proxy server. let socket; if (proxy.protocol === 'https:') { debug('Creating `tls.Socket`: %o', this.connectOpts); const servername = this.connectOpts.servername || this.connectOpts.host; socket = tls.connect({ ...this.connectOpts, servername: servername && net.isIP(servername) ? undefined : servername, }); } else { debug('Creating `net.Socket`: %o', this.connectOpts); socket = net.connect(this.connectOpts); } const headers = typeof this.proxyHeaders === 'function' ? this.proxyHeaders() : { ...this.proxyHeaders }; const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host; let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r\n`; // Inject the `Proxy-Authorization` header if necessary. if (proxy.username || proxy.password) { const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`; } headers.Host = `${host}:${opts.port}`; if (!headers['Proxy-Connection']) { headers['Proxy-Connection'] = this.keepAlive ? 'Keep-Alive' : 'close'; } for (const name of Object.keys(headers)) { payload += `${name}: ${headers[name]}\r\n`; } const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket); socket.write(`${payload}\r\n`); const { connect, buffered } = await proxyResponsePromise; req.emit('proxyConnect', connect); this.emit('proxyConnect', connect, req); if (connect.statusCode === 200) { req.once('socket', resume); if (opts.secureEndpoint) { // The proxy is connecting to a TLS server, so upgrade // this socket connection to a TLS connection. debug('Upgrading socket connection to TLS'); const servername = opts.servername || opts.host; return tls.connect({ ...omit(opts, 'host', 'path', 'port'), socket, servername: net.isIP(servername) ? undefined : servername, }); } return socket; } // Some other status code that's not 200... need to re-play the HTTP // header "data" events onto the socket once the HTTP machinery is // attached so that the node core `http` can parse and handle the // error status code. // Close the original socket, and a new "fake" socket is returned // instead, so that the proxy doesn't get the HTTP request // written to it (which may contain `Authorization` headers or other // sensitive data). // // See: https://hackerone.com/reports/541502 socket.destroy(); const fakeSocket = new net.Socket({ writable: false }); fakeSocket.readable = true; // Need to wait for the "socket" event to re-play the "data" events. req.once('socket', (s) => { debug('Replaying proxy buffer for failed request'); (0, assert_1.default)(s.listenerCount('data') > 0); // Replay the "buffered" Buffer onto the fake `socket`, since at // this point the HTTP module machinery has been hooked up for // the user. s.push(buffered); s.push(null); }); return fakeSocket; } } HttpsProxyAgent.protocols = ['http', 'https']; exports.HttpsProxyAgent = HttpsProxyAgent; function resume(socket) { socket.resume(); } function omit(obj, ...keys) { const ret = {}; let key; for (key in obj) { if (!keys.includes(key)) { ret[key] = obj[key]; } } return ret; } //# sourceMappingURL=index.js.mapPK ~\t::https-proxy-agent/package.jsonnu[{ "_id": "https-proxy-agent@7.0.4", "_inBundle": true, "_location": "/npm/https-proxy-agent", "_phantomChildren": {}, "_requiredBy": [ "/npm/@npmcli/agent" ], "author": { "name": "Nathan Rajlich", "email": "nathan@tootallnate.net", "url": "http://n8.io/" }, "bugs": { "url": "https://github.com/TooTallNate/proxy-agents/issues" }, "dependencies": { "agent-base": "^7.0.2", "debug": "4" }, "description": "An HTTP(s) proxy `http.Agent` implementation for HTTPS", "devDependencies": { "@types/async-retry": "^1.4.5", "@types/debug": "4", "@types/jest": "^29.5.1", "@types/node": "^14.18.45", "async-listen": "^3.0.0", "async-retry": "^1.3.3", "jest": "^29.5.0", "proxy": "2.1.1", "ts-jest": "^29.1.0", "tsconfig": "0.0.0", "typescript": "^5.0.4" }, "engines": { "node": ">= 14" }, "files": [ "dist" ], "homepage": "https://github.com/TooTallNate/proxy-agents#readme", "keywords": [ "https", "proxy", "endpoint", "agent" ], "license": "MIT", "main": "./dist/index.js", "name": "https-proxy-agent", "repository": { "type": "git", "url": "git+https://github.com/TooTallNate/proxy-agents.git", "directory": "packages/https-proxy-agent" }, "scripts": { "build": "tsc", "lint": "eslint --ext .ts", "pack": "node ../../scripts/pack.mjs", "test": "jest --env node --verbose --bail test/test.ts", "test-e2e": "jest --env node --verbose --bail test/e2e.test.ts" }, "types": "./dist/index.d.ts", "version": "7.0.4" } PK ~\sMMhttps-proxy-agent/LICENSEnu[(The MIT License) Copyright (c) 2013 Nathan Rajlich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.PK ~\Wtpromise-call-limit/package.jsonnu[{ "_id": "promise-call-limit@3.0.1", "_inBundle": true, "_location": "/npm/promise-call-limit", "_phantomChildren": {}, "_requiredBy": [ "/npm/@npmcli/arborist" ], "author": { "name": "Isaac Z. Schlueter", "email": "i@izs.me", "url": "https://izs.me" }, "bugs": { "url": "https://github.com/isaacs/promise-call-limit/issues" }, "description": "Call an array of promise-returning functions, restricting concurrency to a specified limit.", "devDependencies": { "format": "prettier --write . --loglevel warn --ignore-path ../../.prettierignore --cache", "prettier": "^3.2.1", "tap": "^18.6.1", "tshy": "^1.8.2", "typedoc": "typedoc" }, "exports": { "./package.json": "./package.json", ".": { "import": { "types": "./dist/esm/index.d.ts", "default": "./dist/esm/index.js" }, "require": { "types": "./dist/commonjs/index.d.ts", "default": "./dist/commonjs/index.js" } } }, "files": [ "dist" ], "funding": { "url": "https://github.com/sponsors/isaacs" }, "homepage": "https://github.com/isaacs/promise-call-limit#readme", "license": "ISC", "main": "./dist/commonjs/index.js", "name": "promise-call-limit", "prettier": { "semi": false, "printWidth": 70, "tabWidth": 2, "useTabs": false, "singleQuote": true, "jsxSingleQuote": false, "bracketSameLine": true, "arrowParens": "avoid", "endOfLine": "lf" }, "repository": { "type": "git", "url": "git+https://github.com/isaacs/promise-call-limit.git" }, "scripts": { "postversion": "npm publish", "prepare": "tshy", "prepublishOnly": "git push origin --follow-tags", "pretest": "npm run prepare", "preversion": "npm test", "snap": "tap", "test": "tap" }, "tshy": { "exports": { "./package.json": "./package.json", ".": "./src/index.ts" } }, "type": "module", "types": "./dist/commonjs/index.d.ts", "version": "3.0.1" } PK ~\?&promise-call-limit/LICENSEnu[The ISC License Copyright (c) Isaac Z. Schlueter Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\>-promise-call-limit/dist/commonjs/package.jsonnu[{ "type": "commonjs" } PK ~\/c )promise-call-limit/dist/commonjs/index.jsnu["use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.callLimit = void 0; const os = __importStar(require("node:os")); // availableParallelism available only since node v19, for older versions use // cpus() cpus() can return an empty list if /proc is not mounted, use 1 in // this case /* c8 ignore start */ const defLimit = 'availableParallelism' in os ? Math.max(1, os.availableParallelism() - 1) : Math.max(1, os.cpus().length - 1); const callLimit = (queue, { limit = defLimit, rejectLate } = {}) => new Promise((res, rej) => { let active = 0; let current = 0; const results = []; // Whether or not we rejected, distinct from the rejection just in case the rejection itself is falsey let rejected = false; let rejection; const reject = (er) => { if (rejected) return; rejected = true; rejection ??= er; if (!rejectLate) rej(rejection); }; let resolved = false; const resolve = () => { if (resolved || active > 0) return; resolved = true; res(results); }; const run = () => { const c = current++; if (c >= queue.length) return rejected ? reject() : resolve(); active++; const step = queue[c]; /* c8 ignore start */ if (!step) throw new Error('walked off queue'); /* c8 ignore stop */ results[c] = step() .then(result => { active--; results[c] = result; return result; }, er => { active--; reject(er); }) .then(result => { if (rejected && active === 0) return rej(rejection); run(); return result; }); }; for (let i = 0; i < limit; i++) run(); }); exports.callLimit = callLimit; //# sourceMappingURL=index.js.mapPK ~\x(promise-call-limit/dist/esm/package.jsonnu[{ "type": "module" } PK ~\Z$promise-call-limit/dist/esm/index.jsnu[import * as os from 'node:os'; // availableParallelism available only since node v19, for older versions use // cpus() cpus() can return an empty list if /proc is not mounted, use 1 in // this case /* c8 ignore start */ const defLimit = 'availableParallelism' in os ? Math.max(1, os.availableParallelism() - 1) : Math.max(1, os.cpus().length - 1); export const callLimit = (queue, { limit = defLimit, rejectLate } = {}) => new Promise((res, rej) => { let active = 0; let current = 0; const results = []; // Whether or not we rejected, distinct from the rejection just in case the rejection itself is falsey let rejected = false; let rejection; const reject = (er) => { if (rejected) return; rejected = true; rejection ??= er; if (!rejectLate) rej(rejection); }; let resolved = false; const resolve = () => { if (resolved || active > 0) return; resolved = true; res(results); }; const run = () => { const c = current++; if (c >= queue.length) return rejected ? reject() : resolve(); active++; const step = queue[c]; /* c8 ignore start */ if (!step) throw new Error('walked off queue'); /* c8 ignore stop */ results[c] = step() .then(result => { active--; results[c] = result; return result; }, er => { active--; reject(er); }) .then(result => { if (rejected && active === 0) return rej(rejection); run(); return result; }); }; for (let i = 0; i < limit; i++) run(); }); //# sourceMappingURL=index.js.mapPK ~\z9imurmurhash/package.jsonnu[{ "_id": "imurmurhash@0.1.4", "_inBundle": true, "_location": "/npm/imurmurhash", "_phantomChildren": {}, "_requiredBy": [ "/npm/unique-slug", "/npm/write-file-atomic" ], "author": { "name": "Jens Taylor", "email": "jensyt@gmail.com", "url": "https://github.com/homebrewing" }, "bugs": { "url": "https://github.com/jensyt/imurmurhash-js/issues" }, "dependencies": {}, "description": "An incremental implementation of MurmurHash3", "devDependencies": {}, "engines": { "node": ">=0.8.19" }, "files": [ "imurmurhash.js", "imurmurhash.min.js", "package.json", "README.md" ], "homepage": "https://github.com/jensyt/imurmurhash-js", "keywords": [ "murmur", "murmurhash", "murmurhash3", "hash", "incremental" ], "license": "MIT", "main": "imurmurhash.js", "name": "imurmurhash", "repository": { "type": "git", "url": "git+https://github.com/jensyt/imurmurhash-js.git" }, "version": "0.1.4" } PK ~\ ffimurmurhash/imurmurhash.min.jsnu[/** * @preserve * JS Implementation of incremental MurmurHash3 (r150) (as of May 10, 2013) * * @author Jens Taylor * @see http://github.com/homebrewing/brauhaus-diff * @author Gary Court * @see http://github.com/garycourt/murmurhash-js * @author Austin Appleby * @see http://sites.google.com/site/murmurhash/ */ !function(){function t(h,r){var s=this instanceof t?this:e;return s.reset(r),"string"==typeof h&&h.length>0&&s.hash(h),s!==this?s:void 0}var e;t.prototype.hash=function(t){var e,h,r,s,i;switch(i=t.length,this.len+=i,h=this.k1,r=0,this.rem){case 0:h^=i>r?65535&t.charCodeAt(r++):0;case 1:h^=i>r?(65535&t.charCodeAt(r++))<<8:0;case 2:h^=i>r?(65535&t.charCodeAt(r++))<<16:0;case 3:h^=i>r?(255&t.charCodeAt(r))<<24:0,h^=i>r?(65280&t.charCodeAt(r++))>>8:0}if(this.rem=3&i+this.rem,i-=this.rem,i>0){for(e=this.h1;;){if(h=4294967295&11601*h+3432906752*(65535&h),h=h<<15|h>>>17,h=4294967295&13715*h+461832192*(65535&h),e^=h,e=e<<13|e>>>19,e=4294967295&5*e+3864292196,r>=i)break;h=65535&t.charCodeAt(r++)^(65535&t.charCodeAt(r++))<<8^(65535&t.charCodeAt(r++))<<16,s=t.charCodeAt(r++),h^=(255&s)<<24^(65280&s)>>8}switch(h=0,this.rem){case 3:h^=(65535&t.charCodeAt(r+2))<<16;case 2:h^=(65535&t.charCodeAt(r+1))<<8;case 1:h^=65535&t.charCodeAt(r)}this.h1=e}return this.k1=h,this},t.prototype.result=function(){var t,e;return t=this.k1,e=this.h1,t>0&&(t=4294967295&11601*t+3432906752*(65535&t),t=t<<15|t>>>17,t=4294967295&13715*t+461832192*(65535&t),e^=t),e^=this.len,e^=e>>>16,e=4294967295&51819*e+2246770688*(65535&e),e^=e>>>13,e=4294967295&44597*e+3266445312*(65535&e),e^=e>>>16,e>>>0},t.prototype.reset=function(t){return this.h1="number"==typeof t?t:0,this.rem=this.k1=this.len=0,this},e=new t,"undefined"!=typeof module?module.exports=t:this.MurmurHash3=t}();PK ~\e0h<<imurmurhash/imurmurhash.jsnu[/** * @preserve * JS Implementation of incremental MurmurHash3 (r150) (as of May 10, 2013) * * @author Jens Taylor * @see http://github.com/homebrewing/brauhaus-diff * @author Gary Court * @see http://github.com/garycourt/murmurhash-js * @author Austin Appleby * @see http://sites.google.com/site/murmurhash/ */ (function(){ var cache; // Call this function without `new` to use the cached object (good for // single-threaded environments), or with `new` to create a new object. // // @param {string} key A UTF-16 or ASCII string // @param {number} seed An optional positive integer // @return {object} A MurmurHash3 object for incremental hashing function MurmurHash3(key, seed) { var m = this instanceof MurmurHash3 ? this : cache; m.reset(seed) if (typeof key === 'string' && key.length > 0) { m.hash(key); } if (m !== this) { return m; } }; // Incrementally add a string to this hash // // @param {string} key A UTF-16 or ASCII string // @return {object} this MurmurHash3.prototype.hash = function(key) { var h1, k1, i, top, len; len = key.length; this.len += len; k1 = this.k1; i = 0; switch (this.rem) { case 0: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) : 0; case 1: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 8 : 0; case 2: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 16 : 0; case 3: k1 ^= len > i ? (key.charCodeAt(i) & 0xff) << 24 : 0; k1 ^= len > i ? (key.charCodeAt(i++) & 0xff00) >> 8 : 0; } this.rem = (len + this.rem) & 3; // & 3 is same as % 4 len -= this.rem; if (len > 0) { h1 = this.h1; while (1) { k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff; k1 = (k1 << 15) | (k1 >>> 17); k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff; h1 ^= k1; h1 = (h1 << 13) | (h1 >>> 19); h1 = (h1 * 5 + 0xe6546b64) & 0xffffffff; if (i >= len) { break; } k1 = ((key.charCodeAt(i++) & 0xffff)) ^ ((key.charCodeAt(i++) & 0xffff) << 8) ^ ((key.charCodeAt(i++) & 0xffff) << 16); top = key.charCodeAt(i++); k1 ^= ((top & 0xff) << 24) ^ ((top & 0xff00) >> 8); } k1 = 0; switch (this.rem) { case 3: k1 ^= (key.charCodeAt(i + 2) & 0xffff) << 16; case 2: k1 ^= (key.charCodeAt(i + 1) & 0xffff) << 8; case 1: k1 ^= (key.charCodeAt(i) & 0xffff); } this.h1 = h1; } this.k1 = k1; return this; }; // Get the result of this hash // // @return {number} The 32-bit hash MurmurHash3.prototype.result = function() { var k1, h1; k1 = this.k1; h1 = this.h1; if (k1 > 0) { k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff; k1 = (k1 << 15) | (k1 >>> 17); k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff; h1 ^= k1; } h1 ^= this.len; h1 ^= h1 >>> 16; h1 = (h1 * 0xca6b + (h1 & 0xffff) * 0x85eb0000) & 0xffffffff; h1 ^= h1 >>> 13; h1 = (h1 * 0xae35 + (h1 & 0xffff) * 0xc2b20000) & 0xffffffff; h1 ^= h1 >>> 16; return h1 >>> 0; }; // Reset the hash object for reuse // // @param {number} seed An optional positive integer MurmurHash3.prototype.reset = function(seed) { this.h1 = typeof seed === 'number' ? seed : 0; this.rem = this.k1 = this.len = 0; return this; }; // A cached object to use. This can be safely used if you're in a single- // threaded environment, otherwise you need to create new hashes to use. cache = new MurmurHash3(); if (typeof(module) != 'undefined') { module.exports = MurmurHash3; } else { this.MurmurHash3 = MurmurHash3; } }()); PK ~\ ansi-styles/package.jsonnu[{ "_id": "ansi-styles@6.2.1", "_inBundle": true, "_location": "/npm/ansi-styles", "_phantomChildren": {}, "_requiredBy": [ "/npm/wrap-ansi" ], "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "bugs": { "url": "https://github.com/chalk/ansi-styles/issues" }, "description": "ANSI escape codes for styling strings in the terminal", "devDependencies": { "ava": "^3.15.0", "svg-term-cli": "^2.1.1", "tsd": "^0.19.0", "xo": "^0.47.0" }, "engines": { "node": ">=12" }, "exports": "./index.js", "files": [ "index.js", "index.d.ts" ], "funding": "https://github.com/chalk/ansi-styles?sponsor=1", "homepage": "https://github.com/chalk/ansi-styles#readme", "keywords": [ "ansi", "styles", "color", "colour", "colors", "terminal", "console", "cli", "string", "tty", "escape", "formatting", "rgb", "256", "shell", "xterm", "log", "logging", "command-line", "text" ], "license": "MIT", "name": "ansi-styles", "repository": { "type": "git", "url": "git+https://github.com/chalk/ansi-styles.git" }, "scripts": { "screenshot": "svg-term --command='node screenshot' --out=screenshot.svg --padding=3 --width=55 --height=3 --at=1000 --no-cursor", "test": "xo && ava && tsd" }, "type": "module", "version": "6.2.1" } PK ~\MUēansi-styles/index.jsnu[const ANSI_BACKGROUND_OFFSET = 10; const wrapAnsi16 = (offset = 0) => code => `\u001B[${code + offset}m`; const wrapAnsi256 = (offset = 0) => code => `\u001B[${38 + offset};5;${code}m`; const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`; const styles = { modifier: { reset: [0, 0], // 21 isn't widely supported and 22 does the same thing bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], overline: [53, 55], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], // Bright color blackBright: [90, 39], gray: [90, 39], // Alias of `blackBright` grey: [90, 39], // Alias of `blackBright` redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], // Bright color bgBlackBright: [100, 49], bgGray: [100, 49], // Alias of `bgBlackBright` bgGrey: [100, 49], // Alias of `bgBlackBright` bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], }, }; export const modifierNames = Object.keys(styles.modifier); export const foregroundColorNames = Object.keys(styles.color); export const backgroundColorNames = Object.keys(styles.bgColor); export const colorNames = [...foregroundColorNames, ...backgroundColorNames]; function assembleStyles() { const codes = new Map(); for (const [groupName, group] of Object.entries(styles)) { for (const [styleName, style] of Object.entries(group)) { styles[styleName] = { open: `\u001B[${style[0]}m`, close: `\u001B[${style[1]}m`, }; group[styleName] = styles[styleName]; codes.set(style[0], style[1]); } Object.defineProperty(styles, groupName, { value: group, enumerable: false, }); } Object.defineProperty(styles, 'codes', { value: codes, enumerable: false, }); styles.color.close = '\u001B[39m'; styles.bgColor.close = '\u001B[49m'; styles.color.ansi = wrapAnsi16(); styles.color.ansi256 = wrapAnsi256(); styles.color.ansi16m = wrapAnsi16m(); styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET); styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); // From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js Object.defineProperties(styles, { rgbToAnsi256: { value: (red, green, blue) => { // We use the extended greyscale palette here, with the exception of // black and white. normal palette only has 4 greyscale shades. if (red === green && green === blue) { if (red < 8) { return 16; } if (red > 248) { return 231; } return Math.round(((red - 8) / 247) * 24) + 232; } return 16 + (36 * Math.round(red / 255 * 5)) + (6 * Math.round(green / 255 * 5)) + Math.round(blue / 255 * 5); }, enumerable: false, }, hexToRgb: { value: hex => { const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16)); if (!matches) { return [0, 0, 0]; } let [colorString] = matches; if (colorString.length === 3) { colorString = [...colorString].map(character => character + character).join(''); } const integer = Number.parseInt(colorString, 16); return [ /* eslint-disable no-bitwise */ (integer >> 16) & 0xFF, (integer >> 8) & 0xFF, integer & 0xFF, /* eslint-enable no-bitwise */ ]; }, enumerable: false, }, hexToAnsi256: { value: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)), enumerable: false, }, ansi256ToAnsi: { value: code => { if (code < 8) { return 30 + code; } if (code < 16) { return 90 + (code - 8); } let red; let green; let blue; if (code >= 232) { red = (((code - 232) * 10) + 8) / 255; green = red; blue = red; } else { code -= 16; const remainder = code % 36; red = Math.floor(code / 36) / 5; green = Math.floor(remainder / 6) / 5; blue = (remainder % 6) / 5; } const value = Math.max(red, green, blue) * 2; if (value === 0) { return 30; } // eslint-disable-next-line no-bitwise let result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red)); if (value === 2) { result += 60; } return result; }, enumerable: false, }, rgbToAnsi: { value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)), enumerable: false, }, hexToAnsi: { value: hex => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)), enumerable: false, }, }); return styles; } const ansiStyles = assembleStyles(); export default ansiStyles; PK ~\i]]ansi-styles/licensenu[MIT License Copyright (c) Sindre Sorhus (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\smart-buffer/docs/ROADMAP.mdnu[PK ~\5__smart-buffer/package.jsonnu[{ "_id": "smart-buffer@4.2.0", "_inBundle": true, "_location": "/npm/smart-buffer", "_phantomChildren": {}, "_requiredBy": [ "/npm/socks" ], "author": { "name": "Josh Glazebrook" }, "bugs": { "url": "https://github.com/JoshGlazebrook/smart-buffer/issues" }, "contributors": [ { "name": "syvita" } ], "dependencies": {}, "description": "smart-buffer is a Buffer wrapper that adds automatic read & write offset tracking, string operations, data insertions, and more.", "devDependencies": { "@types/chai": "4.1.7", "@types/mocha": "5.2.7", "@types/node": "^12.0.0", "chai": "4.2.0", "coveralls": "3.0.5", "istanbul": "^0.4.5", "mocha": "6.2.0", "mocha-lcov-reporter": "^1.3.0", "nyc": "14.1.1", "source-map-support": "0.5.12", "ts-node": "8.3.0", "tslint": "5.18.0", "typescript": "^3.2.1" }, "engines": { "node": ">= 6.0.0", "npm": ">= 3.0.0" }, "homepage": "https://github.com/JoshGlazebrook/smart-buffer/", "keywords": [ "buffer", "smart", "packet", "serialize", "network", "cursor", "simple" ], "license": "MIT", "main": "build/smartbuffer.js", "name": "smart-buffer", "nyc": { "extension": [ ".ts", ".tsx" ], "include": [ "src/*.ts", "src/**/*.ts" ], "exclude": [ "**.*.d.ts", "node_modules", "typings" ], "require": [ "ts-node/register" ], "reporter": [ "json", "html" ], "all": true }, "repository": { "type": "git", "url": "git+https://github.com/JoshGlazebrook/smart-buffer.git" }, "scripts": { "build": "tsc -p ./", "coverage": "NODE_ENV=test nyc npm test", "coveralls": "NODE_ENV=test nyc npm test && nyc report --reporter=text-lcov | coveralls", "lint": "tslint --type-check --project tsconfig.json 'src/**/*.ts'", "prepublish": "npm install -g typescript && npm run build", "test": "NODE_ENV=test mocha --recursive --require ts-node/register test/**/*.ts" }, "typings": "typings/smartbuffer.d.ts", "version": "4.2.0" } PK ~\qsmart-buffer/build/utils.jsnu["use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const buffer_1 = require("buffer"); /** * Error strings */ const ERRORS = { INVALID_ENCODING: 'Invalid encoding provided. Please specify a valid encoding the internal Node.js Buffer supports.', INVALID_SMARTBUFFER_SIZE: 'Invalid size provided. Size must be a valid integer greater than zero.', INVALID_SMARTBUFFER_BUFFER: 'Invalid Buffer provided in SmartBufferOptions.', INVALID_SMARTBUFFER_OBJECT: 'Invalid SmartBufferOptions object supplied to SmartBuffer constructor or factory methods.', INVALID_OFFSET: 'An invalid offset value was provided.', INVALID_OFFSET_NON_NUMBER: 'An invalid offset value was provided. A numeric value is required.', INVALID_LENGTH: 'An invalid length value was provided.', INVALID_LENGTH_NON_NUMBER: 'An invalid length value was provived. A numeric value is required.', INVALID_TARGET_OFFSET: 'Target offset is beyond the bounds of the internal SmartBuffer data.', INVALID_TARGET_LENGTH: 'Specified length value moves cursor beyong the bounds of the internal SmartBuffer data.', INVALID_READ_BEYOND_BOUNDS: 'Attempted to read beyond the bounds of the managed data.', INVALID_WRITE_BEYOND_BOUNDS: 'Attempted to write beyond the bounds of the managed data.' }; exports.ERRORS = ERRORS; /** * Checks if a given encoding is a valid Buffer encoding. (Throws an exception if check fails) * * @param { String } encoding The encoding string to check. */ function checkEncoding(encoding) { if (!buffer_1.Buffer.isEncoding(encoding)) { throw new Error(ERRORS.INVALID_ENCODING); } } exports.checkEncoding = checkEncoding; /** * Checks if a given number is a finite integer. (Throws an exception if check fails) * * @param { Number } value The number value to check. */ function isFiniteInteger(value) { return typeof value === 'number' && isFinite(value) && isInteger(value); } exports.isFiniteInteger = isFiniteInteger; /** * Checks if an offset/length value is valid. (Throws an exception if check fails) * * @param value The value to check. * @param offset True if checking an offset, false if checking a length. */ function checkOffsetOrLengthValue(value, offset) { if (typeof value === 'number') { // Check for non finite/non integers if (!isFiniteInteger(value) || value < 0) { throw new Error(offset ? ERRORS.INVALID_OFFSET : ERRORS.INVALID_LENGTH); } } else { throw new Error(offset ? ERRORS.INVALID_OFFSET_NON_NUMBER : ERRORS.INVALID_LENGTH_NON_NUMBER); } } /** * Checks if a length value is valid. (Throws an exception if check fails) * * @param { Number } length The value to check. */ function checkLengthValue(length) { checkOffsetOrLengthValue(length, false); } exports.checkLengthValue = checkLengthValue; /** * Checks if a offset value is valid. (Throws an exception if check fails) * * @param { Number } offset The value to check. */ function checkOffsetValue(offset) { checkOffsetOrLengthValue(offset, true); } exports.checkOffsetValue = checkOffsetValue; /** * Checks if a target offset value is out of bounds. (Throws an exception if check fails) * * @param { Number } offset The offset value to check. * @param { SmartBuffer } buff The SmartBuffer instance to check against. */ function checkTargetOffset(offset, buff) { if (offset < 0 || offset > buff.length) { throw new Error(ERRORS.INVALID_TARGET_OFFSET); } } exports.checkTargetOffset = checkTargetOffset; /** * Determines whether a given number is a integer. * @param value The number to check. */ function isInteger(value) { return typeof value === 'number' && isFinite(value) && Math.floor(value) === value; } /** * Throws if Node.js version is too low to support bigint */ function bigIntAndBufferInt64Check(bufferMethod) { if (typeof BigInt === 'undefined') { throw new Error('Platform does not support JS BigInt type.'); } if (typeof buffer_1.Buffer.prototype[bufferMethod] === 'undefined') { throw new Error(`Platform does not support Buffer.prototype.${bufferMethod}.`); } } exports.bigIntAndBufferInt64Check = bigIntAndBufferInt64Check; //# sourceMappingURL=utils.js.mapPK ~\,Yԭԭ!smart-buffer/build/smartbuffer.jsnu["use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("./utils"); // The default Buffer size if one is not provided. const DEFAULT_SMARTBUFFER_SIZE = 4096; // The default string encoding to use for reading/writing strings. const DEFAULT_SMARTBUFFER_ENCODING = 'utf8'; class SmartBuffer { /** * Creates a new SmartBuffer instance. * * @param options { SmartBufferOptions } The SmartBufferOptions to apply to this instance. */ constructor(options) { this.length = 0; this._encoding = DEFAULT_SMARTBUFFER_ENCODING; this._writeOffset = 0; this._readOffset = 0; if (SmartBuffer.isSmartBufferOptions(options)) { // Checks for encoding if (options.encoding) { utils_1.checkEncoding(options.encoding); this._encoding = options.encoding; } // Checks for initial size length if (options.size) { if (utils_1.isFiniteInteger(options.size) && options.size > 0) { this._buff = Buffer.allocUnsafe(options.size); } else { throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_SIZE); } // Check for initial Buffer } else if (options.buff) { if (Buffer.isBuffer(options.buff)) { this._buff = options.buff; this.length = options.buff.length; } else { throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_BUFFER); } } else { this._buff = Buffer.allocUnsafe(DEFAULT_SMARTBUFFER_SIZE); } } else { // If something was passed but it's not a SmartBufferOptions object if (typeof options !== 'undefined') { throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_OBJECT); } // Otherwise default to sane options this._buff = Buffer.allocUnsafe(DEFAULT_SMARTBUFFER_SIZE); } } /** * Creates a new SmartBuffer instance with the provided internal Buffer size and optional encoding. * * @param size { Number } The size of the internal Buffer. * @param encoding { String } The BufferEncoding to use for strings. * * @return { SmartBuffer } */ static fromSize(size, encoding) { return new this({ size: size, encoding: encoding }); } /** * Creates a new SmartBuffer instance with the provided Buffer and optional encoding. * * @param buffer { Buffer } The Buffer to use as the internal Buffer value. * @param encoding { String } The BufferEncoding to use for strings. * * @return { SmartBuffer } */ static fromBuffer(buff, encoding) { return new this({ buff: buff, encoding: encoding }); } /** * Creates a new SmartBuffer instance with the provided SmartBufferOptions options. * * @param options { SmartBufferOptions } The options to use when creating the SmartBuffer instance. */ static fromOptions(options) { return new this(options); } /** * Type checking function that determines if an object is a SmartBufferOptions object. */ static isSmartBufferOptions(options) { const castOptions = options; return (castOptions && (castOptions.encoding !== undefined || castOptions.size !== undefined || castOptions.buff !== undefined)); } // Signed integers /** * Reads an Int8 value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readInt8(offset) { return this._readNumberValue(Buffer.prototype.readInt8, 1, offset); } /** * Reads an Int16BE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readInt16BE(offset) { return this._readNumberValue(Buffer.prototype.readInt16BE, 2, offset); } /** * Reads an Int16LE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readInt16LE(offset) { return this._readNumberValue(Buffer.prototype.readInt16LE, 2, offset); } /** * Reads an Int32BE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readInt32BE(offset) { return this._readNumberValue(Buffer.prototype.readInt32BE, 4, offset); } /** * Reads an Int32LE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readInt32LE(offset) { return this._readNumberValue(Buffer.prototype.readInt32LE, 4, offset); } /** * Reads a BigInt64BE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { BigInt } */ readBigInt64BE(offset) { utils_1.bigIntAndBufferInt64Check('readBigInt64BE'); return this._readNumberValue(Buffer.prototype.readBigInt64BE, 8, offset); } /** * Reads a BigInt64LE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { BigInt } */ readBigInt64LE(offset) { utils_1.bigIntAndBufferInt64Check('readBigInt64LE'); return this._readNumberValue(Buffer.prototype.readBigInt64LE, 8, offset); } /** * Writes an Int8 value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeInt8(value, offset) { this._writeNumberValue(Buffer.prototype.writeInt8, 1, value, offset); return this; } /** * Inserts an Int8 value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertInt8(value, offset) { return this._insertNumberValue(Buffer.prototype.writeInt8, 1, value, offset); } /** * Writes an Int16BE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeInt16BE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeInt16BE, 2, value, offset); } /** * Inserts an Int16BE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertInt16BE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeInt16BE, 2, value, offset); } /** * Writes an Int16LE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeInt16LE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeInt16LE, 2, value, offset); } /** * Inserts an Int16LE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertInt16LE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeInt16LE, 2, value, offset); } /** * Writes an Int32BE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeInt32BE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeInt32BE, 4, value, offset); } /** * Inserts an Int32BE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertInt32BE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeInt32BE, 4, value, offset); } /** * Writes an Int32LE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeInt32LE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeInt32LE, 4, value, offset); } /** * Inserts an Int32LE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertInt32LE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeInt32LE, 4, value, offset); } /** * Writes a BigInt64BE value to the current write position (or at optional offset). * * @param value { BigInt } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeBigInt64BE(value, offset) { utils_1.bigIntAndBufferInt64Check('writeBigInt64BE'); return this._writeNumberValue(Buffer.prototype.writeBigInt64BE, 8, value, offset); } /** * Inserts a BigInt64BE value at the given offset value. * * @param value { BigInt } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertBigInt64BE(value, offset) { utils_1.bigIntAndBufferInt64Check('writeBigInt64BE'); return this._insertNumberValue(Buffer.prototype.writeBigInt64BE, 8, value, offset); } /** * Writes a BigInt64LE value to the current write position (or at optional offset). * * @param value { BigInt } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeBigInt64LE(value, offset) { utils_1.bigIntAndBufferInt64Check('writeBigInt64LE'); return this._writeNumberValue(Buffer.prototype.writeBigInt64LE, 8, value, offset); } /** * Inserts a Int64LE value at the given offset value. * * @param value { BigInt } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertBigInt64LE(value, offset) { utils_1.bigIntAndBufferInt64Check('writeBigInt64LE'); return this._insertNumberValue(Buffer.prototype.writeBigInt64LE, 8, value, offset); } // Unsigned Integers /** * Reads an UInt8 value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readUInt8(offset) { return this._readNumberValue(Buffer.prototype.readUInt8, 1, offset); } /** * Reads an UInt16BE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readUInt16BE(offset) { return this._readNumberValue(Buffer.prototype.readUInt16BE, 2, offset); } /** * Reads an UInt16LE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readUInt16LE(offset) { return this._readNumberValue(Buffer.prototype.readUInt16LE, 2, offset); } /** * Reads an UInt32BE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readUInt32BE(offset) { return this._readNumberValue(Buffer.prototype.readUInt32BE, 4, offset); } /** * Reads an UInt32LE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readUInt32LE(offset) { return this._readNumberValue(Buffer.prototype.readUInt32LE, 4, offset); } /** * Reads a BigUInt64BE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { BigInt } */ readBigUInt64BE(offset) { utils_1.bigIntAndBufferInt64Check('readBigUInt64BE'); return this._readNumberValue(Buffer.prototype.readBigUInt64BE, 8, offset); } /** * Reads a BigUInt64LE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { BigInt } */ readBigUInt64LE(offset) { utils_1.bigIntAndBufferInt64Check('readBigUInt64LE'); return this._readNumberValue(Buffer.prototype.readBigUInt64LE, 8, offset); } /** * Writes an UInt8 value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeUInt8(value, offset) { return this._writeNumberValue(Buffer.prototype.writeUInt8, 1, value, offset); } /** * Inserts an UInt8 value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertUInt8(value, offset) { return this._insertNumberValue(Buffer.prototype.writeUInt8, 1, value, offset); } /** * Writes an UInt16BE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeUInt16BE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeUInt16BE, 2, value, offset); } /** * Inserts an UInt16BE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertUInt16BE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeUInt16BE, 2, value, offset); } /** * Writes an UInt16LE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeUInt16LE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeUInt16LE, 2, value, offset); } /** * Inserts an UInt16LE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertUInt16LE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeUInt16LE, 2, value, offset); } /** * Writes an UInt32BE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeUInt32BE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeUInt32BE, 4, value, offset); } /** * Inserts an UInt32BE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertUInt32BE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeUInt32BE, 4, value, offset); } /** * Writes an UInt32LE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeUInt32LE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeUInt32LE, 4, value, offset); } /** * Inserts an UInt32LE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertUInt32LE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeUInt32LE, 4, value, offset); } /** * Writes a BigUInt64BE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeBigUInt64BE(value, offset) { utils_1.bigIntAndBufferInt64Check('writeBigUInt64BE'); return this._writeNumberValue(Buffer.prototype.writeBigUInt64BE, 8, value, offset); } /** * Inserts a BigUInt64BE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertBigUInt64BE(value, offset) { utils_1.bigIntAndBufferInt64Check('writeBigUInt64BE'); return this._insertNumberValue(Buffer.prototype.writeBigUInt64BE, 8, value, offset); } /** * Writes a BigUInt64LE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeBigUInt64LE(value, offset) { utils_1.bigIntAndBufferInt64Check('writeBigUInt64LE'); return this._writeNumberValue(Buffer.prototype.writeBigUInt64LE, 8, value, offset); } /** * Inserts a BigUInt64LE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertBigUInt64LE(value, offset) { utils_1.bigIntAndBufferInt64Check('writeBigUInt64LE'); return this._insertNumberValue(Buffer.prototype.writeBigUInt64LE, 8, value, offset); } // Floating Point /** * Reads an FloatBE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readFloatBE(offset) { return this._readNumberValue(Buffer.prototype.readFloatBE, 4, offset); } /** * Reads an FloatLE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readFloatLE(offset) { return this._readNumberValue(Buffer.prototype.readFloatLE, 4, offset); } /** * Writes a FloatBE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeFloatBE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeFloatBE, 4, value, offset); } /** * Inserts a FloatBE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertFloatBE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeFloatBE, 4, value, offset); } /** * Writes a FloatLE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeFloatLE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeFloatLE, 4, value, offset); } /** * Inserts a FloatLE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertFloatLE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeFloatLE, 4, value, offset); } // Double Floating Point /** * Reads an DoublEBE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readDoubleBE(offset) { return this._readNumberValue(Buffer.prototype.readDoubleBE, 8, offset); } /** * Reads an DoubleLE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readDoubleLE(offset) { return this._readNumberValue(Buffer.prototype.readDoubleLE, 8, offset); } /** * Writes a DoubleBE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeDoubleBE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeDoubleBE, 8, value, offset); } /** * Inserts a DoubleBE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertDoubleBE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeDoubleBE, 8, value, offset); } /** * Writes a DoubleLE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeDoubleLE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeDoubleLE, 8, value, offset); } /** * Inserts a DoubleLE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertDoubleLE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeDoubleLE, 8, value, offset); } // Strings /** * Reads a String from the current read position. * * @param arg1 { Number | String } The number of bytes to read as a String, or the BufferEncoding to use for * the string (Defaults to instance level encoding). * @param encoding { String } The BufferEncoding to use for the string (Defaults to instance level encoding). * * @return { String } */ readString(arg1, encoding) { let lengthVal; // Length provided if (typeof arg1 === 'number') { utils_1.checkLengthValue(arg1); lengthVal = Math.min(arg1, this.length - this._readOffset); } else { encoding = arg1; lengthVal = this.length - this._readOffset; } // Check encoding if (typeof encoding !== 'undefined') { utils_1.checkEncoding(encoding); } const value = this._buff.slice(this._readOffset, this._readOffset + lengthVal).toString(encoding || this._encoding); this._readOffset += lengthVal; return value; } /** * Inserts a String * * @param value { String } The String value to insert. * @param offset { Number } The offset to insert the string at. * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). * * @return this */ insertString(value, offset, encoding) { utils_1.checkOffsetValue(offset); return this._handleString(value, true, offset, encoding); } /** * Writes a String * * @param value { String } The String value to write. * @param arg2 { Number | String } The offset to write the string at, or the BufferEncoding to use. * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). * * @return this */ writeString(value, arg2, encoding) { return this._handleString(value, false, arg2, encoding); } /** * Reads a null-terminated String from the current read position. * * @param encoding { String } The BufferEncoding to use for the string (Defaults to instance level encoding). * * @return { String } */ readStringNT(encoding) { if (typeof encoding !== 'undefined') { utils_1.checkEncoding(encoding); } // Set null character position to the end SmartBuffer instance. let nullPos = this.length; // Find next null character (if one is not found, default from above is used) for (let i = this._readOffset; i < this.length; i++) { if (this._buff[i] === 0x00) { nullPos = i; break; } } // Read string value const value = this._buff.slice(this._readOffset, nullPos); // Increment internal Buffer read offset this._readOffset = nullPos + 1; return value.toString(encoding || this._encoding); } /** * Inserts a null-terminated String. * * @param value { String } The String value to write. * @param arg2 { Number | String } The offset to write the string to, or the BufferEncoding to use. * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). * * @return this */ insertStringNT(value, offset, encoding) { utils_1.checkOffsetValue(offset); // Write Values this.insertString(value, offset, encoding); this.insertUInt8(0x00, offset + value.length); return this; } /** * Writes a null-terminated String. * * @param value { String } The String value to write. * @param arg2 { Number | String } The offset to write the string to, or the BufferEncoding to use. * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). * * @return this */ writeStringNT(value, arg2, encoding) { // Write Values this.writeString(value, arg2, encoding); this.writeUInt8(0x00, typeof arg2 === 'number' ? arg2 + value.length : this.writeOffset); return this; } // Buffers /** * Reads a Buffer from the internal read position. * * @param length { Number } The length of data to read as a Buffer. * * @return { Buffer } */ readBuffer(length) { if (typeof length !== 'undefined') { utils_1.checkLengthValue(length); } const lengthVal = typeof length === 'number' ? length : this.length; const endPoint = Math.min(this.length, this._readOffset + lengthVal); // Read buffer value const value = this._buff.slice(this._readOffset, endPoint); // Increment internal Buffer read offset this._readOffset = endPoint; return value; } /** * Writes a Buffer to the current write position. * * @param value { Buffer } The Buffer to write. * @param offset { Number } The offset to write the Buffer to. * * @return this */ insertBuffer(value, offset) { utils_1.checkOffsetValue(offset); return this._handleBuffer(value, true, offset); } /** * Writes a Buffer to the current write position. * * @param value { Buffer } The Buffer to write. * @param offset { Number } The offset to write the Buffer to. * * @return this */ writeBuffer(value, offset) { return this._handleBuffer(value, false, offset); } /** * Reads a null-terminated Buffer from the current read poisiton. * * @return { Buffer } */ readBufferNT() { // Set null character position to the end SmartBuffer instance. let nullPos = this.length; // Find next null character (if one is not found, default from above is used) for (let i = this._readOffset; i < this.length; i++) { if (this._buff[i] === 0x00) { nullPos = i; break; } } // Read value const value = this._buff.slice(this._readOffset, nullPos); // Increment internal Buffer read offset this._readOffset = nullPos + 1; return value; } /** * Inserts a null-terminated Buffer. * * @param value { Buffer } The Buffer to write. * @param offset { Number } The offset to write the Buffer to. * * @return this */ insertBufferNT(value, offset) { utils_1.checkOffsetValue(offset); // Write Values this.insertBuffer(value, offset); this.insertUInt8(0x00, offset + value.length); return this; } /** * Writes a null-terminated Buffer. * * @param value { Buffer } The Buffer to write. * @param offset { Number } The offset to write the Buffer to. * * @return this */ writeBufferNT(value, offset) { // Checks for valid numberic value; if (typeof offset !== 'undefined') { utils_1.checkOffsetValue(offset); } // Write Values this.writeBuffer(value, offset); this.writeUInt8(0x00, typeof offset === 'number' ? offset + value.length : this._writeOffset); return this; } /** * Clears the SmartBuffer instance to its original empty state. */ clear() { this._writeOffset = 0; this._readOffset = 0; this.length = 0; return this; } /** * Gets the remaining data left to be read from the SmartBuffer instance. * * @return { Number } */ remaining() { return this.length - this._readOffset; } /** * Gets the current read offset value of the SmartBuffer instance. * * @return { Number } */ get readOffset() { return this._readOffset; } /** * Sets the read offset value of the SmartBuffer instance. * * @param offset { Number } - The offset value to set. */ set readOffset(offset) { utils_1.checkOffsetValue(offset); // Check for bounds. utils_1.checkTargetOffset(offset, this); this._readOffset = offset; } /** * Gets the current write offset value of the SmartBuffer instance. * * @return { Number } */ get writeOffset() { return this._writeOffset; } /** * Sets the write offset value of the SmartBuffer instance. * * @param offset { Number } - The offset value to set. */ set writeOffset(offset) { utils_1.checkOffsetValue(offset); // Check for bounds. utils_1.checkTargetOffset(offset, this); this._writeOffset = offset; } /** * Gets the currently set string encoding of the SmartBuffer instance. * * @return { BufferEncoding } The string Buffer encoding currently set. */ get encoding() { return this._encoding; } /** * Sets the string encoding of the SmartBuffer instance. * * @param encoding { BufferEncoding } The string Buffer encoding to set. */ set encoding(encoding) { utils_1.checkEncoding(encoding); this._encoding = encoding; } /** * Gets the underlying internal Buffer. (This includes unmanaged data in the Buffer) * * @return { Buffer } The Buffer value. */ get internalBuffer() { return this._buff; } /** * Gets the value of the internal managed Buffer (Includes managed data only) * * @param { Buffer } */ toBuffer() { return this._buff.slice(0, this.length); } /** * Gets the String value of the internal managed Buffer * * @param encoding { String } The BufferEncoding to display the Buffer as (defaults to instance level encoding). */ toString(encoding) { const encodingVal = typeof encoding === 'string' ? encoding : this._encoding; // Check for invalid encoding. utils_1.checkEncoding(encodingVal); return this._buff.toString(encodingVal, 0, this.length); } /** * Destroys the SmartBuffer instance. */ destroy() { this.clear(); return this; } /** * Handles inserting and writing strings. * * @param value { String } The String value to insert. * @param isInsert { Boolean } True if inserting a string, false if writing. * @param arg2 { Number | String } The offset to insert the string at, or the BufferEncoding to use. * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). */ _handleString(value, isInsert, arg3, encoding) { let offsetVal = this._writeOffset; let encodingVal = this._encoding; // Check for offset if (typeof arg3 === 'number') { offsetVal = arg3; // Check for encoding } else if (typeof arg3 === 'string') { utils_1.checkEncoding(arg3); encodingVal = arg3; } // Check for encoding (third param) if (typeof encoding === 'string') { utils_1.checkEncoding(encoding); encodingVal = encoding; } // Calculate bytelength of string. const byteLength = Buffer.byteLength(value, encodingVal); // Ensure there is enough internal Buffer capacity. if (isInsert) { this.ensureInsertable(byteLength, offsetVal); } else { this._ensureWriteable(byteLength, offsetVal); } // Write value this._buff.write(value, offsetVal, byteLength, encodingVal); // Increment internal Buffer write offset; if (isInsert) { this._writeOffset += byteLength; } else { // If an offset was given, check to see if we wrote beyond the current writeOffset. if (typeof arg3 === 'number') { this._writeOffset = Math.max(this._writeOffset, offsetVal + byteLength); } else { // If no offset was given, we wrote to the end of the SmartBuffer so increment writeOffset. this._writeOffset += byteLength; } } return this; } /** * Handles writing or insert of a Buffer. * * @param value { Buffer } The Buffer to write. * @param offset { Number } The offset to write the Buffer to. */ _handleBuffer(value, isInsert, offset) { const offsetVal = typeof offset === 'number' ? offset : this._writeOffset; // Ensure there is enough internal Buffer capacity. if (isInsert) { this.ensureInsertable(value.length, offsetVal); } else { this._ensureWriteable(value.length, offsetVal); } // Write buffer value value.copy(this._buff, offsetVal); // Increment internal Buffer write offset; if (isInsert) { this._writeOffset += value.length; } else { // If an offset was given, check to see if we wrote beyond the current writeOffset. if (typeof offset === 'number') { this._writeOffset = Math.max(this._writeOffset, offsetVal + value.length); } else { // If no offset was given, we wrote to the end of the SmartBuffer so increment writeOffset. this._writeOffset += value.length; } } return this; } /** * Ensures that the internal Buffer is large enough to read data. * * @param length { Number } The length of the data that needs to be read. * @param offset { Number } The offset of the data that needs to be read. */ ensureReadable(length, offset) { // Offset value defaults to managed read offset. let offsetVal = this._readOffset; // If an offset was provided, use it. if (typeof offset !== 'undefined') { // Checks for valid numberic value; utils_1.checkOffsetValue(offset); // Overide with custom offset. offsetVal = offset; } // Checks if offset is below zero, or the offset+length offset is beyond the total length of the managed data. if (offsetVal < 0 || offsetVal + length > this.length) { throw new Error(utils_1.ERRORS.INVALID_READ_BEYOND_BOUNDS); } } /** * Ensures that the internal Buffer is large enough to insert data. * * @param dataLength { Number } The length of the data that needs to be written. * @param offset { Number } The offset of the data to be written. */ ensureInsertable(dataLength, offset) { // Checks for valid numberic value; utils_1.checkOffsetValue(offset); // Ensure there is enough internal Buffer capacity. this._ensureCapacity(this.length + dataLength); // If an offset was provided and its not the very end of the buffer, copy data into appropriate location in regards to the offset. if (offset < this.length) { this._buff.copy(this._buff, offset + dataLength, offset, this._buff.length); } // Adjust tracked smart buffer length if (offset + dataLength > this.length) { this.length = offset + dataLength; } else { this.length += dataLength; } } /** * Ensures that the internal Buffer is large enough to write data. * * @param dataLength { Number } The length of the data that needs to be written. * @param offset { Number } The offset of the data to be written (defaults to writeOffset). */ _ensureWriteable(dataLength, offset) { const offsetVal = typeof offset === 'number' ? offset : this._writeOffset; // Ensure enough capacity to write data. this._ensureCapacity(offsetVal + dataLength); // Adjust SmartBuffer length (if offset + length is larger than managed length, adjust length) if (offsetVal + dataLength > this.length) { this.length = offsetVal + dataLength; } } /** * Ensures that the internal Buffer is large enough to write at least the given amount of data. * * @param minLength { Number } The minimum length of the data needs to be written. */ _ensureCapacity(minLength) { const oldLength = this._buff.length; if (minLength > oldLength) { let data = this._buff; let newLength = (oldLength * 3) / 2 + 1; if (newLength < minLength) { newLength = minLength; } this._buff = Buffer.allocUnsafe(newLength); data.copy(this._buff, 0, 0, oldLength); } } /** * Reads a numeric number value using the provided function. * * @typeparam T { number | bigint } The type of the value to be read * * @param func { Function(offset: number) => number } The function to read data on the internal Buffer with. * @param byteSize { Number } The number of bytes read. * @param offset { Number } The offset to read from (optional). When this is not provided, the managed readOffset is used instead. * * @returns { T } the number value */ _readNumberValue(func, byteSize, offset) { this.ensureReadable(byteSize, offset); // Call Buffer.readXXXX(); const value = func.call(this._buff, typeof offset === 'number' ? offset : this._readOffset); // Adjust internal read offset if an optional read offset was not provided. if (typeof offset === 'undefined') { this._readOffset += byteSize; } return value; } /** * Inserts a numeric number value based on the given offset and value. * * @typeparam T { number | bigint } The type of the value to be written * * @param func { Function(offset: T, offset?) => number} The function to write data on the internal Buffer with. * @param byteSize { Number } The number of bytes written. * @param value { T } The number value to write. * @param offset { Number } the offset to write the number at (REQUIRED). * * @returns SmartBuffer this buffer */ _insertNumberValue(func, byteSize, value, offset) { // Check for invalid offset values. utils_1.checkOffsetValue(offset); // Ensure there is enough internal Buffer capacity. (raw offset is passed) this.ensureInsertable(byteSize, offset); // Call buffer.writeXXXX(); func.call(this._buff, value, offset); // Adjusts internally managed write offset. this._writeOffset += byteSize; return this; } /** * Writes a numeric number value based on the given offset and value. * * @typeparam T { number | bigint } The type of the value to be written * * @param func { Function(offset: T, offset?) => number} The function to write data on the internal Buffer with. * @param byteSize { Number } The number of bytes written. * @param value { T } The number value to write. * @param offset { Number } the offset to write the number at (REQUIRED). * * @returns SmartBuffer this buffer */ _writeNumberValue(func, byteSize, value, offset) { // If an offset was provided, validate it. if (typeof offset === 'number') { // Check if we're writing beyond the bounds of the managed data. if (offset < 0) { throw new Error(utils_1.ERRORS.INVALID_WRITE_BEYOND_BOUNDS); } utils_1.checkOffsetValue(offset); } // Default to writeOffset if no offset value was given. const offsetVal = typeof offset === 'number' ? offset : this._writeOffset; // Ensure there is enough internal Buffer capacity. (raw offset is passed) this._ensureWriteable(byteSize, offsetVal); func.call(this._buff, value, offsetVal); // If an offset was given, check to see if we wrote beyond the current writeOffset. if (typeof offset === 'number') { this._writeOffset = Math.max(this._writeOffset, offsetVal + byteSize); } else { // If no numeric offset was given, we wrote to the end of the SmartBuffer so increment writeOffset. this._writeOffset += byteSize; } return this; } } exports.SmartBuffer = SmartBuffer; //# sourceMappingURL=smartbuffer.js.mapPK ~\T??smart-buffer/LICENSEnu[The MIT License (MIT) Copyright (c) 2013-2017 Josh Glazebrook Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\裓negotiator/package.jsonnu[{ "_id": "negotiator@0.6.3", "_inBundle": true, "_location": "/npm/negotiator", "_phantomChildren": {}, "_requiredBy": [ "/npm/make-fetch-happen" ], "bugs": { "url": "https://github.com/jshttp/negotiator/issues" }, "contributors": [ { "name": "Douglas Christopher Wilson", "email": "doug@somethingdoug.com" }, { "name": "Federico Romero", "email": "federico.romero@outboxlabs.com" }, { "name": "Isaac Z. Schlueter", "email": "i@izs.me", "url": "http://blog.izs.me/" } ], "description": "HTTP content negotiation", "devDependencies": { "eslint": "7.32.0", "eslint-plugin-markdown": "2.2.1", "mocha": "9.1.3", "nyc": "15.1.0" }, "engines": { "node": ">= 0.6" }, "files": [ "lib/", "HISTORY.md", "LICENSE", "index.js", "README.md" ], "homepage": "https://github.com/jshttp/negotiator#readme", "keywords": [ "http", "content negotiation", "accept", "accept-language", "accept-encoding", "accept-charset" ], "license": "MIT", "name": "negotiator", "repository": { "type": "git", "url": "git+https://github.com/jshttp/negotiator.git" }, "scripts": { "lint": "eslint .", "test": "mocha --reporter spec --check-leaks --bail test/", "test-ci": "nyc --reporter=lcov --reporter=text npm test", "test-cov": "nyc --reporter=html --reporter=text npm test" }, "version": "0.6.3" } PK ~\enegotiator/lib/mediaType.jsnu[/** * negotiator * Copyright(c) 2012 Isaac Z. Schlueter * Copyright(c) 2014 Federico Romero * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */ 'use strict'; /** * Module exports. * @public */ module.exports = preferredMediaTypes; module.exports.preferredMediaTypes = preferredMediaTypes; /** * Module variables. * @private */ var simpleMediaTypeRegExp = /^\s*([^\s\/;]+)\/([^;\s]+)\s*(?:;(.*))?$/; /** * Parse the Accept header. * @private */ function parseAccept(accept) { var accepts = splitMediaTypes(accept); for (var i = 0, j = 0; i < accepts.length; i++) { var mediaType = parseMediaType(accepts[i].trim(), i); if (mediaType) { accepts[j++] = mediaType; } } // trim accepts accepts.length = j; return accepts; } /** * Parse a media type from the Accept header. * @private */ function parseMediaType(str, i) { var match = simpleMediaTypeRegExp.exec(str); if (!match) return null; var params = Object.create(null); var q = 1; var subtype = match[2]; var type = match[1]; if (match[3]) { var kvps = splitParameters(match[3]).map(splitKeyValuePair); for (var j = 0; j < kvps.length; j++) { var pair = kvps[j]; var key = pair[0].toLowerCase(); var val = pair[1]; // get the value, unwrapping quotes var value = val && val[0] === '"' && val[val.length - 1] === '"' ? val.substr(1, val.length - 2) : val; if (key === 'q') { q = parseFloat(value); break; } // store parameter params[key] = value; } } return { type: type, subtype: subtype, params: params, q: q, i: i }; } /** * Get the priority of a media type. * @private */ function getMediaTypePriority(type, accepted, index) { var priority = {o: -1, q: 0, s: 0}; for (var i = 0; i < accepted.length; i++) { var spec = specify(type, accepted[i], index); if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { priority = spec; } } return priority; } /** * Get the specificity of the media type. * @private */ function specify(type, spec, index) { var p = parseMediaType(type); var s = 0; if (!p) { return null; } if(spec.type.toLowerCase() == p.type.toLowerCase()) { s |= 4 } else if(spec.type != '*') { return null; } if(spec.subtype.toLowerCase() == p.subtype.toLowerCase()) { s |= 2 } else if(spec.subtype != '*') { return null; } var keys = Object.keys(spec.params); if (keys.length > 0) { if (keys.every(function (k) { return spec.params[k] == '*' || (spec.params[k] || '').toLowerCase() == (p.params[k] || '').toLowerCase(); })) { s |= 1 } else { return null } } return { i: index, o: spec.i, q: spec.q, s: s, } } /** * Get the preferred media types from an Accept header. * @public */ function preferredMediaTypes(accept, provided) { // RFC 2616 sec 14.2: no header = */* var accepts = parseAccept(accept === undefined ? '*/*' : accept || ''); if (!provided) { // sorted list of all types return accepts .filter(isQuality) .sort(compareSpecs) .map(getFullType); } var priorities = provided.map(function getPriority(type, index) { return getMediaTypePriority(type, accepts, index); }); // sorted list of accepted types return priorities.filter(isQuality).sort(compareSpecs).map(function getType(priority) { return provided[priorities.indexOf(priority)]; }); } /** * Compare two specs. * @private */ function compareSpecs(a, b) { return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; } /** * Get full type string. * @private */ function getFullType(spec) { return spec.type + '/' + spec.subtype; } /** * Check if a spec has any quality. * @private */ function isQuality(spec) { return spec.q > 0; } /** * Count the number of quotes in a string. * @private */ function quoteCount(string) { var count = 0; var index = 0; while ((index = string.indexOf('"', index)) !== -1) { count++; index++; } return count; } /** * Split a key value pair. * @private */ function splitKeyValuePair(str) { var index = str.indexOf('='); var key; var val; if (index === -1) { key = str; } else { key = str.substr(0, index); val = str.substr(index + 1); } return [key, val]; } /** * Split an Accept header into media types. * @private */ function splitMediaTypes(accept) { var accepts = accept.split(','); for (var i = 1, j = 0; i < accepts.length; i++) { if (quoteCount(accepts[j]) % 2 == 0) { accepts[++j] = accepts[i]; } else { accepts[j] += ',' + accepts[i]; } } // trim accepts accepts.length = j + 1; return accepts; } /** * Split a string of parameters. * @private */ function splitParameters(str) { var parameters = str.split(';'); for (var i = 1, j = 0; i < parameters.length; i++) { if (quoteCount(parameters[j]) % 2 == 0) { parameters[++j] = parameters[i]; } else { parameters[j] += ';' + parameters[i]; } } // trim parameters parameters.length = j + 1; for (var i = 0; i < parameters.length; i++) { parameters[i] = parameters[i].trim(); } return parameters; } PK ~\pVPQ Q negotiator/lib/language.jsnu[/** * negotiator * Copyright(c) 2012 Isaac Z. Schlueter * Copyright(c) 2014 Federico Romero * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */ 'use strict'; /** * Module exports. * @public */ module.exports = preferredLanguages; module.exports.preferredLanguages = preferredLanguages; /** * Module variables. * @private */ var simpleLanguageRegExp = /^\s*([^\s\-;]+)(?:-([^\s;]+))?\s*(?:;(.*))?$/; /** * Parse the Accept-Language header. * @private */ function parseAcceptLanguage(accept) { var accepts = accept.split(','); for (var i = 0, j = 0; i < accepts.length; i++) { var language = parseLanguage(accepts[i].trim(), i); if (language) { accepts[j++] = language; } } // trim accepts accepts.length = j; return accepts; } /** * Parse a language from the Accept-Language header. * @private */ function parseLanguage(str, i) { var match = simpleLanguageRegExp.exec(str); if (!match) return null; var prefix = match[1] var suffix = match[2] var full = prefix if (suffix) full += "-" + suffix; var q = 1; if (match[3]) { var params = match[3].split(';') for (var j = 0; j < params.length; j++) { var p = params[j].split('='); if (p[0] === 'q') q = parseFloat(p[1]); } } return { prefix: prefix, suffix: suffix, q: q, i: i, full: full }; } /** * Get the priority of a language. * @private */ function getLanguagePriority(language, accepted, index) { var priority = {o: -1, q: 0, s: 0}; for (var i = 0; i < accepted.length; i++) { var spec = specify(language, accepted[i], index); if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { priority = spec; } } return priority; } /** * Get the specificity of the language. * @private */ function specify(language, spec, index) { var p = parseLanguage(language) if (!p) return null; var s = 0; if(spec.full.toLowerCase() === p.full.toLowerCase()){ s |= 4; } else if (spec.prefix.toLowerCase() === p.full.toLowerCase()) { s |= 2; } else if (spec.full.toLowerCase() === p.prefix.toLowerCase()) { s |= 1; } else if (spec.full !== '*' ) { return null } return { i: index, o: spec.i, q: spec.q, s: s } }; /** * Get the preferred languages from an Accept-Language header. * @public */ function preferredLanguages(accept, provided) { // RFC 2616 sec 14.4: no header = * var accepts = parseAcceptLanguage(accept === undefined ? '*' : accept || ''); if (!provided) { // sorted list of all languages return accepts .filter(isQuality) .sort(compareSpecs) .map(getFullLanguage); } var priorities = provided.map(function getPriority(type, index) { return getLanguagePriority(type, accepts, index); }); // sorted list of accepted languages return priorities.filter(isQuality).sort(compareSpecs).map(function getLanguage(priority) { return provided[priorities.indexOf(priority)]; }); } /** * Compare two specs. * @private */ function compareSpecs(a, b) { return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; } /** * Get full language string. * @private */ function getFullLanguage(spec) { return spec.full; } /** * Check if a spec has any quality. * @private */ function isQuality(spec) { return spec.q > 0; } PK ~\LS negotiator/lib/encoding.jsnu[/** * negotiator * Copyright(c) 2012 Isaac Z. Schlueter * Copyright(c) 2014 Federico Romero * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */ 'use strict'; /** * Module exports. * @public */ module.exports = preferredEncodings; module.exports.preferredEncodings = preferredEncodings; /** * Module variables. * @private */ var simpleEncodingRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; /** * Parse the Accept-Encoding header. * @private */ function parseAcceptEncoding(accept) { var accepts = accept.split(','); var hasIdentity = false; var minQuality = 1; for (var i = 0, j = 0; i < accepts.length; i++) { var encoding = parseEncoding(accepts[i].trim(), i); if (encoding) { accepts[j++] = encoding; hasIdentity = hasIdentity || specify('identity', encoding); minQuality = Math.min(minQuality, encoding.q || 1); } } if (!hasIdentity) { /* * If identity doesn't explicitly appear in the accept-encoding header, * it's added to the list of acceptable encoding with the lowest q */ accepts[j++] = { encoding: 'identity', q: minQuality, i: i }; } // trim accepts accepts.length = j; return accepts; } /** * Parse an encoding from the Accept-Encoding header. * @private */ function parseEncoding(str, i) { var match = simpleEncodingRegExp.exec(str); if (!match) return null; var encoding = match[1]; var q = 1; if (match[2]) { var params = match[2].split(';'); for (var j = 0; j < params.length; j++) { var p = params[j].trim().split('='); if (p[0] === 'q') { q = parseFloat(p[1]); break; } } } return { encoding: encoding, q: q, i: i }; } /** * Get the priority of an encoding. * @private */ function getEncodingPriority(encoding, accepted, index) { var priority = {o: -1, q: 0, s: 0}; for (var i = 0; i < accepted.length; i++) { var spec = specify(encoding, accepted[i], index); if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { priority = spec; } } return priority; } /** * Get the specificity of the encoding. * @private */ function specify(encoding, spec, index) { var s = 0; if(spec.encoding.toLowerCase() === encoding.toLowerCase()){ s |= 1; } else if (spec.encoding !== '*' ) { return null } return { i: index, o: spec.i, q: spec.q, s: s } }; /** * Get the preferred encodings from an Accept-Encoding header. * @public */ function preferredEncodings(accept, provided) { var accepts = parseAcceptEncoding(accept || ''); if (!provided) { // sorted list of all encodings return accepts .filter(isQuality) .sort(compareSpecs) .map(getFullEncoding); } var priorities = provided.map(function getPriority(type, index) { return getEncodingPriority(type, accepts, index); }); // sorted list of accepted encodings return priorities.filter(isQuality).sort(compareSpecs).map(function getEncoding(priority) { return provided[priorities.indexOf(priority)]; }); } /** * Compare two specs. * @private */ function compareSpecs(a, b) { return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; } /** * Get full encoding string. * @private */ function getFullEncoding(spec) { return spec.encoding; } /** * Check if a spec has any quality. * @private */ function isQuality(spec) { return spec.q > 0; } PK ~\ܛ negotiator/lib/charset.jsnu[/** * negotiator * Copyright(c) 2012 Isaac Z. Schlueter * Copyright(c) 2014 Federico Romero * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */ 'use strict'; /** * Module exports. * @public */ module.exports = preferredCharsets; module.exports.preferredCharsets = preferredCharsets; /** * Module variables. * @private */ var simpleCharsetRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; /** * Parse the Accept-Charset header. * @private */ function parseAcceptCharset(accept) { var accepts = accept.split(','); for (var i = 0, j = 0; i < accepts.length; i++) { var charset = parseCharset(accepts[i].trim(), i); if (charset) { accepts[j++] = charset; } } // trim accepts accepts.length = j; return accepts; } /** * Parse a charset from the Accept-Charset header. * @private */ function parseCharset(str, i) { var match = simpleCharsetRegExp.exec(str); if (!match) return null; var charset = match[1]; var q = 1; if (match[2]) { var params = match[2].split(';') for (var j = 0; j < params.length; j++) { var p = params[j].trim().split('='); if (p[0] === 'q') { q = parseFloat(p[1]); break; } } } return { charset: charset, q: q, i: i }; } /** * Get the priority of a charset. * @private */ function getCharsetPriority(charset, accepted, index) { var priority = {o: -1, q: 0, s: 0}; for (var i = 0; i < accepted.length; i++) { var spec = specify(charset, accepted[i], index); if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { priority = spec; } } return priority; } /** * Get the specificity of the charset. * @private */ function specify(charset, spec, index) { var s = 0; if(spec.charset.toLowerCase() === charset.toLowerCase()){ s |= 1; } else if (spec.charset !== '*' ) { return null } return { i: index, o: spec.i, q: spec.q, s: s } } /** * Get the preferred charsets from an Accept-Charset header. * @public */ function preferredCharsets(accept, provided) { // RFC 2616 sec 14.2: no header = * var accepts = parseAcceptCharset(accept === undefined ? '*' : accept || ''); if (!provided) { // sorted list of all charsets return accepts .filter(isQuality) .sort(compareSpecs) .map(getFullCharset); } var priorities = provided.map(function getPriority(type, index) { return getCharsetPriority(type, accepts, index); }); // sorted list of accepted charsets return priorities.filter(isQuality).sort(compareSpecs).map(function getCharset(priority) { return provided[priorities.indexOf(priority)]; }); } /** * Compare two specs. * @private */ function compareSpecs(a, b) { return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; } /** * Get full charset string. * @private */ function getFullCharset(spec) { return spec.charset; } /** * Check if a spec has any quality. * @private */ function isQuality(spec) { return spec.q > 0; } PK ~\Cnegotiator/LICENSEnu[(The MIT License) Copyright (c) 2012-2014 Federico Romero Copyright (c) 2012-2014 Isaac Z. Schlueter Copyright (c) 2014-2015 Douglas Christopher Wilson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\oG negotiator/index.jsnu[/*! * negotiator * Copyright(c) 2012 Federico Romero * Copyright(c) 2012-2014 Isaac Z. Schlueter * Copyright(c) 2015 Douglas Christopher Wilson * MIT Licensed */ 'use strict'; var preferredCharsets = require('./lib/charset') var preferredEncodings = require('./lib/encoding') var preferredLanguages = require('./lib/language') var preferredMediaTypes = require('./lib/mediaType') /** * Module exports. * @public */ module.exports = Negotiator; module.exports.Negotiator = Negotiator; /** * Create a Negotiator instance from a request. * @param {object} request * @public */ function Negotiator(request) { if (!(this instanceof Negotiator)) { return new Negotiator(request); } this.request = request; } Negotiator.prototype.charset = function charset(available) { var set = this.charsets(available); return set && set[0]; }; Negotiator.prototype.charsets = function charsets(available) { return preferredCharsets(this.request.headers['accept-charset'], available); }; Negotiator.prototype.encoding = function encoding(available) { var set = this.encodings(available); return set && set[0]; }; Negotiator.prototype.encodings = function encodings(available) { return preferredEncodings(this.request.headers['accept-encoding'], available); }; Negotiator.prototype.language = function language(available) { var set = this.languages(available); return set && set[0]; }; Negotiator.prototype.languages = function languages(available) { return preferredLanguages(this.request.headers['accept-language'], available); }; Negotiator.prototype.mediaType = function mediaType(available) { var set = this.mediaTypes(available); return set && set[0]; }; Negotiator.prototype.mediaTypes = function mediaTypes(available) { return preferredMediaTypes(this.request.headers.accept, available); }; // Backwards compatibility Negotiator.prototype.preferredCharset = Negotiator.prototype.charset; Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets; Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding; Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings; Negotiator.prototype.preferredLanguage = Negotiator.prototype.language; Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages; Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType; Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes; PK ~\g negotiator/HISTORY.mdnu[0.6.3 / 2022-01-22 ================== * Revert "Lazy-load modules from main entry point" 0.6.2 / 2019-04-29 ================== * Fix sorting charset, encoding, and language with extra parameters 0.6.1 / 2016-05-02 ================== * perf: improve `Accept` parsing speed * perf: improve `Accept-Charset` parsing speed * perf: improve `Accept-Encoding` parsing speed * perf: improve `Accept-Language` parsing speed 0.6.0 / 2015-09-29 ================== * Fix including type extensions in parameters in `Accept` parsing * Fix parsing `Accept` parameters with quoted equals * Fix parsing `Accept` parameters with quoted semicolons * Lazy-load modules from main entry point * perf: delay type concatenation until needed * perf: enable strict mode * perf: hoist regular expressions * perf: remove closures getting spec properties * perf: remove a closure from media type parsing * perf: remove property delete from media type parsing 0.5.3 / 2015-05-10 ================== * Fix media type parameter matching to be case-insensitive 0.5.2 / 2015-05-06 ================== * Fix comparing media types with quoted values * Fix splitting media types with quoted commas 0.5.1 / 2015-02-14 ================== * Fix preference sorting to be stable for long acceptable lists 0.5.0 / 2014-12-18 ================== * Fix list return order when large accepted list * Fix missing identity encoding when q=0 exists * Remove dynamic building of Negotiator class 0.4.9 / 2014-10-14 ================== * Fix error when media type has invalid parameter 0.4.8 / 2014-09-28 ================== * Fix all negotiations to be case-insensitive * Stable sort preferences of same quality according to client order * Support Node.js 0.6 0.4.7 / 2014-06-24 ================== * Handle invalid provided languages * Handle invalid provided media types 0.4.6 / 2014-06-11 ================== * Order by specificity when quality is the same 0.4.5 / 2014-05-29 ================== * Fix regression in empty header handling 0.4.4 / 2014-05-29 ================== * Fix behaviors when headers are not present 0.4.3 / 2014-04-16 ================== * Handle slashes on media params correctly 0.4.2 / 2014-02-28 ================== * Fix media type sorting * Handle media types params strictly 0.4.1 / 2014-01-16 ================== * Use most specific matches 0.4.0 / 2014-01-09 ================== * Remove preferred prefix from methods PK ~\3  color-name/package.jsonnu[{ "_id": "color-name@1.1.4", "_inBundle": true, "_location": "/npm/color-name", "_phantomChildren": {}, "_requiredBy": [ "/npm/color-convert" ], "author": { "name": "DY", "email": "dfcreative@gmail.com" }, "bugs": { "url": "https://github.com/colorjs/color-name/issues" }, "description": "A list of color names and its values", "files": [ "index.js" ], "homepage": "https://github.com/colorjs/color-name", "keywords": [ "color-name", "color", "color-keyword", "keyword" ], "license": "MIT", "main": "index.js", "name": "color-name", "repository": { "type": "git", "url": "git+ssh://git@github.com/colorjs/color-name.git" }, "scripts": { "test": "node test.js" }, "version": "1.1.4" } PK ~\d~==color-name/LICENSEnu[The MIT License (MIT) Copyright (c) 2015 Dmitry Ivanov Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.PK ~\Hz  color-name/index.jsnu['use strict' module.exports = { "aliceblue": [240, 248, 255], "antiquewhite": [250, 235, 215], "aqua": [0, 255, 255], "aquamarine": [127, 255, 212], "azure": [240, 255, 255], "beige": [245, 245, 220], "bisque": [255, 228, 196], "black": [0, 0, 0], "blanchedalmond": [255, 235, 205], "blue": [0, 0, 255], "blueviolet": [138, 43, 226], "brown": [165, 42, 42], "burlywood": [222, 184, 135], "cadetblue": [95, 158, 160], "chartreuse": [127, 255, 0], "chocolate": [210, 105, 30], "coral": [255, 127, 80], "cornflowerblue": [100, 149, 237], "cornsilk": [255, 248, 220], "crimson": [220, 20, 60], "cyan": [0, 255, 255], "darkblue": [0, 0, 139], "darkcyan": [0, 139, 139], "darkgoldenrod": [184, 134, 11], "darkgray": [169, 169, 169], "darkgreen": [0, 100, 0], "darkgrey": [169, 169, 169], "darkkhaki": [189, 183, 107], "darkmagenta": [139, 0, 139], "darkolivegreen": [85, 107, 47], "darkorange": [255, 140, 0], "darkorchid": [153, 50, 204], "darkred": [139, 0, 0], "darksalmon": [233, 150, 122], "darkseagreen": [143, 188, 143], "darkslateblue": [72, 61, 139], "darkslategray": [47, 79, 79], "darkslategrey": [47, 79, 79], "darkturquoise": [0, 206, 209], "darkviolet": [148, 0, 211], "deeppink": [255, 20, 147], "deepskyblue": [0, 191, 255], "dimgray": [105, 105, 105], "dimgrey": [105, 105, 105], "dodgerblue": [30, 144, 255], "firebrick": [178, 34, 34], "floralwhite": [255, 250, 240], "forestgreen": [34, 139, 34], "fuchsia": [255, 0, 255], "gainsboro": [220, 220, 220], "ghostwhite": [248, 248, 255], "gold": [255, 215, 0], "goldenrod": [218, 165, 32], "gray": [128, 128, 128], "green": [0, 128, 0], "greenyellow": [173, 255, 47], "grey": [128, 128, 128], "honeydew": [240, 255, 240], "hotpink": [255, 105, 180], "indianred": [205, 92, 92], "indigo": [75, 0, 130], "ivory": [255, 255, 240], "khaki": [240, 230, 140], "lavender": [230, 230, 250], "lavenderblush": [255, 240, 245], "lawngreen": [124, 252, 0], "lemonchiffon": [255, 250, 205], "lightblue": [173, 216, 230], "lightcoral": [240, 128, 128], "lightcyan": [224, 255, 255], "lightgoldenrodyellow": [250, 250, 210], "lightgray": [211, 211, 211], "lightgreen": [144, 238, 144], "lightgrey": [211, 211, 211], "lightpink": [255, 182, 193], "lightsalmon": [255, 160, 122], "lightseagreen": [32, 178, 170], "lightskyblue": [135, 206, 250], "lightslategray": [119, 136, 153], "lightslategrey": [119, 136, 153], "lightsteelblue": [176, 196, 222], "lightyellow": [255, 255, 224], "lime": [0, 255, 0], "limegreen": [50, 205, 50], "linen": [250, 240, 230], "magenta": [255, 0, 255], "maroon": [128, 0, 0], "mediumaquamarine": [102, 205, 170], "mediumblue": [0, 0, 205], "mediumorchid": [186, 85, 211], "mediumpurple": [147, 112, 219], "mediumseagreen": [60, 179, 113], "mediumslateblue": [123, 104, 238], "mediumspringgreen": [0, 250, 154], "mediumturquoise": [72, 209, 204], "mediumvioletred": [199, 21, 133], "midnightblue": [25, 25, 112], "mintcream": [245, 255, 250], "mistyrose": [255, 228, 225], "moccasin": [255, 228, 181], "navajowhite": [255, 222, 173], "navy": [0, 0, 128], "oldlace": [253, 245, 230], "olive": [128, 128, 0], "olivedrab": [107, 142, 35], "orange": [255, 165, 0], "orangered": [255, 69, 0], "orchid": [218, 112, 214], "palegoldenrod": [238, 232, 170], "palegreen": [152, 251, 152], "paleturquoise": [175, 238, 238], "palevioletred": [219, 112, 147], "papayawhip": [255, 239, 213], "peachpuff": [255, 218, 185], "peru": [205, 133, 63], "pink": [255, 192, 203], "plum": [221, 160, 221], "powderblue": [176, 224, 230], "purple": [128, 0, 128], "rebeccapurple": [102, 51, 153], "red": [255, 0, 0], "rosybrown": [188, 143, 143], "royalblue": [65, 105, 225], "saddlebrown": [139, 69, 19], "salmon": [250, 128, 114], "sandybrown": [244, 164, 96], "seagreen": [46, 139, 87], "seashell": [255, 245, 238], "sienna": [160, 82, 45], "silver": [192, 192, 192], "skyblue": [135, 206, 235], "slateblue": [106, 90, 205], "slategray": [112, 128, 144], "slategrey": [112, 128, 144], "snow": [255, 250, 250], "springgreen": [0, 255, 127], "steelblue": [70, 130, 180], "tan": [210, 180, 140], "teal": [0, 128, 128], "thistle": [216, 191, 216], "tomato": [255, 99, 71], "turquoise": [64, 224, 208], "violet": [238, 130, 238], "wheat": [245, 222, 179], "white": [255, 255, 255], "whitesmoke": [245, 245, 245], "yellow": [255, 255, 0], "yellowgreen": [154, 205, 50] }; PK ~\K& minipass/package.jsonnu[{ "_id": "minipass@7.1.2", "_inBundle": true, "_location": "/npm/minipass", "_phantomChildren": {}, "_requiredBy": [ "/npm", "/npm/cacache", "/npm/fs-minipass", "/npm/glob", "/npm/make-fetch-happen", "/npm/minipass-collect", "/npm/minipass-fetch", "/npm/npm-registry-fetch", "/npm/pacote", "/npm/path-scurry", "/npm/ssri" ], "author": { "name": "Isaac Z. Schlueter", "email": "i@izs.me", "url": "http://blog.izs.me/" }, "bugs": { "url": "https://github.com/isaacs/minipass/issues" }, "description": "minimal implementation of a PassThrough stream", "devDependencies": { "@types/end-of-stream": "^1.4.2", "@types/node": "^20.1.2", "end-of-stream": "^1.4.0", "node-abort-controller": "^3.1.1", "prettier": "^2.6.2", "tap": "^19.0.0", "through2": "^2.0.3", "tshy": "^1.14.0", "typedoc": "^0.25.1" }, "engines": { "node": ">=16 || 14 >=14.17" }, "exports": { "./package.json": "./package.json", ".": { "import": { "types": "./dist/esm/index.d.ts", "default": "./dist/esm/index.js" }, "require": { "types": "./dist/commonjs/index.d.ts", "default": "./dist/commonjs/index.js" } } }, "files": [ "dist" ], "homepage": "https://github.com/isaacs/minipass#readme", "keywords": [ "passthrough", "stream" ], "license": "ISC", "main": "./dist/commonjs/index.js", "name": "minipass", "prettier": { "semi": false, "printWidth": 75, "tabWidth": 2, "useTabs": false, "singleQuote": true, "jsxSingleQuote": false, "bracketSameLine": true, "arrowParens": "avoid", "endOfLine": "lf" }, "repository": { "type": "git", "url": "git+https://github.com/isaacs/minipass.git" }, "scripts": { "format": "prettier --write . --loglevel warn", "postversion": "npm publish", "prepare": "tshy", "prepublishOnly": "git push origin --follow-tags", "presnap": "npm run prepare", "pretest": "npm run prepare", "preversion": "npm test", "snap": "tap", "test": "tap", "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts" }, "tap": { "typecheck": true, "include": [ "test/*.ts" ] }, "tshy": { "selfLink": false, "main": true, "exports": { "./package.json": "./package.json", ".": "./src/index.ts" } }, "type": "module", "types": "./dist/commonjs/index.d.ts", "version": "7.1.2" } PK ~\Ҁminipass/LICENSEnu[The ISC License Copyright (c) 2017-2023 npm, Inc., Isaac Z. Schlueter, and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\>#minipass/dist/commonjs/package.jsonnu[{ "type": "commonjs" } PK ~\,minipass/dist/commonjs/index.jsnu["use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Minipass = exports.isWritable = exports.isReadable = exports.isStream = void 0; const proc = typeof process === 'object' && process ? process : { stdout: null, stderr: null, }; const node_events_1 = require("node:events"); const node_stream_1 = __importDefault(require("node:stream")); const node_string_decoder_1 = require("node:string_decoder"); /** * Return true if the argument is a Minipass stream, Node stream, or something * else that Minipass can interact with. */ const isStream = (s) => !!s && typeof s === 'object' && (s instanceof Minipass || s instanceof node_stream_1.default || (0, exports.isReadable)(s) || (0, exports.isWritable)(s)); exports.isStream = isStream; /** * Return true if the argument is a valid {@link Minipass.Readable} */ const isReadable = (s) => !!s && typeof s === 'object' && s instanceof node_events_1.EventEmitter && typeof s.pipe === 'function' && // node core Writable streams have a pipe() method, but it throws s.pipe !== node_stream_1.default.Writable.prototype.pipe; exports.isReadable = isReadable; /** * Return true if the argument is a valid {@link Minipass.Writable} */ const isWritable = (s) => !!s && typeof s === 'object' && s instanceof node_events_1.EventEmitter && typeof s.write === 'function' && typeof s.end === 'function'; exports.isWritable = isWritable; const EOF = Symbol('EOF'); const MAYBE_EMIT_END = Symbol('maybeEmitEnd'); const EMITTED_END = Symbol('emittedEnd'); const EMITTING_END = Symbol('emittingEnd'); const EMITTED_ERROR = Symbol('emittedError'); const CLOSED = Symbol('closed'); const READ = Symbol('read'); const FLUSH = Symbol('flush'); const FLUSHCHUNK = Symbol('flushChunk'); const ENCODING = Symbol('encoding'); const DECODER = Symbol('decoder'); const FLOWING = Symbol('flowing'); const PAUSED = Symbol('paused'); const RESUME = Symbol('resume'); const BUFFER = Symbol('buffer'); const PIPES = Symbol('pipes'); const BUFFERLENGTH = Symbol('bufferLength'); const BUFFERPUSH = Symbol('bufferPush'); const BUFFERSHIFT = Symbol('bufferShift'); const OBJECTMODE = Symbol('objectMode'); // internal event when stream is destroyed const DESTROYED = Symbol('destroyed'); // internal event when stream has an error const ERROR = Symbol('error'); const EMITDATA = Symbol('emitData'); const EMITEND = Symbol('emitEnd'); const EMITEND2 = Symbol('emitEnd2'); const ASYNC = Symbol('async'); const ABORT = Symbol('abort'); const ABORTED = Symbol('aborted'); const SIGNAL = Symbol('signal'); const DATALISTENERS = Symbol('dataListeners'); const DISCARDED = Symbol('discarded'); const defer = (fn) => Promise.resolve().then(fn); const nodefer = (fn) => fn(); const isEndish = (ev) => ev === 'end' || ev === 'finish' || ev === 'prefinish'; const isArrayBufferLike = (b) => b instanceof ArrayBuffer || (!!b && typeof b === 'object' && b.constructor && b.constructor.name === 'ArrayBuffer' && b.byteLength >= 0); const isArrayBufferView = (b) => !Buffer.isBuffer(b) && ArrayBuffer.isView(b); /** * Internal class representing a pipe to a destination stream. * * @internal */ class Pipe { src; dest; opts; ondrain; constructor(src, dest, opts) { this.src = src; this.dest = dest; this.opts = opts; this.ondrain = () => src[RESUME](); this.dest.on('drain', this.ondrain); } unpipe() { this.dest.removeListener('drain', this.ondrain); } // only here for the prototype /* c8 ignore start */ proxyErrors(_er) { } /* c8 ignore stop */ end() { this.unpipe(); if (this.opts.end) this.dest.end(); } } /** * Internal class representing a pipe to a destination stream where * errors are proxied. * * @internal */ class PipeProxyErrors extends Pipe { unpipe() { this.src.removeListener('error', this.proxyErrors); super.unpipe(); } constructor(src, dest, opts) { super(src, dest, opts); this.proxyErrors = er => dest.emit('error', er); src.on('error', this.proxyErrors); } } const isObjectModeOptions = (o) => !!o.objectMode; const isEncodingOptions = (o) => !o.objectMode && !!o.encoding && o.encoding !== 'buffer'; /** * Main export, the Minipass class * * `RType` is the type of data emitted, defaults to Buffer * * `WType` is the type of data to be written, if RType is buffer or string, * then any {@link Minipass.ContiguousData} is allowed. * * `Events` is the set of event handler signatures that this object * will emit, see {@link Minipass.Events} */ class Minipass extends node_events_1.EventEmitter { [FLOWING] = false; [PAUSED] = false; [PIPES] = []; [BUFFER] = []; [OBJECTMODE]; [ENCODING]; [ASYNC]; [DECODER]; [EOF] = false; [EMITTED_END] = false; [EMITTING_END] = false; [CLOSED] = false; [EMITTED_ERROR] = null; [BUFFERLENGTH] = 0; [DESTROYED] = false; [SIGNAL]; [ABORTED] = false; [DATALISTENERS] = 0; [DISCARDED] = false; /** * true if the stream can be written */ writable = true; /** * true if the stream can be read */ readable = true; /** * If `RType` is Buffer, then options do not need to be provided. * Otherwise, an options object must be provided to specify either * {@link Minipass.SharedOptions.objectMode} or * {@link Minipass.SharedOptions.encoding}, as appropriate. */ constructor(...args) { const options = (args[0] || {}); super(); if (options.objectMode && typeof options.encoding === 'string') { throw new TypeError('Encoding and objectMode may not be used together'); } if (isObjectModeOptions(options)) { this[OBJECTMODE] = true; this[ENCODING] = null; } else if (isEncodingOptions(options)) { this[ENCODING] = options.encoding; this[OBJECTMODE] = false; } else { this[OBJECTMODE] = false; this[ENCODING] = null; } this[ASYNC] = !!options.async; this[DECODER] = this[ENCODING] ? new node_string_decoder_1.StringDecoder(this[ENCODING]) : null; //@ts-ignore - private option for debugging and testing if (options && options.debugExposeBuffer === true) { Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] }); } //@ts-ignore - private option for debugging and testing if (options && options.debugExposePipes === true) { Object.defineProperty(this, 'pipes', { get: () => this[PIPES] }); } const { signal } = options; if (signal) { this[SIGNAL] = signal; if (signal.aborted) { this[ABORT](); } else { signal.addEventListener('abort', () => this[ABORT]()); } } } /** * The amount of data stored in the buffer waiting to be read. * * For Buffer strings, this will be the total byte length. * For string encoding streams, this will be the string character length, * according to JavaScript's `string.length` logic. * For objectMode streams, this is a count of the items waiting to be * emitted. */ get bufferLength() { return this[BUFFERLENGTH]; } /** * The `BufferEncoding` currently in use, or `null` */ get encoding() { return this[ENCODING]; } /** * @deprecated - This is a read only property */ set encoding(_enc) { throw new Error('Encoding must be set at instantiation time'); } /** * @deprecated - Encoding may only be set at instantiation time */ setEncoding(_enc) { throw new Error('Encoding must be set at instantiation time'); } /** * True if this is an objectMode stream */ get objectMode() { return this[OBJECTMODE]; } /** * @deprecated - This is a read-only property */ set objectMode(_om) { throw new Error('objectMode must be set at instantiation time'); } /** * true if this is an async stream */ get ['async']() { return this[ASYNC]; } /** * Set to true to make this stream async. * * Once set, it cannot be unset, as this would potentially cause incorrect * behavior. Ie, a sync stream can be made async, but an async stream * cannot be safely made sync. */ set ['async'](a) { this[ASYNC] = this[ASYNC] || !!a; } // drop everything and get out of the flow completely [ABORT]() { this[ABORTED] = true; this.emit('abort', this[SIGNAL]?.reason); this.destroy(this[SIGNAL]?.reason); } /** * True if the stream has been aborted. */ get aborted() { return this[ABORTED]; } /** * No-op setter. Stream aborted status is set via the AbortSignal provided * in the constructor options. */ set aborted(_) { } write(chunk, encoding, cb) { if (this[ABORTED]) return false; if (this[EOF]) throw new Error('write after end'); if (this[DESTROYED]) { this.emit('error', Object.assign(new Error('Cannot call write after a stream was destroyed'), { code: 'ERR_STREAM_DESTROYED' })); return true; } if (typeof encoding === 'function') { cb = encoding; encoding = 'utf8'; } if (!encoding) encoding = 'utf8'; const fn = this[ASYNC] ? defer : nodefer; // convert array buffers and typed array views into buffers // at some point in the future, we may want to do the opposite! // leave strings and buffers as-is // anything is only allowed if in object mode, so throw if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { if (isArrayBufferView(chunk)) { //@ts-ignore - sinful unsafe type changing chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength); } else if (isArrayBufferLike(chunk)) { //@ts-ignore - sinful unsafe type changing chunk = Buffer.from(chunk); } else if (typeof chunk !== 'string') { throw new Error('Non-contiguous data written to non-objectMode stream'); } } // handle object mode up front, since it's simpler // this yields better performance, fewer checks later. if (this[OBJECTMODE]) { // maybe impossible? /* c8 ignore start */ if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true); /* c8 ignore stop */ if (this[FLOWING]) this.emit('data', chunk); else this[BUFFERPUSH](chunk); if (this[BUFFERLENGTH] !== 0) this.emit('readable'); if (cb) fn(cb); return this[FLOWING]; } // at this point the chunk is a buffer or string // don't buffer it up or send it to the decoder if (!chunk.length) { if (this[BUFFERLENGTH] !== 0) this.emit('readable'); if (cb) fn(cb); return this[FLOWING]; } // fast-path writing strings of same encoding to a stream with // an empty buffer, skipping the buffer/decoder dance if (typeof chunk === 'string' && // unless it is a string already ready for us to use !(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)) { //@ts-ignore - sinful unsafe type change chunk = Buffer.from(chunk, encoding); } if (Buffer.isBuffer(chunk) && this[ENCODING]) { //@ts-ignore - sinful unsafe type change chunk = this[DECODER].write(chunk); } // Note: flushing CAN potentially switch us into not-flowing mode if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true); if (this[FLOWING]) this.emit('data', chunk); else this[BUFFERPUSH](chunk); if (this[BUFFERLENGTH] !== 0) this.emit('readable'); if (cb) fn(cb); return this[FLOWING]; } /** * Low-level explicit read method. * * In objectMode, the argument is ignored, and one item is returned if * available. * * `n` is the number of bytes (or in the case of encoding streams, * characters) to consume. If `n` is not provided, then the entire buffer * is returned, or `null` is returned if no data is available. * * If `n` is greater that the amount of data in the internal buffer, * then `null` is returned. */ read(n) { if (this[DESTROYED]) return null; this[DISCARDED] = false; if (this[BUFFERLENGTH] === 0 || n === 0 || (n && n > this[BUFFERLENGTH])) { this[MAYBE_EMIT_END](); return null; } if (this[OBJECTMODE]) n = null; if (this[BUFFER].length > 1 && !this[OBJECTMODE]) { // not object mode, so if we have an encoding, then RType is string // otherwise, must be Buffer this[BUFFER] = [ (this[ENCODING] ? this[BUFFER].join('') : Buffer.concat(this[BUFFER], this[BUFFERLENGTH])), ]; } const ret = this[READ](n || null, this[BUFFER][0]); this[MAYBE_EMIT_END](); return ret; } [READ](n, chunk) { if (this[OBJECTMODE]) this[BUFFERSHIFT](); else { const c = chunk; if (n === c.length || n === null) this[BUFFERSHIFT](); else if (typeof c === 'string') { this[BUFFER][0] = c.slice(n); chunk = c.slice(0, n); this[BUFFERLENGTH] -= n; } else { this[BUFFER][0] = c.subarray(n); chunk = c.subarray(0, n); this[BUFFERLENGTH] -= n; } } this.emit('data', chunk); if (!this[BUFFER].length && !this[EOF]) this.emit('drain'); return chunk; } end(chunk, encoding, cb) { if (typeof chunk === 'function') { cb = chunk; chunk = undefined; } if (typeof encoding === 'function') { cb = encoding; encoding = 'utf8'; } if (chunk !== undefined) this.write(chunk, encoding); if (cb) this.once('end', cb); this[EOF] = true; this.writable = false; // if we haven't written anything, then go ahead and emit, // even if we're not reading. // we'll re-emit if a new 'end' listener is added anyway. // This makes MP more suitable to write-only use cases. if (this[FLOWING] || !this[PAUSED]) this[MAYBE_EMIT_END](); return this; } // don't let the internal resume be overwritten [RESUME]() { if (this[DESTROYED]) return; if (!this[DATALISTENERS] && !this[PIPES].length) { this[DISCARDED] = true; } this[PAUSED] = false; this[FLOWING] = true; this.emit('resume'); if (this[BUFFER].length) this[FLUSH](); else if (this[EOF]) this[MAYBE_EMIT_END](); else this.emit('drain'); } /** * Resume the stream if it is currently in a paused state * * If called when there are no pipe destinations or `data` event listeners, * this will place the stream in a "discarded" state, where all data will * be thrown away. The discarded state is removed if a pipe destination or * data handler is added, if pause() is called, or if any synchronous or * asynchronous iteration is started. */ resume() { return this[RESUME](); } /** * Pause the stream */ pause() { this[FLOWING] = false; this[PAUSED] = true; this[DISCARDED] = false; } /** * true if the stream has been forcibly destroyed */ get destroyed() { return this[DESTROYED]; } /** * true if the stream is currently in a flowing state, meaning that * any writes will be immediately emitted. */ get flowing() { return this[FLOWING]; } /** * true if the stream is currently in a paused state */ get paused() { return this[PAUSED]; } [BUFFERPUSH](chunk) { if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1; else this[BUFFERLENGTH] += chunk.length; this[BUFFER].push(chunk); } [BUFFERSHIFT]() { if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1; else this[BUFFERLENGTH] -= this[BUFFER][0].length; return this[BUFFER].shift(); } [FLUSH](noDrain = false) { do { } while (this[FLUSHCHUNK](this[BUFFERSHIFT]()) && this[BUFFER].length); if (!noDrain && !this[BUFFER].length && !this[EOF]) this.emit('drain'); } [FLUSHCHUNK](chunk) { this.emit('data', chunk); return this[FLOWING]; } /** * Pipe all data emitted by this stream into the destination provided. * * Triggers the flow of data. */ pipe(dest, opts) { if (this[DESTROYED]) return dest; this[DISCARDED] = false; const ended = this[EMITTED_END]; opts = opts || {}; if (dest === proc.stdout || dest === proc.stderr) opts.end = false; else opts.end = opts.end !== false; opts.proxyErrors = !!opts.proxyErrors; // piping an ended stream ends immediately if (ended) { if (opts.end) dest.end(); } else { // "as" here just ignores the WType, which pipes don't care about, // since they're only consuming from us, and writing to the dest this[PIPES].push(!opts.proxyErrors ? new Pipe(this, dest, opts) : new PipeProxyErrors(this, dest, opts)); if (this[ASYNC]) defer(() => this[RESUME]()); else this[RESUME](); } return dest; } /** * Fully unhook a piped destination stream. * * If the destination stream was the only consumer of this stream (ie, * there are no other piped destinations or `'data'` event listeners) * then the flow of data will stop until there is another consumer or * {@link Minipass#resume} is explicitly called. */ unpipe(dest) { const p = this[PIPES].find(p => p.dest === dest); if (p) { if (this[PIPES].length === 1) { if (this[FLOWING] && this[DATALISTENERS] === 0) { this[FLOWING] = false; } this[PIPES] = []; } else this[PIPES].splice(this[PIPES].indexOf(p), 1); p.unpipe(); } } /** * Alias for {@link Minipass#on} */ addListener(ev, handler) { return this.on(ev, handler); } /** * Mostly identical to `EventEmitter.on`, with the following * behavior differences to prevent data loss and unnecessary hangs: * * - Adding a 'data' event handler will trigger the flow of data * * - Adding a 'readable' event handler when there is data waiting to be read * will cause 'readable' to be emitted immediately. * * - Adding an 'endish' event handler ('end', 'finish', etc.) which has * already passed will cause the event to be emitted immediately and all * handlers removed. * * - Adding an 'error' event handler after an error has been emitted will * cause the event to be re-emitted immediately with the error previously * raised. */ on(ev, handler) { const ret = super.on(ev, handler); if (ev === 'data') { this[DISCARDED] = false; this[DATALISTENERS]++; if (!this[PIPES].length && !this[FLOWING]) { this[RESUME](); } } else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) { super.emit('readable'); } else if (isEndish(ev) && this[EMITTED_END]) { super.emit(ev); this.removeAllListeners(ev); } else if (ev === 'error' && this[EMITTED_ERROR]) { const h = handler; if (this[ASYNC]) defer(() => h.call(this, this[EMITTED_ERROR])); else h.call(this, this[EMITTED_ERROR]); } return ret; } /** * Alias for {@link Minipass#off} */ removeListener(ev, handler) { return this.off(ev, handler); } /** * Mostly identical to `EventEmitter.off` * * If a 'data' event handler is removed, and it was the last consumer * (ie, there are no pipe destinations or other 'data' event listeners), * then the flow of data will stop until there is another consumer or * {@link Minipass#resume} is explicitly called. */ off(ev, handler) { const ret = super.off(ev, handler); // if we previously had listeners, and now we don't, and we don't // have any pipes, then stop the flow, unless it's been explicitly // put in a discarded flowing state via stream.resume(). if (ev === 'data') { this[DATALISTENERS] = this.listeners('data').length; if (this[DATALISTENERS] === 0 && !this[DISCARDED] && !this[PIPES].length) { this[FLOWING] = false; } } return ret; } /** * Mostly identical to `EventEmitter.removeAllListeners` * * If all 'data' event handlers are removed, and they were the last consumer * (ie, there are no pipe destinations), then the flow of data will stop * until there is another consumer or {@link Minipass#resume} is explicitly * called. */ removeAllListeners(ev) { const ret = super.removeAllListeners(ev); if (ev === 'data' || ev === undefined) { this[DATALISTENERS] = 0; if (!this[DISCARDED] && !this[PIPES].length) { this[FLOWING] = false; } } return ret; } /** * true if the 'end' event has been emitted */ get emittedEnd() { return this[EMITTED_END]; } [MAYBE_EMIT_END]() { if (!this[EMITTING_END] && !this[EMITTED_END] && !this[DESTROYED] && this[BUFFER].length === 0 && this[EOF]) { this[EMITTING_END] = true; this.emit('end'); this.emit('prefinish'); this.emit('finish'); if (this[CLOSED]) this.emit('close'); this[EMITTING_END] = false; } } /** * Mostly identical to `EventEmitter.emit`, with the following * behavior differences to prevent data loss and unnecessary hangs: * * If the stream has been destroyed, and the event is something other * than 'close' or 'error', then `false` is returned and no handlers * are called. * * If the event is 'end', and has already been emitted, then the event * is ignored. If the stream is in a paused or non-flowing state, then * the event will be deferred until data flow resumes. If the stream is * async, then handlers will be called on the next tick rather than * immediately. * * If the event is 'close', and 'end' has not yet been emitted, then * the event will be deferred until after 'end' is emitted. * * If the event is 'error', and an AbortSignal was provided for the stream, * and there are no listeners, then the event is ignored, matching the * behavior of node core streams in the presense of an AbortSignal. * * If the event is 'finish' or 'prefinish', then all listeners will be * removed after emitting the event, to prevent double-firing. */ emit(ev, ...args) { const data = args[0]; // error and close are only events allowed after calling destroy() if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED]) { return false; } else if (ev === 'data') { return !this[OBJECTMODE] && !data ? false : this[ASYNC] ? (defer(() => this[EMITDATA](data)), true) : this[EMITDATA](data); } else if (ev === 'end') { return this[EMITEND](); } else if (ev === 'close') { this[CLOSED] = true; // don't emit close before 'end' and 'finish' if (!this[EMITTED_END] && !this[DESTROYED]) return false; const ret = super.emit('close'); this.removeAllListeners('close'); return ret; } else if (ev === 'error') { this[EMITTED_ERROR] = data; super.emit(ERROR, data); const ret = !this[SIGNAL] || this.listeners('error').length ? super.emit('error', data) : false; this[MAYBE_EMIT_END](); return ret; } else if (ev === 'resume') { const ret = super.emit('resume'); this[MAYBE_EMIT_END](); return ret; } else if (ev === 'finish' || ev === 'prefinish') { const ret = super.emit(ev); this.removeAllListeners(ev); return ret; } // Some other unknown event const ret = super.emit(ev, ...args); this[MAYBE_EMIT_END](); return ret; } [EMITDATA](data) { for (const p of this[PIPES]) { if (p.dest.write(data) === false) this.pause(); } const ret = this[DISCARDED] ? false : super.emit('data', data); this[MAYBE_EMIT_END](); return ret; } [EMITEND]() { if (this[EMITTED_END]) return false; this[EMITTED_END] = true; this.readable = false; return this[ASYNC] ? (defer(() => this[EMITEND2]()), true) : this[EMITEND2](); } [EMITEND2]() { if (this[DECODER]) { const data = this[DECODER].end(); if (data) { for (const p of this[PIPES]) { p.dest.write(data); } if (!this[DISCARDED]) super.emit('data', data); } } for (const p of this[PIPES]) { p.end(); } const ret = super.emit('end'); this.removeAllListeners('end'); return ret; } /** * Return a Promise that resolves to an array of all emitted data once * the stream ends. */ async collect() { const buf = Object.assign([], { dataLength: 0, }); if (!this[OBJECTMODE]) buf.dataLength = 0; // set the promise first, in case an error is raised // by triggering the flow here. const p = this.promise(); this.on('data', c => { buf.push(c); if (!this[OBJECTMODE]) buf.dataLength += c.length; }); await p; return buf; } /** * Return a Promise that resolves to the concatenation of all emitted data * once the stream ends. * * Not allowed on objectMode streams. */ async concat() { if (this[OBJECTMODE]) { throw new Error('cannot concat in objectMode'); } const buf = await this.collect(); return (this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength)); } /** * Return a void Promise that resolves once the stream ends. */ async promise() { return new Promise((resolve, reject) => { this.on(DESTROYED, () => reject(new Error('stream destroyed'))); this.on('error', er => reject(er)); this.on('end', () => resolve()); }); } /** * Asynchronous `for await of` iteration. * * This will continue emitting all chunks until the stream terminates. */ [Symbol.asyncIterator]() { // set this up front, in case the consumer doesn't call next() // right away. this[DISCARDED] = false; let stopped = false; const stop = async () => { this.pause(); stopped = true; return { value: undefined, done: true }; }; const next = () => { if (stopped) return stop(); const res = this.read(); if (res !== null) return Promise.resolve({ done: false, value: res }); if (this[EOF]) return stop(); let resolve; let reject; const onerr = (er) => { this.off('data', ondata); this.off('end', onend); this.off(DESTROYED, ondestroy); stop(); reject(er); }; const ondata = (value) => { this.off('error', onerr); this.off('end', onend); this.off(DESTROYED, ondestroy); this.pause(); resolve({ value, done: !!this[EOF] }); }; const onend = () => { this.off('error', onerr); this.off('data', ondata); this.off(DESTROYED, ondestroy); stop(); resolve({ done: true, value: undefined }); }; const ondestroy = () => onerr(new Error('stream destroyed')); return new Promise((res, rej) => { reject = rej; resolve = res; this.once(DESTROYED, ondestroy); this.once('error', onerr); this.once('end', onend); this.once('data', ondata); }); }; return { next, throw: stop, return: stop, [Symbol.asyncIterator]() { return this; }, }; } /** * Synchronous `for of` iteration. * * The iteration will terminate when the internal buffer runs out, even * if the stream has not yet terminated. */ [Symbol.iterator]() { // set this up front, in case the consumer doesn't call next() // right away. this[DISCARDED] = false; let stopped = false; const stop = () => { this.pause(); this.off(ERROR, stop); this.off(DESTROYED, stop); this.off('end', stop); stopped = true; return { done: true, value: undefined }; }; const next = () => { if (stopped) return stop(); const value = this.read(); return value === null ? stop() : { done: false, value }; }; this.once('end', stop); this.once(ERROR, stop); this.once(DESTROYED, stop); return { next, throw: stop, return: stop, [Symbol.iterator]() { return this; }, }; } /** * Destroy a stream, preventing it from being used for any further purpose. * * If the stream has a `close()` method, then it will be called on * destruction. * * After destruction, any attempt to write data, read data, or emit most * events will be ignored. * * If an error argument is provided, then it will be emitted in an * 'error' event. */ destroy(er) { if (this[DESTROYED]) { if (er) this.emit('error', er); else this.emit(DESTROYED); return this; } this[DESTROYED] = true; this[DISCARDED] = true; // throw away all buffered data, it's never coming out this[BUFFER].length = 0; this[BUFFERLENGTH] = 0; const wc = this; if (typeof wc.close === 'function' && !this[CLOSED]) wc.close(); if (er) this.emit('error', er); // if no error to emit, still reject pending promises else this.emit(DESTROYED); return this; } /** * Alias for {@link isStream} * * Former export location, maintained for backwards compatibility. * * @deprecated */ static get isStream() { return exports.isStream; } } exports.Minipass = Minipass; //# sourceMappingURL=index.js.mapPK ~\xminipass/dist/esm/package.jsonnu[{ "type": "module" } PK ~\hl¡́́minipass/dist/esm/index.jsnu[const proc = typeof process === 'object' && process ? process : { stdout: null, stderr: null, }; import { EventEmitter } from 'node:events'; import Stream from 'node:stream'; import { StringDecoder } from 'node:string_decoder'; /** * Return true if the argument is a Minipass stream, Node stream, or something * else that Minipass can interact with. */ export const isStream = (s) => !!s && typeof s === 'object' && (s instanceof Minipass || s instanceof Stream || isReadable(s) || isWritable(s)); /** * Return true if the argument is a valid {@link Minipass.Readable} */ export const isReadable = (s) => !!s && typeof s === 'object' && s instanceof EventEmitter && typeof s.pipe === 'function' && // node core Writable streams have a pipe() method, but it throws s.pipe !== Stream.Writable.prototype.pipe; /** * Return true if the argument is a valid {@link Minipass.Writable} */ export const isWritable = (s) => !!s && typeof s === 'object' && s instanceof EventEmitter && typeof s.write === 'function' && typeof s.end === 'function'; const EOF = Symbol('EOF'); const MAYBE_EMIT_END = Symbol('maybeEmitEnd'); const EMITTED_END = Symbol('emittedEnd'); const EMITTING_END = Symbol('emittingEnd'); const EMITTED_ERROR = Symbol('emittedError'); const CLOSED = Symbol('closed'); const READ = Symbol('read'); const FLUSH = Symbol('flush'); const FLUSHCHUNK = Symbol('flushChunk'); const ENCODING = Symbol('encoding'); const DECODER = Symbol('decoder'); const FLOWING = Symbol('flowing'); const PAUSED = Symbol('paused'); const RESUME = Symbol('resume'); const BUFFER = Symbol('buffer'); const PIPES = Symbol('pipes'); const BUFFERLENGTH = Symbol('bufferLength'); const BUFFERPUSH = Symbol('bufferPush'); const BUFFERSHIFT = Symbol('bufferShift'); const OBJECTMODE = Symbol('objectMode'); // internal event when stream is destroyed const DESTROYED = Symbol('destroyed'); // internal event when stream has an error const ERROR = Symbol('error'); const EMITDATA = Symbol('emitData'); const EMITEND = Symbol('emitEnd'); const EMITEND2 = Symbol('emitEnd2'); const ASYNC = Symbol('async'); const ABORT = Symbol('abort'); const ABORTED = Symbol('aborted'); const SIGNAL = Symbol('signal'); const DATALISTENERS = Symbol('dataListeners'); const DISCARDED = Symbol('discarded'); const defer = (fn) => Promise.resolve().then(fn); const nodefer = (fn) => fn(); const isEndish = (ev) => ev === 'end' || ev === 'finish' || ev === 'prefinish'; const isArrayBufferLike = (b) => b instanceof ArrayBuffer || (!!b && typeof b === 'object' && b.constructor && b.constructor.name === 'ArrayBuffer' && b.byteLength >= 0); const isArrayBufferView = (b) => !Buffer.isBuffer(b) && ArrayBuffer.isView(b); /** * Internal class representing a pipe to a destination stream. * * @internal */ class Pipe { src; dest; opts; ondrain; constructor(src, dest, opts) { this.src = src; this.dest = dest; this.opts = opts; this.ondrain = () => src[RESUME](); this.dest.on('drain', this.ondrain); } unpipe() { this.dest.removeListener('drain', this.ondrain); } // only here for the prototype /* c8 ignore start */ proxyErrors(_er) { } /* c8 ignore stop */ end() { this.unpipe(); if (this.opts.end) this.dest.end(); } } /** * Internal class representing a pipe to a destination stream where * errors are proxied. * * @internal */ class PipeProxyErrors extends Pipe { unpipe() { this.src.removeListener('error', this.proxyErrors); super.unpipe(); } constructor(src, dest, opts) { super(src, dest, opts); this.proxyErrors = er => dest.emit('error', er); src.on('error', this.proxyErrors); } } const isObjectModeOptions = (o) => !!o.objectMode; const isEncodingOptions = (o) => !o.objectMode && !!o.encoding && o.encoding !== 'buffer'; /** * Main export, the Minipass class * * `RType` is the type of data emitted, defaults to Buffer * * `WType` is the type of data to be written, if RType is buffer or string, * then any {@link Minipass.ContiguousData} is allowed. * * `Events` is the set of event handler signatures that this object * will emit, see {@link Minipass.Events} */ export class Minipass extends EventEmitter { [FLOWING] = false; [PAUSED] = false; [PIPES] = []; [BUFFER] = []; [OBJECTMODE]; [ENCODING]; [ASYNC]; [DECODER]; [EOF] = false; [EMITTED_END] = false; [EMITTING_END] = false; [CLOSED] = false; [EMITTED_ERROR] = null; [BUFFERLENGTH] = 0; [DESTROYED] = false; [SIGNAL]; [ABORTED] = false; [DATALISTENERS] = 0; [DISCARDED] = false; /** * true if the stream can be written */ writable = true; /** * true if the stream can be read */ readable = true; /** * If `RType` is Buffer, then options do not need to be provided. * Otherwise, an options object must be provided to specify either * {@link Minipass.SharedOptions.objectMode} or * {@link Minipass.SharedOptions.encoding}, as appropriate. */ constructor(...args) { const options = (args[0] || {}); super(); if (options.objectMode && typeof options.encoding === 'string') { throw new TypeError('Encoding and objectMode may not be used together'); } if (isObjectModeOptions(options)) { this[OBJECTMODE] = true; this[ENCODING] = null; } else if (isEncodingOptions(options)) { this[ENCODING] = options.encoding; this[OBJECTMODE] = false; } else { this[OBJECTMODE] = false; this[ENCODING] = null; } this[ASYNC] = !!options.async; this[DECODER] = this[ENCODING] ? new StringDecoder(this[ENCODING]) : null; //@ts-ignore - private option for debugging and testing if (options && options.debugExposeBuffer === true) { Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] }); } //@ts-ignore - private option for debugging and testing if (options && options.debugExposePipes === true) { Object.defineProperty(this, 'pipes', { get: () => this[PIPES] }); } const { signal } = options; if (signal) { this[SIGNAL] = signal; if (signal.aborted) { this[ABORT](); } else { signal.addEventListener('abort', () => this[ABORT]()); } } } /** * The amount of data stored in the buffer waiting to be read. * * For Buffer strings, this will be the total byte length. * For string encoding streams, this will be the string character length, * according to JavaScript's `string.length` logic. * For objectMode streams, this is a count of the items waiting to be * emitted. */ get bufferLength() { return this[BUFFERLENGTH]; } /** * The `BufferEncoding` currently in use, or `null` */ get encoding() { return this[ENCODING]; } /** * @deprecated - This is a read only property */ set encoding(_enc) { throw new Error('Encoding must be set at instantiation time'); } /** * @deprecated - Encoding may only be set at instantiation time */ setEncoding(_enc) { throw new Error('Encoding must be set at instantiation time'); } /** * True if this is an objectMode stream */ get objectMode() { return this[OBJECTMODE]; } /** * @deprecated - This is a read-only property */ set objectMode(_om) { throw new Error('objectMode must be set at instantiation time'); } /** * true if this is an async stream */ get ['async']() { return this[ASYNC]; } /** * Set to true to make this stream async. * * Once set, it cannot be unset, as this would potentially cause incorrect * behavior. Ie, a sync stream can be made async, but an async stream * cannot be safely made sync. */ set ['async'](a) { this[ASYNC] = this[ASYNC] || !!a; } // drop everything and get out of the flow completely [ABORT]() { this[ABORTED] = true; this.emit('abort', this[SIGNAL]?.reason); this.destroy(this[SIGNAL]?.reason); } /** * True if the stream has been aborted. */ get aborted() { return this[ABORTED]; } /** * No-op setter. Stream aborted status is set via the AbortSignal provided * in the constructor options. */ set aborted(_) { } write(chunk, encoding, cb) { if (this[ABORTED]) return false; if (this[EOF]) throw new Error('write after end'); if (this[DESTROYED]) { this.emit('error', Object.assign(new Error('Cannot call write after a stream was destroyed'), { code: 'ERR_STREAM_DESTROYED' })); return true; } if (typeof encoding === 'function') { cb = encoding; encoding = 'utf8'; } if (!encoding) encoding = 'utf8'; const fn = this[ASYNC] ? defer : nodefer; // convert array buffers and typed array views into buffers // at some point in the future, we may want to do the opposite! // leave strings and buffers as-is // anything is only allowed if in object mode, so throw if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { if (isArrayBufferView(chunk)) { //@ts-ignore - sinful unsafe type changing chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength); } else if (isArrayBufferLike(chunk)) { //@ts-ignore - sinful unsafe type changing chunk = Buffer.from(chunk); } else if (typeof chunk !== 'string') { throw new Error('Non-contiguous data written to non-objectMode stream'); } } // handle object mode up front, since it's simpler // this yields better performance, fewer checks later. if (this[OBJECTMODE]) { // maybe impossible? /* c8 ignore start */ if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true); /* c8 ignore stop */ if (this[FLOWING]) this.emit('data', chunk); else this[BUFFERPUSH](chunk); if (this[BUFFERLENGTH] !== 0) this.emit('readable'); if (cb) fn(cb); return this[FLOWING]; } // at this point the chunk is a buffer or string // don't buffer it up or send it to the decoder if (!chunk.length) { if (this[BUFFERLENGTH] !== 0) this.emit('readable'); if (cb) fn(cb); return this[FLOWING]; } // fast-path writing strings of same encoding to a stream with // an empty buffer, skipping the buffer/decoder dance if (typeof chunk === 'string' && // unless it is a string already ready for us to use !(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)) { //@ts-ignore - sinful unsafe type change chunk = Buffer.from(chunk, encoding); } if (Buffer.isBuffer(chunk) && this[ENCODING]) { //@ts-ignore - sinful unsafe type change chunk = this[DECODER].write(chunk); } // Note: flushing CAN potentially switch us into not-flowing mode if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true); if (this[FLOWING]) this.emit('data', chunk); else this[BUFFERPUSH](chunk); if (this[BUFFERLENGTH] !== 0) this.emit('readable'); if (cb) fn(cb); return this[FLOWING]; } /** * Low-level explicit read method. * * In objectMode, the argument is ignored, and one item is returned if * available. * * `n` is the number of bytes (or in the case of encoding streams, * characters) to consume. If `n` is not provided, then the entire buffer * is returned, or `null` is returned if no data is available. * * If `n` is greater that the amount of data in the internal buffer, * then `null` is returned. */ read(n) { if (this[DESTROYED]) return null; this[DISCARDED] = false; if (this[BUFFERLENGTH] === 0 || n === 0 || (n && n > this[BUFFERLENGTH])) { this[MAYBE_EMIT_END](); return null; } if (this[OBJECTMODE]) n = null; if (this[BUFFER].length > 1 && !this[OBJECTMODE]) { // not object mode, so if we have an encoding, then RType is string // otherwise, must be Buffer this[BUFFER] = [ (this[ENCODING] ? this[BUFFER].join('') : Buffer.concat(this[BUFFER], this[BUFFERLENGTH])), ]; } const ret = this[READ](n || null, this[BUFFER][0]); this[MAYBE_EMIT_END](); return ret; } [READ](n, chunk) { if (this[OBJECTMODE]) this[BUFFERSHIFT](); else { const c = chunk; if (n === c.length || n === null) this[BUFFERSHIFT](); else if (typeof c === 'string') { this[BUFFER][0] = c.slice(n); chunk = c.slice(0, n); this[BUFFERLENGTH] -= n; } else { this[BUFFER][0] = c.subarray(n); chunk = c.subarray(0, n); this[BUFFERLENGTH] -= n; } } this.emit('data', chunk); if (!this[BUFFER].length && !this[EOF]) this.emit('drain'); return chunk; } end(chunk, encoding, cb) { if (typeof chunk === 'function') { cb = chunk; chunk = undefined; } if (typeof encoding === 'function') { cb = encoding; encoding = 'utf8'; } if (chunk !== undefined) this.write(chunk, encoding); if (cb) this.once('end', cb); this[EOF] = true; this.writable = false; // if we haven't written anything, then go ahead and emit, // even if we're not reading. // we'll re-emit if a new 'end' listener is added anyway. // This makes MP more suitable to write-only use cases. if (this[FLOWING] || !this[PAUSED]) this[MAYBE_EMIT_END](); return this; } // don't let the internal resume be overwritten [RESUME]() { if (this[DESTROYED]) return; if (!this[DATALISTENERS] && !this[PIPES].length) { this[DISCARDED] = true; } this[PAUSED] = false; this[FLOWING] = true; this.emit('resume'); if (this[BUFFER].length) this[FLUSH](); else if (this[EOF]) this[MAYBE_EMIT_END](); else this.emit('drain'); } /** * Resume the stream if it is currently in a paused state * * If called when there are no pipe destinations or `data` event listeners, * this will place the stream in a "discarded" state, where all data will * be thrown away. The discarded state is removed if a pipe destination or * data handler is added, if pause() is called, or if any synchronous or * asynchronous iteration is started. */ resume() { return this[RESUME](); } /** * Pause the stream */ pause() { this[FLOWING] = false; this[PAUSED] = true; this[DISCARDED] = false; } /** * true if the stream has been forcibly destroyed */ get destroyed() { return this[DESTROYED]; } /** * true if the stream is currently in a flowing state, meaning that * any writes will be immediately emitted. */ get flowing() { return this[FLOWING]; } /** * true if the stream is currently in a paused state */ get paused() { return this[PAUSED]; } [BUFFERPUSH](chunk) { if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1; else this[BUFFERLENGTH] += chunk.length; this[BUFFER].push(chunk); } [BUFFERSHIFT]() { if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1; else this[BUFFERLENGTH] -= this[BUFFER][0].length; return this[BUFFER].shift(); } [FLUSH](noDrain = false) { do { } while (this[FLUSHCHUNK](this[BUFFERSHIFT]()) && this[BUFFER].length); if (!noDrain && !this[BUFFER].length && !this[EOF]) this.emit('drain'); } [FLUSHCHUNK](chunk) { this.emit('data', chunk); return this[FLOWING]; } /** * Pipe all data emitted by this stream into the destination provided. * * Triggers the flow of data. */ pipe(dest, opts) { if (this[DESTROYED]) return dest; this[DISCARDED] = false; const ended = this[EMITTED_END]; opts = opts || {}; if (dest === proc.stdout || dest === proc.stderr) opts.end = false; else opts.end = opts.end !== false; opts.proxyErrors = !!opts.proxyErrors; // piping an ended stream ends immediately if (ended) { if (opts.end) dest.end(); } else { // "as" here just ignores the WType, which pipes don't care about, // since they're only consuming from us, and writing to the dest this[PIPES].push(!opts.proxyErrors ? new Pipe(this, dest, opts) : new PipeProxyErrors(this, dest, opts)); if (this[ASYNC]) defer(() => this[RESUME]()); else this[RESUME](); } return dest; } /** * Fully unhook a piped destination stream. * * If the destination stream was the only consumer of this stream (ie, * there are no other piped destinations or `'data'` event listeners) * then the flow of data will stop until there is another consumer or * {@link Minipass#resume} is explicitly called. */ unpipe(dest) { const p = this[PIPES].find(p => p.dest === dest); if (p) { if (this[PIPES].length === 1) { if (this[FLOWING] && this[DATALISTENERS] === 0) { this[FLOWING] = false; } this[PIPES] = []; } else this[PIPES].splice(this[PIPES].indexOf(p), 1); p.unpipe(); } } /** * Alias for {@link Minipass#on} */ addListener(ev, handler) { return this.on(ev, handler); } /** * Mostly identical to `EventEmitter.on`, with the following * behavior differences to prevent data loss and unnecessary hangs: * * - Adding a 'data' event handler will trigger the flow of data * * - Adding a 'readable' event handler when there is data waiting to be read * will cause 'readable' to be emitted immediately. * * - Adding an 'endish' event handler ('end', 'finish', etc.) which has * already passed will cause the event to be emitted immediately and all * handlers removed. * * - Adding an 'error' event handler after an error has been emitted will * cause the event to be re-emitted immediately with the error previously * raised. */ on(ev, handler) { const ret = super.on(ev, handler); if (ev === 'data') { this[DISCARDED] = false; this[DATALISTENERS]++; if (!this[PIPES].length && !this[FLOWING]) { this[RESUME](); } } else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) { super.emit('readable'); } else if (isEndish(ev) && this[EMITTED_END]) { super.emit(ev); this.removeAllListeners(ev); } else if (ev === 'error' && this[EMITTED_ERROR]) { const h = handler; if (this[ASYNC]) defer(() => h.call(this, this[EMITTED_ERROR])); else h.call(this, this[EMITTED_ERROR]); } return ret; } /** * Alias for {@link Minipass#off} */ removeListener(ev, handler) { return this.off(ev, handler); } /** * Mostly identical to `EventEmitter.off` * * If a 'data' event handler is removed, and it was the last consumer * (ie, there are no pipe destinations or other 'data' event listeners), * then the flow of data will stop until there is another consumer or * {@link Minipass#resume} is explicitly called. */ off(ev, handler) { const ret = super.off(ev, handler); // if we previously had listeners, and now we don't, and we don't // have any pipes, then stop the flow, unless it's been explicitly // put in a discarded flowing state via stream.resume(). if (ev === 'data') { this[DATALISTENERS] = this.listeners('data').length; if (this[DATALISTENERS] === 0 && !this[DISCARDED] && !this[PIPES].length) { this[FLOWING] = false; } } return ret; } /** * Mostly identical to `EventEmitter.removeAllListeners` * * If all 'data' event handlers are removed, and they were the last consumer * (ie, there are no pipe destinations), then the flow of data will stop * until there is another consumer or {@link Minipass#resume} is explicitly * called. */ removeAllListeners(ev) { const ret = super.removeAllListeners(ev); if (ev === 'data' || ev === undefined) { this[DATALISTENERS] = 0; if (!this[DISCARDED] && !this[PIPES].length) { this[FLOWING] = false; } } return ret; } /** * true if the 'end' event has been emitted */ get emittedEnd() { return this[EMITTED_END]; } [MAYBE_EMIT_END]() { if (!this[EMITTING_END] && !this[EMITTED_END] && !this[DESTROYED] && this[BUFFER].length === 0 && this[EOF]) { this[EMITTING_END] = true; this.emit('end'); this.emit('prefinish'); this.emit('finish'); if (this[CLOSED]) this.emit('close'); this[EMITTING_END] = false; } } /** * Mostly identical to `EventEmitter.emit`, with the following * behavior differences to prevent data loss and unnecessary hangs: * * If the stream has been destroyed, and the event is something other * than 'close' or 'error', then `false` is returned and no handlers * are called. * * If the event is 'end', and has already been emitted, then the event * is ignored. If the stream is in a paused or non-flowing state, then * the event will be deferred until data flow resumes. If the stream is * async, then handlers will be called on the next tick rather than * immediately. * * If the event is 'close', and 'end' has not yet been emitted, then * the event will be deferred until after 'end' is emitted. * * If the event is 'error', and an AbortSignal was provided for the stream, * and there are no listeners, then the event is ignored, matching the * behavior of node core streams in the presense of an AbortSignal. * * If the event is 'finish' or 'prefinish', then all listeners will be * removed after emitting the event, to prevent double-firing. */ emit(ev, ...args) { const data = args[0]; // error and close are only events allowed after calling destroy() if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED]) { return false; } else if (ev === 'data') { return !this[OBJECTMODE] && !data ? false : this[ASYNC] ? (defer(() => this[EMITDATA](data)), true) : this[EMITDATA](data); } else if (ev === 'end') { return this[EMITEND](); } else if (ev === 'close') { this[CLOSED] = true; // don't emit close before 'end' and 'finish' if (!this[EMITTED_END] && !this[DESTROYED]) return false; const ret = super.emit('close'); this.removeAllListeners('close'); return ret; } else if (ev === 'error') { this[EMITTED_ERROR] = data; super.emit(ERROR, data); const ret = !this[SIGNAL] || this.listeners('error').length ? super.emit('error', data) : false; this[MAYBE_EMIT_END](); return ret; } else if (ev === 'resume') { const ret = super.emit('resume'); this[MAYBE_EMIT_END](); return ret; } else if (ev === 'finish' || ev === 'prefinish') { const ret = super.emit(ev); this.removeAllListeners(ev); return ret; } // Some other unknown event const ret = super.emit(ev, ...args); this[MAYBE_EMIT_END](); return ret; } [EMITDATA](data) { for (const p of this[PIPES]) { if (p.dest.write(data) === false) this.pause(); } const ret = this[DISCARDED] ? false : super.emit('data', data); this[MAYBE_EMIT_END](); return ret; } [EMITEND]() { if (this[EMITTED_END]) return false; this[EMITTED_END] = true; this.readable = false; return this[ASYNC] ? (defer(() => this[EMITEND2]()), true) : this[EMITEND2](); } [EMITEND2]() { if (this[DECODER]) { const data = this[DECODER].end(); if (data) { for (const p of this[PIPES]) { p.dest.write(data); } if (!this[DISCARDED]) super.emit('data', data); } } for (const p of this[PIPES]) { p.end(); } const ret = super.emit('end'); this.removeAllListeners('end'); return ret; } /** * Return a Promise that resolves to an array of all emitted data once * the stream ends. */ async collect() { const buf = Object.assign([], { dataLength: 0, }); if (!this[OBJECTMODE]) buf.dataLength = 0; // set the promise first, in case an error is raised // by triggering the flow here. const p = this.promise(); this.on('data', c => { buf.push(c); if (!this[OBJECTMODE]) buf.dataLength += c.length; }); await p; return buf; } /** * Return a Promise that resolves to the concatenation of all emitted data * once the stream ends. * * Not allowed on objectMode streams. */ async concat() { if (this[OBJECTMODE]) { throw new Error('cannot concat in objectMode'); } const buf = await this.collect(); return (this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength)); } /** * Return a void Promise that resolves once the stream ends. */ async promise() { return new Promise((resolve, reject) => { this.on(DESTROYED, () => reject(new Error('stream destroyed'))); this.on('error', er => reject(er)); this.on('end', () => resolve()); }); } /** * Asynchronous `for await of` iteration. * * This will continue emitting all chunks until the stream terminates. */ [Symbol.asyncIterator]() { // set this up front, in case the consumer doesn't call next() // right away. this[DISCARDED] = false; let stopped = false; const stop = async () => { this.pause(); stopped = true; return { value: undefined, done: true }; }; const next = () => { if (stopped) return stop(); const res = this.read(); if (res !== null) return Promise.resolve({ done: false, value: res }); if (this[EOF]) return stop(); let resolve; let reject; const onerr = (er) => { this.off('data', ondata); this.off('end', onend); this.off(DESTROYED, ondestroy); stop(); reject(er); }; const ondata = (value) => { this.off('error', onerr); this.off('end', onend); this.off(DESTROYED, ondestroy); this.pause(); resolve({ value, done: !!this[EOF] }); }; const onend = () => { this.off('error', onerr); this.off('data', ondata); this.off(DESTROYED, ondestroy); stop(); resolve({ done: true, value: undefined }); }; const ondestroy = () => onerr(new Error('stream destroyed')); return new Promise((res, rej) => { reject = rej; resolve = res; this.once(DESTROYED, ondestroy); this.once('error', onerr); this.once('end', onend); this.once('data', ondata); }); }; return { next, throw: stop, return: stop, [Symbol.asyncIterator]() { return this; }, }; } /** * Synchronous `for of` iteration. * * The iteration will terminate when the internal buffer runs out, even * if the stream has not yet terminated. */ [Symbol.iterator]() { // set this up front, in case the consumer doesn't call next() // right away. this[DISCARDED] = false; let stopped = false; const stop = () => { this.pause(); this.off(ERROR, stop); this.off(DESTROYED, stop); this.off('end', stop); stopped = true; return { done: true, value: undefined }; }; const next = () => { if (stopped) return stop(); const value = this.read(); return value === null ? stop() : { done: false, value }; }; this.once('end', stop); this.once(ERROR, stop); this.once(DESTROYED, stop); return { next, throw: stop, return: stop, [Symbol.iterator]() { return this; }, }; } /** * Destroy a stream, preventing it from being used for any further purpose. * * If the stream has a `close()` method, then it will be called on * destruction. * * After destruction, any attempt to write data, read data, or emit most * events will be ignored. * * If an error argument is provided, then it will be emitted in an * 'error' event. */ destroy(er) { if (this[DESTROYED]) { if (er) this.emit('error', er); else this.emit(DESTROYED); return this; } this[DESTROYED] = true; this[DISCARDED] = true; // throw away all buffered data, it's never coming out this[BUFFER].length = 0; this[BUFFERLENGTH] = 0; const wc = this; if (typeof wc.close === 'function' && !this[CLOSED]) wc.close(); if (er) this.emit('error', er); // if no error to emit, still reject pending promises else this.emit(DESTROYED); return this; } /** * Alias for {@link isStream} * * Former export location, maintained for backwards compatibility. * * @deprecated */ static get isStream() { return isStream; } } //# sourceMappingURL=index.js.mapPK ~\*2$$strip-ansi/package.jsonnu[{ "_id": "strip-ansi@6.0.1", "_inBundle": true, "_location": "/npm/strip-ansi", "_phantomChildren": {}, "_requiredBy": [ "/npm/cli-columns", "/npm/string-width", "/npm/string-width-cjs", "/npm/wrap-ansi-cjs" ], "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "bugs": { "url": "https://github.com/chalk/strip-ansi/issues" }, "dependencies": { "ansi-regex": "^5.0.1" }, "description": "Strip ANSI escape codes from a string", "devDependencies": { "ava": "^2.4.0", "tsd": "^0.10.0", "xo": "^0.25.3" }, "engines": { "node": ">=8" }, "files": [ "index.js", "index.d.ts" ], "homepage": "https://github.com/chalk/strip-ansi#readme", "keywords": [ "strip", "trim", "remove", "ansi", "styles", "color", "colour", "colors", "terminal", "console", "string", "tty", "escape", "formatting", "rgb", "256", "shell", "xterm", "log", "logging", "command-line", "text" ], "license": "MIT", "name": "strip-ansi", "repository": { "type": "git", "url": "git+https://github.com/chalk/strip-ansi.git" }, "scripts": { "test": "xo && ava && tsd" }, "version": "6.0.1" } PK ~\*9strip-ansi/index.jsnu['use strict'; const ansiRegex = require('ansi-regex'); module.exports = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; PK ~\E}UUstrip-ansi/licensenu[MIT License Copyright (c) Sindre Sorhus (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\kjust-diff/package.jsonnu[{ "_id": "just-diff@6.0.2", "_inBundle": true, "_location": "/npm/just-diff", "_phantomChildren": {}, "_requiredBy": [ "/npm/parse-conflict-json" ], "author": { "name": "Angus Croll" }, "bugs": { "url": "https://github.com/angus-c/just/issues" }, "description": "Return an object representing the diffs between two objects. Supports jsonPatch protocol", "exports": { ".": { "types": "./index.d.ts", "require": "./index.cjs", "import": "./index.mjs" }, "./package.json": "./package.json" }, "homepage": "https://github.com/angus-c/just#readme", "keywords": [ "object", "diff", "jsonPatch", "no-dependencies", "just" ], "license": "MIT", "main": "index.cjs", "name": "just-diff", "repository": { "type": "git", "url": "git+https://github.com/angus-c/just.git" }, "scripts": { "build": "rollup -c", "test": "echo \"Error: no test specified\" && exit 1" }, "type": "module", "types": "index.d.ts", "version": "6.0.2" } PK ~\F66just-diff/LICENSEnu[The MIT License (MIT) Copyright (c) 2016 angus croll Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\GZ$,,just-diff/index.mjsnu[/* const obj1 = {a: 4, b: 5}; const obj2 = {a: 3, b: 5}; const obj3 = {a: 4, c: 5}; diff(obj1, obj2); [ { "op": "replace", "path": ['a'], "value": 3 } ] diff(obj2, obj3); [ { "op": "remove", "path": ['b'] }, { "op": "replace", "path": ['a'], "value": 4 } { "op": "add", "path": ['c'], "value": 5 } ] // using converter to generate jsPatch standard paths // see http://jsonpatch.com import {diff, jsonPatchPathConverter} from 'just-diff' diff(obj1, obj2, jsonPatchPathConverter); [ { "op": "replace", "path": '/a', "value": 3 } ] diff(obj2, obj3, jsonPatchPathConverter); [ { "op": "remove", "path": '/b' }, { "op": "replace", "path": '/a', "value": 4 } { "op": "add", "path": '/c', "value": 5 } ] // arrays const obj4 = {a: 4, b: [1, 2, 3]}; const obj5 = {a: 3, b: [1, 2, 4]}; const obj6 = {a: 3, b: [1, 2, 4, 5]}; diff(obj4, obj5); [ { "op": "replace", "path": ['a'], "value": 3 } { "op": "replace", "path": ['b', 2], "value": 4 } ] diff(obj5, obj6); [ { "op": "add", "path": ['b', 3], "value": 5 } ] // nested paths const obj7 = {a: 4, b: {c: 3}}; const obj8 = {a: 4, b: {c: 4}}; const obj9 = {a: 5, b: {d: 4}}; diff(obj7, obj8); [ { "op": "replace", "path": ['b', 'c'], "value": 4 } ] diff(obj8, obj9); [ { "op": "replace", "path": ['a'], "value": 5 } { "op": "remove", "path": ['b', 'c']} { "op": "add", "path": ['b', 'd'], "value": 4 } ] */ function diff(obj1, obj2, pathConverter) { if (!obj1 || typeof obj1 != 'object' || !obj2 || typeof obj2 != 'object') { throw new Error('both arguments must be objects or arrays'); } pathConverter || (pathConverter = function(arr) { return arr; }); function getDiff({obj1, obj2, basePath, basePathForRemoves, diffs}) { var obj1Keys = Object.keys(obj1); var obj1KeysLength = obj1Keys.length; var obj2Keys = Object.keys(obj2); var obj2KeysLength = obj2Keys.length; var path; var lengthDelta = obj1.length - obj2.length; if (trimFromRight(obj1, obj2)) { for (var i = 0; i < obj1KeysLength; i++) { var key = Array.isArray(obj1) ? Number(obj1Keys[i]) : obj1Keys[i]; if (!(key in obj2)) { path = basePathForRemoves.concat(key); diffs.remove.push({ op: 'remove', path: pathConverter(path), }); } } for (var i = 0; i < obj2KeysLength; i++) { var key = Array.isArray(obj2) ? Number(obj2Keys[i]) : obj2Keys[i]; pushReplaces({ key, obj1, obj2, path: basePath.concat(key), pathForRemoves: basePath.concat(key), diffs, }); } } else { // trim from left, objects are both arrays for (var i = 0; i < lengthDelta; i++) { path = basePathForRemoves.concat(i); diffs.remove.push({ op: 'remove', path: pathConverter(path), }); } // now make a copy of obj1 with excess elements left trimmed and see if there any replaces var obj1Trimmed = obj1.slice(lengthDelta);; for (var i = 0; i < obj2KeysLength; i++) { pushReplaces({ key: i, obj1: obj1Trimmed, obj2, path: basePath.concat(i), // since list of removes are reversed before presenting result, // we need to ignore existing parent removes when doing nested removes pathForRemoves: basePath.concat(i + lengthDelta), diffs, }); } } } var diffs = {remove: [], replace: [], add: []}; getDiff({ obj1, obj2, basePath: [], basePathForRemoves: [], diffs, }); // reverse removes since we want to maintain indexes return diffs.remove .reverse() .concat(diffs.replace) .concat(diffs.add); function pushReplaces({key, obj1, obj2, path, pathForRemoves, diffs}) { var obj1AtKey = obj1[key]; var obj2AtKey = obj2[key]; if(!(key in obj1) && (key in obj2)) { var obj2Value = obj2AtKey; diffs.add.push({ op: 'add', path: pathConverter(path), value: obj2Value, }); } else if(obj1AtKey !== obj2AtKey) { if(Object(obj1AtKey) !== obj1AtKey || Object(obj2AtKey) !== obj2AtKey || differentTypes(obj1AtKey, obj2AtKey) ) { pushReplace(path, diffs, obj2AtKey); } else { if(!Object.keys(obj1AtKey).length && !Object.keys(obj2AtKey).length && String(obj1AtKey) != String(obj2AtKey)) { pushReplace(path, diffs, obj2AtKey); } else { getDiff({ obj1: obj1[key], obj2: obj2[key], basePath: path, basePathForRemoves: pathForRemoves, diffs}); } } } } function pushReplace(path, diffs, newValue) { diffs.replace.push({ op: 'replace', path: pathConverter(path), value: newValue, }); } } function jsonPatchPathConverter(arrayPath) { return [''].concat(arrayPath).join('/'); } function differentTypes(a, b) { return Object.prototype.toString.call(a) != Object.prototype.toString.call(b); } function trimFromRight(obj1, obj2) { var lengthDelta = obj1.length - obj2.length; if (Array.isArray(obj1) && Array.isArray(obj2) && lengthDelta > 0) { var leftMatches = 0; var rightMatches = 0; for (var i = 0; i < obj2.length; i++) { if (String(obj1[i]) === String(obj2[i])) { leftMatches++; } else { break; } } for (var j = obj2.length; j > 0; j--) { if (String(obj1[j + lengthDelta]) === String(obj2[j])) { rightMatches++; } else { break; } } // bias to trim right becase it requires less index shifting return leftMatches >= rightMatches; } return true; } export {diff, jsonPatchPathConverter}; PK ~\!xxjust-diff/rollup.config.jsnu[const createRollupConfig = require('../../config/createRollupConfig'); module.exports = createRollupConfig(__dirname); PK ~\[[just-diff/index.cjsnu[module.exports = { diff: diff, jsonPatchPathConverter: jsonPatchPathConverter, }; /* const obj1 = {a: 4, b: 5}; const obj2 = {a: 3, b: 5}; const obj3 = {a: 4, c: 5}; diff(obj1, obj2); [ { "op": "replace", "path": ['a'], "value": 3 } ] diff(obj2, obj3); [ { "op": "remove", "path": ['b'] }, { "op": "replace", "path": ['a'], "value": 4 } { "op": "add", "path": ['c'], "value": 5 } ] // using converter to generate jsPatch standard paths // see http://jsonpatch.com import {diff, jsonPatchPathConverter} from 'just-diff' diff(obj1, obj2, jsonPatchPathConverter); [ { "op": "replace", "path": '/a', "value": 3 } ] diff(obj2, obj3, jsonPatchPathConverter); [ { "op": "remove", "path": '/b' }, { "op": "replace", "path": '/a', "value": 4 } { "op": "add", "path": '/c', "value": 5 } ] // arrays const obj4 = {a: 4, b: [1, 2, 3]}; const obj5 = {a: 3, b: [1, 2, 4]}; const obj6 = {a: 3, b: [1, 2, 4, 5]}; diff(obj4, obj5); [ { "op": "replace", "path": ['a'], "value": 3 } { "op": "replace", "path": ['b', 2], "value": 4 } ] diff(obj5, obj6); [ { "op": "add", "path": ['b', 3], "value": 5 } ] // nested paths const obj7 = {a: 4, b: {c: 3}}; const obj8 = {a: 4, b: {c: 4}}; const obj9 = {a: 5, b: {d: 4}}; diff(obj7, obj8); [ { "op": "replace", "path": ['b', 'c'], "value": 4 } ] diff(obj8, obj9); [ { "op": "replace", "path": ['a'], "value": 5 } { "op": "remove", "path": ['b', 'c']} { "op": "add", "path": ['b', 'd'], "value": 4 } ] */ function diff(obj1, obj2, pathConverter) { if (!obj1 || typeof obj1 != 'object' || !obj2 || typeof obj2 != 'object') { throw new Error('both arguments must be objects or arrays'); } pathConverter || (pathConverter = function(arr) { return arr; }); function getDiff({obj1, obj2, basePath, basePathForRemoves, diffs}) { var obj1Keys = Object.keys(obj1); var obj1KeysLength = obj1Keys.length; var obj2Keys = Object.keys(obj2); var obj2KeysLength = obj2Keys.length; var path; var lengthDelta = obj1.length - obj2.length; if (trimFromRight(obj1, obj2)) { for (var i = 0; i < obj1KeysLength; i++) { var key = Array.isArray(obj1) ? Number(obj1Keys[i]) : obj1Keys[i]; if (!(key in obj2)) { path = basePathForRemoves.concat(key); diffs.remove.push({ op: 'remove', path: pathConverter(path), }); } } for (var i = 0; i < obj2KeysLength; i++) { var key = Array.isArray(obj2) ? Number(obj2Keys[i]) : obj2Keys[i]; pushReplaces({ key, obj1, obj2, path: basePath.concat(key), pathForRemoves: basePath.concat(key), diffs, }); } } else { // trim from left, objects are both arrays for (var i = 0; i < lengthDelta; i++) { path = basePathForRemoves.concat(i); diffs.remove.push({ op: 'remove', path: pathConverter(path), }); } // now make a copy of obj1 with excess elements left trimmed and see if there any replaces var obj1Trimmed = obj1.slice(lengthDelta);; for (var i = 0; i < obj2KeysLength; i++) { pushReplaces({ key: i, obj1: obj1Trimmed, obj2, path: basePath.concat(i), // since list of removes are reversed before presenting result, // we need to ignore existing parent removes when doing nested removes pathForRemoves: basePath.concat(i + lengthDelta), diffs, }); } } } var diffs = {remove: [], replace: [], add: []}; getDiff({ obj1, obj2, basePath: [], basePathForRemoves: [], diffs, }); // reverse removes since we want to maintain indexes return diffs.remove .reverse() .concat(diffs.replace) .concat(diffs.add); function pushReplaces({key, obj1, obj2, path, pathForRemoves, diffs}) { var obj1AtKey = obj1[key]; var obj2AtKey = obj2[key]; if(!(key in obj1) && (key in obj2)) { var obj2Value = obj2AtKey; diffs.add.push({ op: 'add', path: pathConverter(path), value: obj2Value, }); } else if(obj1AtKey !== obj2AtKey) { if(Object(obj1AtKey) !== obj1AtKey || Object(obj2AtKey) !== obj2AtKey || differentTypes(obj1AtKey, obj2AtKey) ) { pushReplace(path, diffs, obj2AtKey); } else { if(!Object.keys(obj1AtKey).length && !Object.keys(obj2AtKey).length && String(obj1AtKey) != String(obj2AtKey)) { pushReplace(path, diffs, obj2AtKey); } else { getDiff({ obj1: obj1[key], obj2: obj2[key], basePath: path, basePathForRemoves: pathForRemoves, diffs}); } } } } function pushReplace(path, diffs, newValue) { diffs.replace.push({ op: 'replace', path: pathConverter(path), value: newValue, }); } } function jsonPatchPathConverter(arrayPath) { return [''].concat(arrayPath).join('/'); } function differentTypes(a, b) { return Object.prototype.toString.call(a) != Object.prototype.toString.call(b); } function trimFromRight(obj1, obj2) { var lengthDelta = obj1.length - obj2.length; if (Array.isArray(obj1) && Array.isArray(obj2) && lengthDelta > 0) { var leftMatches = 0; var rightMatches = 0; for (var i = 0; i < obj2.length; i++) { if (String(obj1[i]) === String(obj2[i])) { leftMatches++; } else { break; } } for (var j = obj2.length; j > 0; j--) { if (String(obj1[j + lengthDelta]) === String(obj2[j])) { rightMatches++; } else { break; } } // bias to trim right becase it requires less index shifting return leftMatches >= rightMatches; } return true; } PK ~\ b.length ? [a, b] : [b, a] for (const x of s) { if (x === l.shift()) yield x else break } } const commonAncestorPath = (a, b) => a === b ? a : parse(a).root !== parse(b).root ? null : [...commonArrayMembers(norm(a).split(sep), norm(b).split(sep))].join(sep) module.exports = (...paths) => paths.reduce(commonAncestorPath) PK ~\Bunique-slug/package.jsonnu[{ "_id": "unique-slug@4.0.0", "_inBundle": true, "_location": "/npm/unique-slug", "_phantomChildren": {}, "_requiredBy": [ "/npm/unique-filename" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/unique-slug/issues" }, "dependencies": { "imurmurhash": "^0.1.4" }, "description": "Generate a unique character string suitible for use in files and URLs.", "devDependencies": { "@npmcli/eslint-config": "^3.1.0", "@npmcli/template-oss": "4.5.1", "tap": "^16.3.0" }, "engines": { "node": "^14.17.0 || ^16.13.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/unique-slug#readme", "keywords": [], "license": "ISC", "main": "lib/index.js", "name": "unique-slug", "repository": { "type": "git", "url": "git+https://github.com/npm/unique-slug.git" }, "scripts": { "lint": "eslint \"**/*.js\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "version": "4.5.1" }, "version": "4.0.0" } PK ~\ȅunique-slug/lib/index.jsnu['use strict' var MurmurHash3 = require('imurmurhash') module.exports = function (uniq) { if (uniq) { var hash = new MurmurHash3(uniq) return ('00000000' + hash.result().toString(16)).slice(-8) } else { return (Math.random().toString(16) + '0000000').slice(2, 10) } } PK ~\Uunique-slug/LICENSEnu[The ISC License Copyright npm, Inc Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\GWWjsonparse/package.jsonnu[{ "_id": "jsonparse@1.3.1", "_inBundle": true, "_location": "/npm/jsonparse", "_phantomChildren": {}, "_requiredBy": [ "/npm/minipass-json-stream" ], "author": { "name": "Tim Caswell", "email": "tim@creationix.com" }, "bugs": { "url": "http://github.com/creationix/jsonparse/issues" }, "description": "This is a pure-js JSON streaming parser for node.js", "devDependencies": { "tap": "~0.3.3", "tape": "~0.1.1" }, "engines": [ "node >= 0.2.0" ], "homepage": "https://github.com/creationix/jsonparse#readme", "license": "MIT", "main": "jsonparse.js", "name": "jsonparse", "repository": { "type": "git", "url": "git+ssh://git@github.com/creationix/jsonparse.git" }, "scripts": { "test": "tap test/*.js" }, "tags": [ "json", "stream" ], "version": "1.3.1" } PK ~\vuc  jsonparse/samplejson/basic.jsonnu[[ { }, { "image": [ {"shape": "rect", "fill": "#333", "stroke": "#999", "x": 0.5e+1, "y": 0.5, "z": 0.8e-0, "w": 0.5e5, "u": 2E10, "foo": 2E+1, "bar": 2E-0, "width": 47, "height": 47} ], "jumpable": 3, "solid": { "1": [2,4], "2": [], "3": [2,6], "4": [], "5": [2,8,1,3,7,9,4,6], "6": [], "7": [4,8], "8": [], "9": [6,8] }, "corners": {"1": true,"3": true,"7": true,"9": true} }, { "image": [ {"shape": "polygon", "fill": "#248", "stroke": "#48f", "points": [[0.5,47.5],[47.5,47.5],[47.5,0.5]]} ], "solid": { "1": [2,4], "2": [1], "3": [2], "4": [], "5": [2,8,1,3,7,9,4,6], "6": [], "7": [4,8], "8": [], "9": [6,8] }, "corners": {"1": true,"3": true,"7": false,"9": true} }, { "image": [ {"shape": "polygon", "fill": "#248", "stroke": "#48f", "points": [[0.5,0.5],[47.5,47.5],[0.5,47.5]]} ], "solid": { "1": [2], "2": [3], "3": [2,6], "4": [], "5": [2,8,1,3,7,9,4,6], "6": [], "7": [4,8], "8": [], "9": [6,8] }, "corners": {"1": true,"3": true,"7": true,"9": false} }, { "image": [ {"shape": "polygon", "fill": "#333", "stroke": "#999", "points": [[0.5,0.5],[47.5,47.5],[47.5,0.5]]} ], "jumpable": 3, "solid": { "1": [2,4], "2": [], "3": [2,6], "4": [], "5": [2,8,1,3,7,9,4,6], "6": [3], "7": [4,8], "8": [7], "9": [6,8] }, "corners": {"1": false,"3": true,"7": true,"9": true} }, { "image": [ {"shape": "polygon", "fill": "#333", "stroke": "#999", "points": [[0.5,0.5],[0.5,47.5],[47.5,0.5]]} ], "jumpable": 3, "solid": { "1": [2,4], "2": [], "3": [2,6], "4": [1], "5": [2,8,1,3,7,9,4,6], "6": [], "7": [4,8], "8": [9], "9": [6,8] }, "corners": {"1": true,"3": false,"7": true,"9": true} }, { "image": [ {"shape": "polygon", "fill": "#482", "stroke": "#8f4", "points": [[0.5,47.5],[0.5,23.5],[24.5,23.5],[24.5,0.5],[47.5,0.5],[47.5,47.5]]} ], "jumpable": 3, "solid": { "1": [2,4], "2": [], "3": [6,2], "4": [], "5": [2,8,1,3,7,9,4,6], "6": [9], "7": [4,8], "8": [], "9": [6,8] }, "corners": {"1": true,"3": true,"7": false,"9": true} }, { "image": [ {"shape": "polygon", "fill": "#482", "stroke": "#8f4", "points": [[0.5,0.5],[23.5,0.5],[23.5,24.5],[47.5,24.5],[47.5,47.5],[0.5,47.5]]} ], "jumpable": 3, "solid": { "1": [4,2], "2": [], "3": [2,6], "4": [7], "5": [2,8,1,3,7,9,4,6], "6": [], "7": [4,8], "8": [], "9": [6,8] }, "corners": {"1": true,"3": true,"7": true,"9": false} }, { "image": [ {"shape": "circle", "fill": "#ff0", "stroke": "#ff8", "cx": 24, "cy": 24, "r": 18} ], "item": true }, { "image": [ {"shape": "polygon", "fill": "#842", "stroke": "#f84", "points": [[4.5,0.5],[14.5,0.5],[14.5,17.5],[34,17.5],[33.5,0.5],[43.5,0.5],[43.5,47.5],[33.5,47.5],[33.5,30.5],[14.5,30.5],[14.5,47.5],[4.5,47.5]]} ], "jumpable": 3 }, { "image": [ {"shape": "polygon", "fill": "#333", "stroke": "#999", "points": [[0.5,0.5],[47.5,0.5],[24,47.5]]} ], "jumpable": 3, "solid": { "1": [2,4], "2": [], "3": [2,6], "4": [1], "5": [2,8,1,3,7,9,4,6], "6": [3], "7": [4,8], "8": [], "9": [6,8] }, "corners": {"1": false,"3": false,"7": true,"9": true} }, { "image": [ {"shape": "rect", "fill": "#114acb", "x": 0.5, "y": 0.5, "width": 47, "height": 47}, {"shape": "polygon", "fill": "rgba(255,255,255,0.30)", "points": [[0.5,0.5],[47.5,0.5],[40,8],[8,8],[8,40],[0.5,47.5]]}, {"shape": "polygon", "fill": "rgba(0,0,0,0.30)", "points": [[47.5,0.5],[48,48],[0.5,47.5],[8,40],[40,40],[40,8]]}, {"shape": "polygon", "fill": "rgb(255,255,0)", "stroke": "rgba(255,255,0,0.5)", "points": [[24,9],[35,20],[26,29],[26,33],[22,33],[22,27],[29,20],[24,15],[16,23],[13,20]]}, {"shape": "rect", "fill": "rgb(255,255,0)", "stroke": "rgba(255,255,0,0.5)", "x": 22, "y":35, "width": 4, "height": 4} ] } ] PK ~\XO jsonparse/samplejson/basic2.jsonnu[[ { }, { "image": [ {"shape": "rect", "fill": "#333", "stroke": "#999", "x": 0.5, "y": 0.5, "width": 47, "height": 47} ], "jumpable": 3, "solid": { "1": [2,4], "2": [], "3": [2,6], "4": [], "5": [2,8,1,3,7,9,4,6], "6": [], "7": [4,8], "8": [], "9": [6,8] }, "corners": {"1": true,"3": true,"7": true,"9": true} }, { "image": [ {"shape": "polygon", "fill": "#248", "stroke": "#48f", "points": [[0.5,47.5],[47.5,47.5],[47.5,0.5]]} ], "solid": { "1": [2,4], "2": [1], "3": [2], "4": [], "5": [2,8,1,3,7,9,4,6], "6": [], "7": [4,8], "8": [], "9": [6,8] }, "corners": {"1": true,"3": true,"7": false,"9": true} }, { "image": [ {"shape": "polygon", "fill": "#248", "stroke": "#48f", "points": [[0.5,0.5],[47.5,47.5],[0.5,47.5]]} ], "solid": { "1": [2], "2": [3], "3": [2,6], "4": [], "5": [2,8,1,3,7,9,4,6], "6": [], "7": [4,8], "8": [], "9": [6,8] }, "corners": {"1": true,"3": true,"7": true,"9": false} }, { "image": [ {"shape": "polygon", "fill": "#333", "stroke": "#999", "points": [[0.5,0.5],[47.5,47.5],[47.5,0.5]]} ], "jumpable": 3, "solid": { "1": [2,4], "2": [], "3": [2,6], "4": [], "5": [2,8,1,3,7,9,4,6], "6": [3], "7": [4,8], "8": [7], "9": [6,8] }, "corners": {"1": false,"3": true,"7": true,"9": true} }, { "image": [ {"shape": "polygon", "fill": "#333", "stroke": "#999", "points": [[0.5,0.5],[0.5,47.5],[47.5,0.5]]} ], "jumpable": 3, "solid": { "1": [2,4], "2": [], "3": [2,6], "4": [1], "5": [2,8,1,3,7,9,4,6], "6": [], "7": [4,8], "8": [9], "9": [6,8] }, "corners": {"1": true,"3": false,"7": true,"9": true} }, { "image": [ {"shape": "polygon", "fill": "#482", "stroke": "#8f4", "points": [[0.5,47.5],[0.5,23.5],[24.5,23.5],[24.5,0.5],[47.5,0.5],[47.5,47.5]]} ], "jumpable": 3, "solid": { "1": [2,4], "2": [], "3": [6,2], "4": [], "5": [2,8,1,3,7,9,4,6], "6": [9], "7": [4,8], "8": [], "9": [6,8] }, "corners": {"1": true,"3": true,"7": false,"9": true} }, { "image": [ {"shape": "polygon", "fill": "#482", "stroke": "#8f4", "points": [[0.5,0.5],[23.5,0.5],[23.5,24.5],[47.5,24.5],[47.5,47.5],[0.5,47.5]]} ], "jumpable": 3, "solid": { "1": [4,2], "2": [], "3": [2,6], "4": [7], "5": [2,8,1,3,7,9,4,6], "6": [], "7": [4,8], "8": [], "9": [6,8] }, "corners": {"1": true,"3": true,"7": true,"9": false} }, { "image": [ {"shape": "circle", "fill": "#ff0", "stroke": "#ff8", "cx": 24, "cy": 24, "r": 18} ], "item": true }, { "image": [ {"shape": "polygon", "fill": "#842", "stroke": "#f84", "points": [[4.5,0.5],[14.5,0.5],[14.5,17.5],[34,17.5],[33.5,0.5],[43.5,0.5],[43.5,47.5],[33.5,47.5],[33.5,30.5],[14.5,30.5],[14.5,47.5],[4.5,47.5]]} ], "jumpable": 3 }, { "image": [ {"shape": "polygon", "fill": "#333", "stroke": "#999", "points": [[0.5,0.5],[47.5,0.5],[24,47.5]]} ], "jumpable": 3, "solid": { "1": [2,4], "2": [], "3": [2,6], "4": [1], "5": [2,8,1,3,7,9,4,6], "6": [3], "7": [4,8], "8": [], "9": [6,8] }, "corners": {"1": false,"3": false,"7": true,"9": true} }, { "image": [ {"shape": "rect", "fill": "#114acb", "x": 0.5, "y": 0.5, "width": 47, "height": 47}, {"shape": "polygon", "fill": "rgba(255,255,255,0.30)", "points": [[0.5,0.5],[47.5,0.5],[40,8],[8,8],[8,40],[0.5,47.5]]}, {"shape": "polygon", "fill": "rgba(0,0,0,0.30)", "points": [[47.5,0.5],[48,48],[0.5,47.5],[8,40],[40,40],[40,8]]}, {"shape": "polygon", "fill": "rgb(255,255,0)", "stroke": "rgba(255,255,0,0.5)", "points": [[24,9],[35,20],[26,29],[26,33],[22,33],[22,27],[29,20],[24,15],[16,23],[13,20]]}, {"shape": "rect", "fill": "rgb(255,255,0)", "stroke": "rgba(255,255,0,0.5)", "x": 22, "y":35, "width": 4, "height": 4} ], "item": true }, { "image": [ {"shape": "circle", "fill": "#80f", "stroke": "#88f", "cx": 24, "cy": 24, "r": 18} ], "item": true }, { "image": [ {"shape": "circle", "fill": "#4f4", "stroke": "#8f8", "cx": 24, "cy": 24, "r": 18} ], "item": true } ] PK ~\S<<jsonparse/jsonparse.jsnu[/*global Buffer*/ // Named constants with unique integer values var C = {}; // Tokens var LEFT_BRACE = C.LEFT_BRACE = 0x1; var RIGHT_BRACE = C.RIGHT_BRACE = 0x2; var LEFT_BRACKET = C.LEFT_BRACKET = 0x3; var RIGHT_BRACKET = C.RIGHT_BRACKET = 0x4; var COLON = C.COLON = 0x5; var COMMA = C.COMMA = 0x6; var TRUE = C.TRUE = 0x7; var FALSE = C.FALSE = 0x8; var NULL = C.NULL = 0x9; var STRING = C.STRING = 0xa; var NUMBER = C.NUMBER = 0xb; // Tokenizer States var START = C.START = 0x11; var STOP = C.STOP = 0x12; var TRUE1 = C.TRUE1 = 0x21; var TRUE2 = C.TRUE2 = 0x22; var TRUE3 = C.TRUE3 = 0x23; var FALSE1 = C.FALSE1 = 0x31; var FALSE2 = C.FALSE2 = 0x32; var FALSE3 = C.FALSE3 = 0x33; var FALSE4 = C.FALSE4 = 0x34; var NULL1 = C.NULL1 = 0x41; var NULL2 = C.NULL2 = 0x42; var NULL3 = C.NULL3 = 0x43; var NUMBER1 = C.NUMBER1 = 0x51; var NUMBER3 = C.NUMBER3 = 0x53; var STRING1 = C.STRING1 = 0x61; var STRING2 = C.STRING2 = 0x62; var STRING3 = C.STRING3 = 0x63; var STRING4 = C.STRING4 = 0x64; var STRING5 = C.STRING5 = 0x65; var STRING6 = C.STRING6 = 0x66; // Parser States var VALUE = C.VALUE = 0x71; var KEY = C.KEY = 0x72; // Parser Modes var OBJECT = C.OBJECT = 0x81; var ARRAY = C.ARRAY = 0x82; // Character constants var BACK_SLASH = "\\".charCodeAt(0); var FORWARD_SLASH = "\/".charCodeAt(0); var BACKSPACE = "\b".charCodeAt(0); var FORM_FEED = "\f".charCodeAt(0); var NEWLINE = "\n".charCodeAt(0); var CARRIAGE_RETURN = "\r".charCodeAt(0); var TAB = "\t".charCodeAt(0); var STRING_BUFFER_SIZE = 64 * 1024; function Parser() { this.tState = START; this.value = undefined; this.string = undefined; // string data this.stringBuffer = Buffer.alloc ? Buffer.alloc(STRING_BUFFER_SIZE) : new Buffer(STRING_BUFFER_SIZE); this.stringBufferOffset = 0; this.unicode = undefined; // unicode escapes this.highSurrogate = undefined; this.key = undefined; this.mode = undefined; this.stack = []; this.state = VALUE; this.bytes_remaining = 0; // number of bytes remaining in multi byte utf8 char to read after split boundary this.bytes_in_sequence = 0; // bytes in multi byte utf8 char to read this.temp_buffs = { "2": new Buffer(2), "3": new Buffer(3), "4": new Buffer(4) }; // for rebuilding chars split before boundary is reached // Stream offset this.offset = -1; } // Slow code to string converter (only used when throwing syntax errors) Parser.toknam = function (code) { var keys = Object.keys(C); for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; if (C[key] === code) { return key; } } return code && ("0x" + code.toString(16)); }; var proto = Parser.prototype; proto.onError = function (err) { throw err; }; proto.charError = function (buffer, i) { this.tState = STOP; this.onError(new Error("Unexpected " + JSON.stringify(String.fromCharCode(buffer[i])) + " at position " + i + " in state " + Parser.toknam(this.tState))); }; proto.appendStringChar = function (char) { if (this.stringBufferOffset >= STRING_BUFFER_SIZE) { this.string += this.stringBuffer.toString('utf8'); this.stringBufferOffset = 0; } this.stringBuffer[this.stringBufferOffset++] = char; }; proto.appendStringBuf = function (buf, start, end) { var size = buf.length; if (typeof start === 'number') { if (typeof end === 'number') { if (end < 0) { // adding a negative end decreeses the size size = buf.length - start + end; } else { size = end - start; } } else { size = buf.length - start; } } if (size < 0) { size = 0; } if (this.stringBufferOffset + size > STRING_BUFFER_SIZE) { this.string += this.stringBuffer.toString('utf8', 0, this.stringBufferOffset); this.stringBufferOffset = 0; } buf.copy(this.stringBuffer, this.stringBufferOffset, start, end); this.stringBufferOffset += size; }; proto.write = function (buffer) { if (typeof buffer === "string") buffer = new Buffer(buffer); var n; for (var i = 0, l = buffer.length; i < l; i++) { if (this.tState === START){ n = buffer[i]; this.offset++; if(n === 0x7b){ this.onToken(LEFT_BRACE, "{"); // { }else if(n === 0x7d){ this.onToken(RIGHT_BRACE, "}"); // } }else if(n === 0x5b){ this.onToken(LEFT_BRACKET, "["); // [ }else if(n === 0x5d){ this.onToken(RIGHT_BRACKET, "]"); // ] }else if(n === 0x3a){ this.onToken(COLON, ":"); // : }else if(n === 0x2c){ this.onToken(COMMA, ","); // , }else if(n === 0x74){ this.tState = TRUE1; // t }else if(n === 0x66){ this.tState = FALSE1; // f }else if(n === 0x6e){ this.tState = NULL1; // n }else if(n === 0x22){ // " this.string = ""; this.stringBufferOffset = 0; this.tState = STRING1; }else if(n === 0x2d){ this.string = "-"; this.tState = NUMBER1; // - }else{ if (n >= 0x30 && n < 0x40) { // 1-9 this.string = String.fromCharCode(n); this.tState = NUMBER3; } else if (n === 0x20 || n === 0x09 || n === 0x0a || n === 0x0d) { // whitespace } else { return this.charError(buffer, i); } } }else if (this.tState === STRING1){ // After open quote n = buffer[i]; // get current byte from buffer // check for carry over of a multi byte char split between data chunks // & fill temp buffer it with start of this data chunk up to the boundary limit set in the last iteration if (this.bytes_remaining > 0) { for (var j = 0; j < this.bytes_remaining; j++) { this.temp_buffs[this.bytes_in_sequence][this.bytes_in_sequence - this.bytes_remaining + j] = buffer[j]; } this.appendStringBuf(this.temp_buffs[this.bytes_in_sequence]); this.bytes_in_sequence = this.bytes_remaining = 0; i = i + j - 1; } else if (this.bytes_remaining === 0 && n >= 128) { // else if no remainder bytes carried over, parse multi byte (>=128) chars one at a time if (n <= 193 || n > 244) { return this.onError(new Error("Invalid UTF-8 character at position " + i + " in state " + Parser.toknam(this.tState))); } if ((n >= 194) && (n <= 223)) this.bytes_in_sequence = 2; if ((n >= 224) && (n <= 239)) this.bytes_in_sequence = 3; if ((n >= 240) && (n <= 244)) this.bytes_in_sequence = 4; if ((this.bytes_in_sequence + i) > buffer.length) { // if bytes needed to complete char fall outside buffer length, we have a boundary split for (var k = 0; k <= (buffer.length - 1 - i); k++) { this.temp_buffs[this.bytes_in_sequence][k] = buffer[i + k]; // fill temp buffer of correct size with bytes available in this chunk } this.bytes_remaining = (i + this.bytes_in_sequence) - buffer.length; i = buffer.length - 1; } else { this.appendStringBuf(buffer, i, i + this.bytes_in_sequence); i = i + this.bytes_in_sequence - 1; } } else if (n === 0x22) { this.tState = START; this.string += this.stringBuffer.toString('utf8', 0, this.stringBufferOffset); this.stringBufferOffset = 0; this.onToken(STRING, this.string); this.offset += Buffer.byteLength(this.string, 'utf8') + 1; this.string = undefined; } else if (n === 0x5c) { this.tState = STRING2; } else if (n >= 0x20) { this.appendStringChar(n); } else { return this.charError(buffer, i); } }else if (this.tState === STRING2){ // After backslash n = buffer[i]; if(n === 0x22){ this.appendStringChar(n); this.tState = STRING1; }else if(n === 0x5c){ this.appendStringChar(BACK_SLASH); this.tState = STRING1; }else if(n === 0x2f){ this.appendStringChar(FORWARD_SLASH); this.tState = STRING1; }else if(n === 0x62){ this.appendStringChar(BACKSPACE); this.tState = STRING1; }else if(n === 0x66){ this.appendStringChar(FORM_FEED); this.tState = STRING1; }else if(n === 0x6e){ this.appendStringChar(NEWLINE); this.tState = STRING1; }else if(n === 0x72){ this.appendStringChar(CARRIAGE_RETURN); this.tState = STRING1; }else if(n === 0x74){ this.appendStringChar(TAB); this.tState = STRING1; }else if(n === 0x75){ this.unicode = ""; this.tState = STRING3; }else{ return this.charError(buffer, i); } }else if (this.tState === STRING3 || this.tState === STRING4 || this.tState === STRING5 || this.tState === STRING6){ // unicode hex codes n = buffer[i]; // 0-9 A-F a-f if ((n >= 0x30 && n < 0x40) || (n > 0x40 && n <= 0x46) || (n > 0x60 && n <= 0x66)) { this.unicode += String.fromCharCode(n); if (this.tState++ === STRING6) { var intVal = parseInt(this.unicode, 16); this.unicode = undefined; if (this.highSurrogate !== undefined && intVal >= 0xDC00 && intVal < (0xDFFF + 1)) { //<56320,57343> - lowSurrogate this.appendStringBuf(new Buffer(String.fromCharCode(this.highSurrogate, intVal))); this.highSurrogate = undefined; } else if (this.highSurrogate === undefined && intVal >= 0xD800 && intVal < (0xDBFF + 1)) { //<55296,56319> - highSurrogate this.highSurrogate = intVal; } else { if (this.highSurrogate !== undefined) { this.appendStringBuf(new Buffer(String.fromCharCode(this.highSurrogate))); this.highSurrogate = undefined; } this.appendStringBuf(new Buffer(String.fromCharCode(intVal))); } this.tState = STRING1; } } else { return this.charError(buffer, i); } } else if (this.tState === NUMBER1 || this.tState === NUMBER3) { n = buffer[i]; switch (n) { case 0x30: // 0 case 0x31: // 1 case 0x32: // 2 case 0x33: // 3 case 0x34: // 4 case 0x35: // 5 case 0x36: // 6 case 0x37: // 7 case 0x38: // 8 case 0x39: // 9 case 0x2e: // . case 0x65: // e case 0x45: // E case 0x2b: // + case 0x2d: // - this.string += String.fromCharCode(n); this.tState = NUMBER3; break; default: this.tState = START; var result = Number(this.string); if (isNaN(result)){ return this.charError(buffer, i); } if ((this.string.match(/[0-9]+/) == this.string) && (result.toString() != this.string)) { // Long string of digits which is an ID string and not valid and/or safe JavaScript integer Number this.onToken(STRING, this.string); } else { this.onToken(NUMBER, result); } this.offset += this.string.length - 1; this.string = undefined; i--; break; } }else if (this.tState === TRUE1){ // r if (buffer[i] === 0x72) { this.tState = TRUE2; } else { return this.charError(buffer, i); } }else if (this.tState === TRUE2){ // u if (buffer[i] === 0x75) { this.tState = TRUE3; } else { return this.charError(buffer, i); } }else if (this.tState === TRUE3){ // e if (buffer[i] === 0x65) { this.tState = START; this.onToken(TRUE, true); this.offset+= 3; } else { return this.charError(buffer, i); } }else if (this.tState === FALSE1){ // a if (buffer[i] === 0x61) { this.tState = FALSE2; } else { return this.charError(buffer, i); } }else if (this.tState === FALSE2){ // l if (buffer[i] === 0x6c) { this.tState = FALSE3; } else { return this.charError(buffer, i); } }else if (this.tState === FALSE3){ // s if (buffer[i] === 0x73) { this.tState = FALSE4; } else { return this.charError(buffer, i); } }else if (this.tState === FALSE4){ // e if (buffer[i] === 0x65) { this.tState = START; this.onToken(FALSE, false); this.offset+= 4; } else { return this.charError(buffer, i); } }else if (this.tState === NULL1){ // u if (buffer[i] === 0x75) { this.tState = NULL2; } else { return this.charError(buffer, i); } }else if (this.tState === NULL2){ // l if (buffer[i] === 0x6c) { this.tState = NULL3; } else { return this.charError(buffer, i); } }else if (this.tState === NULL3){ // l if (buffer[i] === 0x6c) { this.tState = START; this.onToken(NULL, null); this.offset += 3; } else { return this.charError(buffer, i); } } } }; proto.onToken = function (token, value) { // Override this to get events }; proto.parseError = function (token, value) { this.tState = STOP; this.onError(new Error("Unexpected " + Parser.toknam(token) + (value ? ("(" + JSON.stringify(value) + ")") : "") + " in state " + Parser.toknam(this.state))); }; proto.push = function () { this.stack.push({value: this.value, key: this.key, mode: this.mode}); }; proto.pop = function () { var value = this.value; var parent = this.stack.pop(); this.value = parent.value; this.key = parent.key; this.mode = parent.mode; this.emit(value); if (!this.mode) { this.state = VALUE; } }; proto.emit = function (value) { if (this.mode) { this.state = COMMA; } this.onValue(value); }; proto.onValue = function (value) { // Override me }; proto.onToken = function (token, value) { if(this.state === VALUE){ if(token === STRING || token === NUMBER || token === TRUE || token === FALSE || token === NULL){ if (this.value) { this.value[this.key] = value; } this.emit(value); }else if(token === LEFT_BRACE){ this.push(); if (this.value) { this.value = this.value[this.key] = {}; } else { this.value = {}; } this.key = undefined; this.state = KEY; this.mode = OBJECT; }else if(token === LEFT_BRACKET){ this.push(); if (this.value) { this.value = this.value[this.key] = []; } else { this.value = []; } this.key = 0; this.mode = ARRAY; this.state = VALUE; }else if(token === RIGHT_BRACE){ if (this.mode === OBJECT) { this.pop(); } else { return this.parseError(token, value); } }else if(token === RIGHT_BRACKET){ if (this.mode === ARRAY) { this.pop(); } else { return this.parseError(token, value); } }else{ return this.parseError(token, value); } }else if(this.state === KEY){ if (token === STRING) { this.key = value; this.state = COLON; } else if (token === RIGHT_BRACE) { this.pop(); } else { return this.parseError(token, value); } }else if(this.state === COLON){ if (token === COLON) { this.state = VALUE; } else { return this.parseError(token, value); } }else if(this.state === COMMA){ if (token === COMMA) { if (this.mode === ARRAY) { this.key++; this.state = VALUE; } else if (this.mode === OBJECT) { this.state = KEY; } } else if (token === RIGHT_BRACKET && this.mode === ARRAY || token === RIGHT_BRACE && this.mode === OBJECT) { this.pop(); } else { return this.parseError(token, value); } }else{ return this.parseError(token, value); } }; Parser.C = C; module.exports = Parser; PK ~\4ҳjsonparse/test/offset.jsnu[var test = require('tape'); var Parser = require('../'); var input = '{\n "string": "value",\n "number": 3,\n "object"'; var input2 = ': {\n "key": "vд"\n },\n "array": [\n -1,\n 12\n ]\n '; var input3 = '"null": null, "true": true, "false": false, "frac": 3.14 }'; var offsets = [ [ 0, Parser.C.LEFT_BRACE ], [ 4, Parser.C.STRING ], [ 12, Parser.C.COLON ], [ 14, Parser.C.STRING ], [ 21, Parser.C.COMMA ], [ 25, Parser.C.STRING ], [ 33, Parser.C.COLON ], [ 35, Parser.C.NUMBER ], [ 36, Parser.C.COMMA ], [ 40, Parser.C.STRING ], [ 48, Parser.C.COLON ], [ 50, Parser.C.LEFT_BRACE ], [ 54, Parser.C.STRING ], [ 59, Parser.C.COLON ], [ 61, Parser.C.STRING ], [ 69, Parser.C.RIGHT_BRACE ], [ 70, Parser.C.COMMA ], [ 74, Parser.C.STRING ], [ 81, Parser.C.COLON ], [ 83, Parser.C.LEFT_BRACKET ], [ 87, Parser.C.NUMBER ], [ 89, Parser.C.COMMA ], [ 93, Parser.C.NUMBER ], [ 98, Parser.C.RIGHT_BRACKET ], [ 102, Parser.C.STRING ], [ 108, Parser.C.COLON ], [ 110, Parser.C.NULL ], [ 114, Parser.C.COMMA ], [ 116, Parser.C.STRING ], [ 122, Parser.C.COLON ], [ 124, Parser.C.TRUE ], [ 128, Parser.C.COMMA ], [ 130, Parser.C.STRING ], [ 137, Parser.C.COLON ], [ 139, Parser.C.FALSE ], [ 144, Parser.C.COMMA ], [ 146, Parser.C.STRING ], [ 152, Parser.C.COLON ], [ 154, Parser.C.NUMBER ], [ 159, Parser.C.RIGHT_BRACE ] ]; test('offset', function(t) { t.plan(offsets.length * 2 + 1); var p = new Parser(); var i = 0; p.onToken = function (token) { t.equal(p.offset, offsets[i][0]); t.equal(token, offsets[i][1]); i++; }; p.write(input); p.write(input2); p.write(input3); t.equal(i, offsets.length); }); PK ~\2jsonparse/test/primitives.jsnu[var test = require('tape'); var Parser = require('../'); var expected = [ [ [], '' ], [ [], 'Hello' ], [ [], 'This"is' ], [ [], '\r\n\f\t\\/"' ], [ [], 'Λάμβδα' ], [ [], '\\' ], [ [], '/' ], [ [], '"' ], [ [ 0 ], 0 ], [ [ 1 ], 1 ], [ [ 2 ], -1 ], [ [], [ 0, 1, -1 ] ], [ [ 0 ], 1 ], [ [ 1 ], 1.1 ], [ [ 2 ], -1.1 ], [ [ 3 ], -1 ], [ [], [ 1, 1.1, -1.1, -1 ] ], [ [ 0 ], -1 ], [ [], [ -1 ] ], [ [ 0 ], -0.1 ], [ [], [ -0.1 ] ], [ [ 0 ], 6.02e+23 ], [ [], [ 6.02e+23 ] ], [ [ 0 ], '7161093205057351174' ], [ [], [ '7161093205057351174'] ] ]; test('primitives', function (t) { t.plan(25); var p = new Parser(); p.onValue = function (value) { var keys = this.stack .slice(1) .map(function (item) { return item.key }) .concat(this.key !== undefined ? this.key : []) ; t.deepEqual( [ keys, value ], expected.shift() ); }; p.write('"""Hello""This\\"is""\\r\\n\\f\\t\\\\\\/\\""'); p.write('"\\u039b\\u03ac\\u03bc\\u03b2\\u03b4\\u03b1"'); p.write('"\\\\"'); p.write('"\\/"'); p.write('"\\""'); p.write('[0,1,-1]'); p.write('[1.0,1.1,-1.1,-1.0][-1][-0.1]'); p.write('[6.02e23]'); p.write('[7161093205057351174]'); }); PK ~\"!/ jsonparse/test/boundary.jsnu[var test = require('tape'); var Parser = require('../'); test('2 byte utf8 \'De\' character: д', function (t) { t.plan(1); var p = new Parser(); p.onValue = function (value) { t.equal(value, 'д'); }; var de_buffer = new Buffer([0xd0, 0xb4]); p.write('"'); p.write(de_buffer); p.write('"'); }); test('3 byte utf8 \'Han\' character: 我', function (t) { t.plan(1); var p = new Parser(); p.onValue = function (value) { t.equal(value, '我'); }; var han_buffer = new Buffer([0xe6, 0x88, 0x91]); p.write('"'); p.write(han_buffer); p.write('"'); }); test('4 byte utf8 character (unicode scalar U+2070E): 𠜎', function (t) { t.plan(1); var p = new Parser(); p.onValue = function (value) { t.equal(value, '𠜎'); }; var Ux2070E_buffer = new Buffer([0xf0, 0xa0, 0x9c, 0x8e]); p.write('"'); p.write(Ux2070E_buffer); p.write('"'); }); test('3 byte utf8 \'Han\' character chunked inbetween 2nd and 3rd byte: 我', function (t) { t.plan(1); var p = new Parser(); p.onValue = function (value) { t.equal(value, '我'); }; var han_buffer_first = new Buffer([0xe6, 0x88]); var han_buffer_second = new Buffer([0x91]); p.write('"'); p.write(han_buffer_first); p.write(han_buffer_second); p.write('"'); }); test('4 byte utf8 character (unicode scalar U+2070E) chunked inbetween 2nd and 3rd byte: 𠜎', function (t) { t.plan(1); var p = new Parser(); p.onValue = function (value) { t.equal(value, '𠜎'); }; var Ux2070E_buffer_first = new Buffer([0xf0, 0xa0]); var Ux2070E_buffer_second = new Buffer([0x9c, 0x8e]); p.write('"'); p.write(Ux2070E_buffer_first); p.write(Ux2070E_buffer_second); p.write('"'); }); test('1-4 byte utf8 character string chunked inbetween random bytes: Aж文𠜱B', function (t) { t.plan(1); var p = new Parser(); p.onValue = function (value) { t.equal(value, 'Aж文𠜱B'); }; var eclectic_buffer = new Buffer([0x41, // A 0xd0, 0xb6, // ж 0xe6, 0x96, 0x87, // 文 0xf0, 0xa0, 0x9c, 0xb1, // 𠜱 0x42]); // B var rand_chunk = Math.floor(Math.random() * (eclectic_buffer.length)); var first_buffer = eclectic_buffer.slice(0, rand_chunk); var second_buffer = eclectic_buffer.slice(rand_chunk); //console.log('eclectic_buffer: ' + eclectic_buffer) //console.log('sliced from 0 to ' + rand_chunk); //console.log(first_buffer); //console.log('then sliced from ' + rand_chunk + ' to the end'); //console.log(second_buffer); console.log('chunked after offset ' + rand_chunk); p.write('"'); p.write(first_buffer); p.write(second_buffer); p.write('"'); });PK ~\Oejsonparse/test/surrogate.jsnu[var test = require('tape'); var Parser = require('../'); test('parse surrogate pair', function (t) { t.plan(1); var p = new Parser(); p.onValue = function (value) { t.equal(value, '😋'); }; p.write('"\\uD83D\\uDE0B"'); }); test('parse chunked surrogate pair', function (t) { t.plan(1); var p = new Parser(); p.onValue = function (value) { t.equal(value, '😋'); }; p.write('"\\uD83D'); p.write('\\uDE0B"'); }); PK ~\n\jsonparse/test/unvalid.jsnu[var test = require('tape'); var Parser = require('../'); test('unvalid', function (t) { var count = 0; var p = new Parser(); p.onError = function (value) { count++; t.equal(1, count); t.end(); }; p.write('{"test": eer['); }); PK ~\n jsonparse/test/utf8.jsnu[var test = require('tape'); var Parser = require('../'); test('3 bytes of utf8', function (t) { t.plan(1); var p = new Parser(); p.onValue = function (value) { t.equal(value, '├──'); }; p.write('"├──"'); }); test('utf8 snowman', function (t) { t.plan(1); var p = new Parser(); p.onValue = function (value) { t.equal(value, '☃'); }; p.write('"☃"'); }); test('utf8 with regular ascii', function (t) { t.plan(4); var p = new Parser(); var expected = [ "snow: ☃!", "xyz", "¡que!" ]; expected.push(expected.slice()); p.onValue = function (value) { t.deepEqual(value, expected.shift()); }; p.write('["snow: ☃!","xyz","¡que!"]'); }); PK ~\=!jsonparse/test/big-token.jsnu[var stream = require('stream'); var JsonParse = require('../jsonparse'); var test = require('tape'); test('can handle large tokens without running out of memory', function (t) { var parser = new JsonParse(); var chunkSize = 1024; var chunks = 1024 * 200; // 200mb var quote = Buffer.from ? Buffer.from('"') : new Buffer('"'); t.plan(1); parser.onToken = function (type, value) { t.equal(value.length, chunkSize * chunks, 'token should be size of input json'); t.end(); }; parser.write(quote); for (var i = 0; i < chunks; ++i) { var buf = Buffer.alloc ? Buffer.alloc(chunkSize) : new Buffer(chunkSize); buf.fill('a'); parser.write(buf); } parser.write(quote); }); PK ~\^OV"??jsonparse/LICENSEnu[The MIT License Copyright (c) 2012 Tim Caswell Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\03,,jsonparse/bench.jsnu[var fs = require('fs'), Parser = require('./jsonparse'); var json = fs.readFileSync("samplejson/basic.json"); while (true) { var start = Date.now(); for (var i = 0; i < 1000; i++) { JSON.parse(json); } var first = Date.now() - start; start = Date.now(); var p = new Parser(); for (var i = 0; i < 1000; i++) { p.write(json); } var second = Date.now() - start; console.log("JSON.parse took %s", first); console.log("streaming parser took %s", second); console.log("streaming is %s times slower", second / first); } PK ~\3&!jsonparse/examples/twitterfeed.jsnu[var Parser = require('../jsonparse'); var Http = require('http'); require('./colors'); var p = new Parser(); var cred = require('./credentials'); var client = Http.createClient(80, "stream.twitter.com"); var request = client.request("GET", "/1/statuses/sample.json", { "Host": "stream.twitter.com", "Authorization": (new Buffer(cred.username + ":" + cred.password)).toString("base64") }); request.on('response', function (response) { console.log(response.statusCode); console.dir(response.headers); response.on('data', function (chunk) { p.write(chunk); }); response.on('end', function () { console.log("END"); }); }); request.end(); var text = "", name = ""; p.onValue = function (value) { if (this.stack.length === 1 && this.key === 'text') { text = value; } if (this.stack.length === 2 && this.key === 'name' && this.stack[1].key === 'user') { name = value; } if (this.stack.length === 0) { console.log(text.blue + " - " + name.yellow); text = name = ""; } }; PK ~\N { createDebug[key] = env[key]; }); /** * The currently active debug mode names, and names to skip. */ createDebug.names = []; createDebug.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ createDebug.formatters = {}; /** * Selects a color for a debug namespace * @param {String} namespace The namespace string for the debug instance to be colored * @return {Number|String} An ANSI color code for the given namespace * @api private */ function selectColor(namespace) { let hash = 0; for (let i = 0; i < namespace.length; i++) { hash = ((hash << 5) - hash) + namespace.charCodeAt(i); hash |= 0; // Convert to 32bit integer } return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; } createDebug.selectColor = selectColor; /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function createDebug(namespace) { let prevTime; let enableOverride = null; let namespacesCache; let enabledCache; function debug(...args) { // Disabled? if (!debug.enabled) { return; } const self = debug; // Set `diff` timestamp const curr = Number(new Date()); const ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; args[0] = createDebug.coerce(args[0]); if (typeof args[0] !== 'string') { // Anything else let's inspect with %O args.unshift('%O'); } // Apply any `formatters` transformations let index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { // If we encounter an escaped % then don't increase the array index if (match === '%%') { return '%'; } index++; const formatter = createDebug.formatters[format]; if (typeof formatter === 'function') { const val = args[index]; match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // Apply env-specific formatting (colors, etc.) createDebug.formatArgs.call(self, args); const logFn = self.log || createDebug.log; logFn.apply(self, args); } debug.namespace = namespace; debug.useColors = createDebug.useColors(); debug.color = createDebug.selectColor(namespace); debug.extend = extend; debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. Object.defineProperty(debug, 'enabled', { enumerable: true, configurable: false, get: () => { if (enableOverride !== null) { return enableOverride; } if (namespacesCache !== createDebug.namespaces) { namespacesCache = createDebug.namespaces; enabledCache = createDebug.enabled(namespace); } return enabledCache; }, set: v => { enableOverride = v; } }); // Env-specific initialization logic for debug instances if (typeof createDebug.init === 'function') { createDebug.init(debug); } return debug; } function extend(namespace, delimiter) { const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); newDebug.log = this.log; return newDebug; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { createDebug.save(namespaces); createDebug.namespaces = namespaces; createDebug.names = []; createDebug.skips = []; let i; const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); const len = split.length; for (i = 0; i < len; i++) { if (!split[i]) { // ignore empty strings continue; } namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); } else { createDebug.names.push(new RegExp('^' + namespaces + '$')); } } } /** * Disable debug output. * * @return {String} namespaces * @api public */ function disable() { const namespaces = [ ...createDebug.names.map(toNamespace), ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) ].join(','); createDebug.enable(''); return namespaces; } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { if (name[name.length - 1] === '*') { return true; } let i; let len; for (i = 0, len = createDebug.skips.length; i < len; i++) { if (createDebug.skips[i].test(name)) { return false; } } for (i = 0, len = createDebug.names.length; i < len; i++) { if (createDebug.names[i].test(name)) { return true; } } return false; } /** * Convert regexp to namespace * * @param {RegExp} regxep * @return {String} namespace * @api private */ function toNamespace(regexp) { return regexp.toString() .substring(2, regexp.toString().length - 2) .replace(/\.\*\?$/, '*'); } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) { return val.stack || val.message; } return val; } /** * XXX DO NOT USE. This is a temporary stub function. * XXX It WILL be removed in the next major release. */ function destroy() { console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } createDebug.enable(createDebug.load()); return createDebug; } module.exports = setup; PK ~\GNMMdebug/src/node.jsnu[/** * Module dependencies. */ const tty = require('tty'); const util = require('util'); /** * This is the Node.js implementation of `debug()`. */ exports.init = init; exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.destroy = util.deprecate( () => {}, 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' ); /** * Colors. */ exports.colors = [6, 2, 3, 4, 5, 1]; try { // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) // eslint-disable-next-line import/no-extraneous-dependencies const supportsColor = require('supports-color'); if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { exports.colors = [ 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 214, 215, 220, 221 ]; } } catch (error) { // Swallow - we only care if `supports-color` is available; it doesn't have to be. } /** * Build up the default `inspectOpts` object from the environment variables. * * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ exports.inspectOpts = Object.keys(process.env).filter(key => { return /^debug_/i.test(key); }).reduce((obj, key) => { // Camel-case const prop = key .substring(6) .toLowerCase() .replace(/_([a-z])/g, (_, k) => { return k.toUpperCase(); }); // Coerce string value into JS value let val = process.env[key]; if (/^(yes|on|true|enabled)$/i.test(val)) { val = true; } else if (/^(no|off|false|disabled)$/i.test(val)) { val = false; } else if (val === 'null') { val = null; } else { val = Number(val); } obj[prop] = val; return obj; }, {}); /** * Is stdout a TTY? Colored output is enabled when `true`. */ function useColors() { return 'colors' in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd); } /** * Adds ANSI color escape codes if enabled. * * @api public */ function formatArgs(args) { const {namespace: name, useColors} = this; if (useColors) { const c = this.color; const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); const prefix = ` ${colorCode};1m${name} \u001B[0m`; args[0] = prefix + args[0].split('\n').join('\n' + prefix); args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); } else { args[0] = getDate() + name + ' ' + args[0]; } } function getDate() { if (exports.inspectOpts.hideDate) { return ''; } return new Date().toISOString() + ' '; } /** * Invokes `util.format()` with the specified arguments and writes to stderr. */ function log(...args) { return process.stderr.write(util.format(...args) + '\n'); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { if (namespaces) { process.env.DEBUG = namespaces; } else { // If you set a process.env field to null or undefined, it gets cast to the // string 'null' or 'undefined'. Just delete instead. delete process.env.DEBUG; } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { return process.env.DEBUG; } /** * Init logic for `debug` instances. * * Create a new `inspectOpts` object in case `useColors` is set * differently for a particular `debug` instance. */ function init(debug) { debug.inspectOpts = {}; const keys = Object.keys(exports.inspectOpts); for (let i = 0; i < keys.length; i++) { debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; } } module.exports = require('./common')(exports); const {formatters} = module.exports; /** * Map %o to `util.inspect()`, all on a single line. */ formatters.o = function (v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts) .split('\n') .map(str => str.trim()) .join(' '); }; /** * Map %O to `util.inspect()`, allowing multiple lines if needed. */ formatters.O = function (v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts); }; PK ~\>"zzdebug/src/browser.jsnu[/* eslint-env browser */ /** * This is the web browser implementation of `debug()`. */ exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = localstorage(); exports.destroy = (() => { let warned = false; return () => { if (!warned) { warned = true; console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } }; })(); /** * Colors. */ exports.colors = [ '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ // eslint-disable-next-line complexity function useColors() { // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { return true; } // Internet Explorer and Edge do not support colors. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { return false; } // Is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || // Is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || // Is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || // Double check webkit in userAgent just in case we are in a worker (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** * Colorize log arguments if enabled. * * @api public */ function formatArgs(args) { args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff); if (!this.useColors) { return; } const c = 'color: ' + this.color; args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into let index = 0; let lastC = 0; args[0].replace(/%[a-zA-Z%]/g, match => { if (match === '%%') { return; } index++; if (match === '%c') { // We only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); } /** * Invokes `console.debug()` when available. * No-op when `console.debug` is not a "function". * If `console.debug` is not available, falls back * to `console.log`. * * @api public */ exports.log = console.debug || console.log || (() => {}); /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (namespaces) { exports.storage.setItem('debug', namespaces); } else { exports.storage.removeItem('debug'); } } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { let r; try { r = exports.storage.getItem('debug'); } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (!r && typeof process !== 'undefined' && 'env' in process) { r = process.env.DEBUG; } return r; } /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage() { try { // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context // The Browser also has localStorage in the global context. return localStorage; } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } module.exports = require('./common')(exports); const {formatters} = module.exports; /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ formatters.j = function (v) { try { return JSON.stringify(v); } catch (error) { return '[UnexpectedJSONParseError]: ' + error.message; } }; PK ~\Ѫdebug/package.jsonnu[{ "_id": "debug@4.3.4", "_inBundle": true, "_location": "/npm/debug", "_phantomChildren": {}, "_requiredBy": [ "/npm/agent-base", "/npm/http-proxy-agent", "/npm/https-proxy-agent", "/npm/socks-proxy-agent", "/npm/tuf-js" ], "author": { "name": "Josh Junon", "email": "josh.junon@protonmail.com" }, "browser": "./src/browser.js", "bugs": { "url": "https://github.com/debug-js/debug/issues" }, "contributors": [ { "name": "TJ Holowaychuk", "email": "tj@vision-media.ca" }, { "name": "Nathan Rajlich", "email": "nathan@tootallnate.net", "url": "http://n8.io" }, { "name": "Andrew Rhyne", "email": "rhyneandrew@gmail.com" } ], "dependencies": { "ms": "2.1.2" }, "description": "Lightweight debugging utility for Node.js and the browser", "devDependencies": { "brfs": "^2.0.1", "browserify": "^16.2.3", "coveralls": "^3.0.2", "istanbul": "^0.4.5", "karma": "^3.1.4", "karma-browserify": "^6.0.0", "karma-chrome-launcher": "^2.2.0", "karma-mocha": "^1.3.0", "mocha": "^5.2.0", "mocha-lcov-reporter": "^1.2.0", "xo": "^0.23.0" }, "engines": { "node": ">=6.0" }, "files": [ "src", "LICENSE", "README.md" ], "homepage": "https://github.com/debug-js/debug#readme", "keywords": [ "debug", "log", "debugger" ], "license": "MIT", "main": "./src/index.js", "name": "debug", "peerDependenciesMeta": { "supports-color": { "optional": true } }, "repository": { "type": "git", "url": "git://github.com/debug-js/debug.git" }, "scripts": { "lint": "xo", "test": "npm run test:node && npm run test:browser && npm run lint", "test:browser": "karma start --single-run", "test:coverage": "cat ./coverage/lcov.info | coveralls", "test:node": "istanbul cover _mocha -- test.js" }, "version": "4.3.4" } PK ~\iS"debug/node_modules/ms/package.jsonnu[{ "_id": "ms@2.1.2", "_inBundle": true, "_location": "/npm/debug/ms", "_phantomChildren": {}, "_requiredBy": [ "/npm/debug" ], "bugs": { "url": "https://github.com/zeit/ms/issues" }, "description": "Tiny millisecond conversion utility", "devDependencies": { "eslint": "4.12.1", "expect.js": "0.3.1", "husky": "0.14.3", "lint-staged": "5.0.0", "mocha": "4.0.1" }, "eslintConfig": { "extends": "eslint:recommended", "env": { "node": true, "es6": true } }, "files": [ "index.js" ], "homepage": "https://github.com/zeit/ms#readme", "license": "MIT", "lint-staged": { "*.js": [ "npm run lint", "prettier --single-quote --write", "git add" ] }, "main": "./index", "name": "ms", "repository": { "type": "git", "url": "git+https://github.com/zeit/ms.git" }, "scripts": { "lint": "eslint lib/* bin/*", "precommit": "lint-staged", "test": "mocha tests.js" }, "version": "2.1.2" } PK ~\r debug/node_modules/ms/index.jsnu[/** * Helpers. */ var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; var w = d * 7; var y = d * 365.25; /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} [options] * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ module.exports = function(val, options) { options = options || {}; var type = typeof val; if (type === 'string' && val.length > 0) { return parse(val); } else if (type === 'number' && isFinite(val)) { return options.long ? fmtLong(val) : fmtShort(val); } throw new Error( 'val is not a non-empty string or a valid number. val=' + JSON.stringify(val) ); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = String(str); if (str.length > 100) { return; } var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( str ); if (!match) { return; } var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y; case 'weeks': case 'week': case 'w': return n * w; case 'days': case 'day': case 'd': return n * d; case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h; case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m; case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s; case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n; default: return undefined; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return Math.round(ms / d) + 'd'; } if (msAbs >= h) { return Math.round(ms / h) + 'h'; } if (msAbs >= m) { return Math.round(ms / m) + 'm'; } if (msAbs >= s) { return Math.round(ms / s) + 's'; } return ms + 'ms'; } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return plural(ms, msAbs, d, 'day'); } if (msAbs >= h) { return plural(ms, msAbs, h, 'hour'); } if (msAbs >= m) { return plural(ms, msAbs, m, 'minute'); } if (msAbs >= s) { return plural(ms, msAbs, s, 'second'); } return ms + ' ms'; } /** * Pluralization helper. */ function plural(ms, msAbs, n, name) { var isPlural = msAbs >= n * 1.5; return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); } PK ~\i 55 debug/node_modules/ms/license.mdnu[The MIT License (MIT) Copyright (c) 2016 Zeit, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\ߟss debug/LICENSEnu[(The MIT License) Copyright (c) 2014-2017 TJ Holowaychuk Copyright (c) 2018-2021 Josh Junon Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK ~\|r'bin-links/package.jsonnu[{ "_id": "bin-links@4.0.4", "_inBundle": true, "_location": "/npm/bin-links", "_phantomChildren": {}, "_requiredBy": [ "/npm/@npmcli/arborist" ], "author": { "name": "GitHub Inc." }, "bugs": { "url": "https://github.com/npm/bin-links/issues" }, "dependencies": { "cmd-shim": "^6.0.0", "npm-normalize-package-bin": "^3.0.0", "read-cmd-shim": "^4.0.0", "write-file-atomic": "^5.0.0" }, "description": "JavaScript package binary linker", "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.22.0", "require-inject": "^1.4.4", "tap": "^16.0.1" }, "engines": { "node": "^14.17.0 || ^16.13.0 || >=18.0.0" }, "files": [ "bin/", "lib/" ], "homepage": "https://github.com/npm/bin-links#readme", "keywords": [ "npm", "link", "bins" ], "license": "ISC", "main": "./lib/index.js", "name": "bin-links", "repository": { "type": "git", "url": "git+https://github.com/npm/bin-links.git" }, "scripts": { "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", "lintfix": "npm run lint -- --fix", "postlint": "template-oss-check", "posttest": "npm run lint", "snap": "tap", "template-oss-apply": "template-oss-apply --force", "test": "tap" }, "tap": { "check-coverage": true, "coverage-map": "map.js", "nyc-arg": [ "--exclude", "tap-snapshots/**" ] }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "windowsCI": false, "version": "4.22.0", "publish": true }, "version": "4.0.4" } PK ~\Uvvbin-links/lib/is-windows.jsnu[const platform = process.env.__TESTING_BIN_LINKS_PLATFORM__ || process.platform module.exports = platform === 'win32' PK ~\w*!bin-links/lib/get-node-modules.jsnu[// we know it's global and/or not top, so the path has to be // {prefix}/node_modules/{name}. Can't rely on pkg.name, because // it might be installed as an alias. const { dirname, basename } = require('path') // this gets called a lot and can't change, so memoize it const memo = new Map() module.exports = path => { if (memo.has(path)) { return memo.get(path) } const scopeOrNm = dirname(path) const nm = basename(scopeOrNm) === 'node_modules' ? scopeOrNm : dirname(scopeOrNm) memo.set(path, nm) return nm } PK ~\?bin-links/lib/get-prefix.jsnu[const { dirname } = require('path') const getNodeModules = require('./get-node-modules.js') module.exports = path => dirname(getNodeModules(path)) PK ~\Obin-links/lib/man-target.jsnu[const isWindows = require('./is-windows.js') const getPrefix = require('./get-prefix.js') const { dirname } = require('path') module.exports = ({ top, path }) => !top || isWindows ? null : dirname(getPrefix(path)) + '/share/man' PK ~\6܈bin-links/lib/fix-bin.jsnu[// make sure that bins are executable, and that they don't have // windows line-endings on the hashbang line. const { chmod, open, readFile, } = require('fs/promises') const execMode = 0o777 & (~process.umask()) const writeFileAtomic = require('write-file-atomic') const isWindowsHashBang = buf => buf[0] === '#'.charCodeAt(0) && buf[1] === '!'.charCodeAt(0) && /^#![^\n]+\r\n/.test(buf.toString()) const isWindowsHashbangFile = file => { const FALSE = () => false return open(file, 'r').then(fh => { const buf = Buffer.alloc(2048) return fh.read(buf, 0, 2048, 0) .then( () => { const isWHB = isWindowsHashBang(buf) return fh.close().then(() => isWHB, () => isWHB) }, // don't leak FD if read() fails () => fh.close().then(FALSE, FALSE) ) }, FALSE) } const dos2Unix = file => readFile(file, 'utf8').then(content => writeFileAtomic(file, content.replace(/^(#![^\n]+)\r\n/, '$1\n'))) const fixBin = (file, mode = execMode) => chmod(file, mode) .then(() => isWindowsHashbangFile(file)) .then(isWHB => isWHB ? dos2Unix(file) : null) module.exports = fixBin PK ~\9*IIbin-links/lib/bin-target.jsnu[const isWindows = require('./is-windows.js') const getPrefix = require('./get-prefix.js') const getNodeModules = require('./get-node-modules.js') const { dirname } = require('path') module.exports = ({ top, path }) => !top ? getNodeModules(path) + '/.bin' : isWindows ? getPrefix(path) : dirname(getPrefix(path)) + '/bin' PK ~\q2 2 bin-links/lib/link-gently.jsnu[// if the thing isn't there, skip it // if there's a non-symlink there already, eexist // if there's a symlink already, pointing somewhere else, eexist // if there's a symlink already, pointing into our pkg, remove it first // then create the symlink const { resolve, dirname } = require('path') const { lstat, mkdir, readlink, rm, symlink } = require('fs/promises') const throwNonEnoent = er => { if (er.code !== 'ENOENT') { throw er } } const rmOpts = { recursive: true, force: true, } // even in --force mode, we never create a link over a link we've // already created. you can have multiple packages in a tree trying // to contend for the same bin, or the same manpage listed multiple times, // which creates a race condition and nondeterminism. const seen = new Set() const SKIP = Symbol('skip - missing or already installed') const CLOBBER = Symbol('clobber - ours or in forceful mode') const linkGently = async ({ path, to, from, absFrom, force }) => { if (seen.has(to)) { return false } seen.add(to) // if the script or manpage isn't there, just ignore it. // this arguably *should* be an install error of some sort, // or at least a warning, but npm has always behaved this // way in the past, so it'd be a breaking change return Promise.all([ lstat(absFrom).catch(throwNonEnoent), lstat(to).catch(throwNonEnoent), ]).then(([stFrom, stTo]) => { // not present in package, skip it if (!stFrom) { return SKIP } // exists! maybe clobber if we can if (stTo) { if (!stTo.isSymbolicLink()) { return force && rm(to, rmOpts).then(() => CLOBBER) } return readlink(to).then(target => { if (target === from) { return SKIP } // skip it, already set up like we want it. target = resolve(dirname(to), target) if (target.indexOf(path) === 0 || force) { return rm(to, rmOpts).then(() => CLOBBER) } // neither skip nor clobber return false }) } else { // doesn't exist, dir might not either return mkdir(dirname(to), { recursive: true }) } }) .then(skipOrClobber => { if (skipOrClobber === SKIP) { return false } return symlink(from, to, 'file').catch(er => { if (skipOrClobber === CLOBBER || force) { return rm(to, rmOpts).then(() => symlink(from, to, 'file')) } throw er }).then(() => true) }) } const resetSeen = () => { for (const p of seen) { seen.delete(p) } } module.exports = Object.assign(linkGently, { resetSeen }) PK ~\URRbin-links/lib/index.jsnu[const linkBins = require('./link-bins.js') const linkMans = require('./link-mans.js') const binLinks = opts => { const { path, pkg, force, global, top } = opts // global top pkgs on windows get bins installed in {prefix}, and no mans // // unix global top pkgs get their bins installed in {prefix}/bin, // and mans in {prefix}/share/man // // non-top pkgs get their bins installed in {prefix}/node_modules/.bin, // and do not install mans // // non-global top pkgs don't have any bins or mans linked. From here on // out, if it's top, we know that it's global, so no need to pass that // option further down the stack. if (top && !global) { return Promise.resolve() } return Promise.all([ // allow clobbering within the local node_modules/.bin folder. // only global bins are protected in this way, or else it is // yet another vector for excessive dependency conflicts. linkBins({ path, pkg, top, force: force || !top }), linkMans({ path, pkg, top, force }), ]) } const shimBin = require('./shim-bin.js') const linkGently = require('./link-gently.js') const resetSeen = () => { shimBin.resetSeen() linkGently.resetSeen() } const checkBins = require('./check-bins.js') const getPaths = require('./get-paths.js') module.exports = Object.assign(binLinks, { checkBins, resetSeen, getPaths, }) PK ~\00bin-links/lib/shim-bin.jsnu[const { resolve, dirname } = require('path') const { lstat } = require('fs/promises') const throwNonEnoent = er => { if (er.code !== 'ENOENT') { throw er } } const cmdShim = require('cmd-shim') const readCmdShim = require('read-cmd-shim') const fixBin = require('./fix-bin.js') // even in --force mode, we never create a shim over a shim we've // already created. you can have multiple packages in a tree trying // to contend for the same bin, which creates a race condition and // nondeterminism. const seen = new Set() const failEEXIST = ({ to, from }) => Promise.reject(Object.assign(new Error('EEXIST: file already exists'), { path: to, dest: from, code: 'EEXIST', })) const handleReadCmdShimError = ({ er, from, to }) => er.code === 'ENOENT' ? null : er.code === 'ENOTASHIM' ? failEEXIST({ from, to }) : Promise.reject(er) const SKIP = Symbol('skip - missing or already installed') const shimBin = ({ path, to, from, absFrom, force }) => { const shims = [ to, to + '.cmd', to + '.ps1', ] for (const shim of shims) { if (seen.has(shim)) { return true } seen.add(shim) } return Promise.all([ ...shims, absFrom, ].map(f => lstat(f).catch(throwNonEnoent))).then((stats) => { const [, , , stFrom] = stats if (!stFrom) { return SKIP } if (force) { return false } return Promise.all(shims.map((s, i) => [s, stats[i]]).map(([s, st]) => { if (!st) { return false } return readCmdShim(s) .then(target => { target = resolve(dirname(to), target) if (target.indexOf(resolve(path)) !== 0) { return failEEXIST({ from, to, path }) } return false }, er => handleReadCmdShimError({ er, from, to })) })) }) .then(skip => skip !== SKIP && doShim(absFrom, to)) } const doShim = (absFrom, to) => cmdShim(absFrom, to).then(() => fixBin(absFrom)) const resetSeen = () => { for (const p of seen) { seen.delete(p) } } module.exports = Object.assign(shimBin, { resetSeen }) PK ~\~,bin-links/lib/get-paths.jsnu[// get all the paths that are (or might be) installed for a given pkg // There's no guarantee that all of these will be installed, but if they // are present, then we can assume that they're associated. const binTarget = require('./bin-target.js') const manTarget = require('./man-target.js') const { resolve, basename, extname } = require('path') const isWindows = require('./is-windows.js') module.exports = ({ path, pkg, global, top }) => { if (top && !global) { return [] } const binSet = [] const binTarg = binTarget({ path, top }) if (pkg.bin) { for (const bin of Object.keys(pkg.bin)) { const b = resolve(binTarg, bin) binSet.push(b) if (isWindows) { binSet.push(b + '.cmd') binSet.push(b + '.ps1') } } } const manTarg = manTarget({ path, top }) const manSet = [] if (manTarg && pkg.man && Array.isArray(pkg.man) && pkg.man.length) { for (const man of pkg.man) { if (!/.\.[0-9]+(\.gz)?$/.test(man)) { return binSet } const section = extname(basename(man, '.gz')).slice(1) const base = basename(man) manSet.push(resolve(manTarg, 'man' + section, base)) } } return manSet.length ? [...binSet, ...manSet] : binSet } PK ~\g*Lbin-links/lib/check-bins.jsnu[const checkBin = require('./check-bin.js') const normalize = require('npm-normalize-package-bin') const checkBins = async ({ pkg, path, top, global, force }) => { // always ok to clobber when forced // always ok to clobber local bins, or when forced if (force || !global || !top) { return } pkg = normalize(pkg) if (!pkg.bin) { return } await Promise.all(Object.keys(pkg.bin) .map(bin => checkBin({ bin, path, top, global, force }))) } module.exports = checkBins PK ~\FWWbin-links/lib/link-bin.jsnu[const linkGently = require('./link-gently.js') const fixBin = require('./fix-bin.js') // linking bins is simple. just symlink, and if we linked it, fix the bin up const linkBin = ({ path, to, from, absFrom, force }) => linkGently({ path, to, from, absFrom, force }) .then(linked => linked && fixBin(absFrom)) module.exports = linkBin PK ~\*2bin-links/lib/link-mans.jsnu[const { dirname, relative, join, resolve, basename } = require('path') const linkGently = require('./link-gently.js') const manTarget = require('./man-target.js') const linkMans = async ({ path, pkg, top, force }) => { const target = manTarget({ path, top }) if (!target || !Array.isArray(pkg?.man) || !pkg.man.length) { return [] } const links = [] // `new Set` to filter out duplicates for (let man of new Set(pkg.man)) { if (!man || typeof man !== 'string') { continue } // break any links to c:\\blah or /foo/blah or ../blah man = join('/', man).replace(/\\|:/g, '/').slice(1) const parseMan = man.match(/\.([0-9]+)(\.gz)?$/) if (!parseMan) { throw Object.assign(new Error('invalid man entry name\n' + 'Man files must end with a number, ' + 'and optionally a .gz suffix if they are compressed.' ), { code: 'EBADMAN', path, pkgid: pkg._id, man, }) } const section = parseMan[1] const base = basename(man) const absFrom = resolve(path, man) /* istanbul ignore if - that unpossible */ if (absFrom.indexOf(path) !== 0) { throw Object.assign(new Error('invalid man entry'), { code: 'EBADMAN', path, pkgid: pkg._id, man, }) } const to = resolve(target, 'man' + section, base) const from = relative(dirname(to), absFrom) links.push(linkGently({ from, to, path, absFrom, force })) } return Promise.all(links) } module.exports = linkMans PK ~\ybin-links/lib/link-bins.jsnu[const isWindows = require('./is-windows.js') const binTarget = require('./bin-target.js') const { dirname, resolve, relative } = require('path') const linkBin = isWindows ? require('./shim-bin.js') : require('./link-bin.js') const normalize = require('npm-normalize-package-bin') const linkBins = ({ path, pkg, top, force }) => { pkg = normalize(pkg) if (!pkg.bin) { return Promise.resolve([]) } const promises = [] const target = binTarget({ path, top }) for (const [key, val] of Object.entries(pkg.bin)) { const to = resolve(target, key) const absFrom = resolve(path, val) const from = relative(dirname(to), absFrom) promises.push(linkBin({ path, from, to, absFrom, force })) } return Promise.all(promises) } module.exports = linkBins PK ~\!2bin-links/lib/check-bin.jsnu[// check to see if a bin is allowed to be overwritten // either rejects or resolves to nothing. return value not relevant. const isWindows = require('./is-windows.js') const binTarget = require('./bin-target.js') const { resolve, dirname } = require('path') const readCmdShim = require('read-cmd-shim') const { readlink } = require('fs/promises') const checkBin = async ({ bin, path, top, global, force }) => { // always ok to clobber when forced // always ok to clobber local bins, or when forced if (force || !global || !top) { return } // ok, need to make sure, then const target = resolve(binTarget({ path, top }), bin) path = resolve(path) return isWindows ? checkShim({ target, path }) : checkLink({ target, path }) } // only enoent is allowed. anything else is a problem. const handleReadLinkError = async ({ er, target }) => er.code === 'ENOENT' ? null : failEEXIST({ target }) const checkLink = async ({ target, path }) => { const current = await readlink(target) .catch(er => handleReadLinkError({ er, target })) if (!current) { return } const resolved = resolve(dirname(target), current) if (resolved.toLowerCase().indexOf(path.toLowerCase()) !== 0) { return failEEXIST({ target }) } } const handleReadCmdShimError = ({ er, target }) => er.code === 'ENOENT' ? null : failEEXIST({ target }) const failEEXIST = ({ target }) => Promise.reject(Object.assign(new Error('EEXIST: file already exists'), { path: target, code: 'EEXIST', })) const checkShim = async ({ target, path }) => { const shims = [ target, target + '.cmd', target + '.ps1', ] await Promise.all(shims.map(async shim => { const current = await readCmdShim(shim) .catch(er => handleReadCmdShimError({ er, target: shim })) if (!current) { return } const resolved = resolve(dirname(shim), current.replace(/\\/g, '/')) if (resolved.toLowerCase().indexOf(path.toLowerCase()) !== 0) { return failEEXIST({ target: shim }) } })) } module.exports = checkBin PK ~\.9bin-links/LICENSEnu[The ISC License Copyright (c) npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\*eLccminipass-pipeline/package.jsonnu[{ "_id": "minipass-pipeline@1.2.4", "_inBundle": true, "_location": "/npm/minipass-pipeline", "_phantomChildren": { "yallist": "4.0.0" }, "_requiredBy": [ "/npm", "/npm/cacache", "/npm/make-fetch-happen" ], "author": { "name": "Isaac Z. Schlueter", "email": "i@izs.me", "url": "https://izs.me" }, "dependencies": { "minipass": "^3.0.0" }, "description": "create a pipeline of streams using Minipass", "devDependencies": { "tap": "^14.6.9" }, "engines": { "node": ">=8" }, "files": [ "index.js" ], "license": "ISC", "name": "minipass-pipeline", "scripts": { "postpublish": "git push origin --follow-tags", "postversion": "npm publish", "preversion": "npm test", "snap": "tap", "test": "tap" }, "tap": { "check-coverage": true }, "version": "1.2.4" } PK ~\\8I4minipass-pipeline/node_modules/minipass/package.jsonnu[{ "_id": "minipass@3.3.6", "_inBundle": true, "_location": "/npm/minipass-pipeline/minipass", "_phantomChildren": {}, "_requiredBy": [ "/npm/minipass-pipeline" ], "author": { "name": "Isaac Z. Schlueter", "email": "i@izs.me", "url": "http://blog.izs.me/" }, "bugs": { "url": "https://github.com/isaacs/minipass/issues" }, "dependencies": { "yallist": "^4.0.0" }, "description": "minimal implementation of a PassThrough stream", "devDependencies": { "@types/node": "^17.0.41", "end-of-stream": "^1.4.0", "prettier": "^2.6.2", "tap": "^16.2.0", "through2": "^2.0.3", "ts-node": "^10.8.1", "typescript": "^4.7.3" }, "engines": { "node": ">=8" }, "files": [ "index.d.ts", "index.js" ], "homepage": "https://github.com/isaacs/minipass#readme", "keywords": [ "passthrough", "stream" ], "license": "ISC", "main": "index.js", "name": "minipass", "prettier": { "semi": false, "printWidth": 80, "tabWidth": 2, "useTabs": false, "singleQuote": true, "jsxSingleQuote": false, "bracketSameLine": true, "arrowParens": "avoid", "endOfLine": "lf" }, "repository": { "type": "git", "url": "git+https://github.com/isaacs/minipass.git" }, "scripts": { "postpublish": "git push origin --follow-tags", "postversion": "npm publish", "preversion": "npm test", "test": "tap" }, "tap": { "check-coverage": true }, "types": "index.d.ts", "version": "3.3.6" } PK ~\/minipass-pipeline/node_modules/minipass/LICENSEnu[The ISC License Copyright (c) 2017-2022 npm, Inc., Isaac Z. Schlueter, and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\-@@0minipass-pipeline/node_modules/minipass/index.jsnu['use strict' const proc = typeof process === 'object' && process ? process : { stdout: null, stderr: null, } const EE = require('events') const Stream = require('stream') const SD = require('string_decoder').StringDecoder const EOF = Symbol('EOF') const MAYBE_EMIT_END = Symbol('maybeEmitEnd') const EMITTED_END = Symbol('emittedEnd') const EMITTING_END = Symbol('emittingEnd') const EMITTED_ERROR = Symbol('emittedError') const CLOSED = Symbol('closed') const READ = Symbol('read') const FLUSH = Symbol('flush') const FLUSHCHUNK = Symbol('flushChunk') const ENCODING = Symbol('encoding') const DECODER = Symbol('decoder') const FLOWING = Symbol('flowing') const PAUSED = Symbol('paused') const RESUME = Symbol('resume') const BUFFERLENGTH = Symbol('bufferLength') const BUFFERPUSH = Symbol('bufferPush') const BUFFERSHIFT = Symbol('bufferShift') const OBJECTMODE = Symbol('objectMode') const DESTROYED = Symbol('destroyed') const EMITDATA = Symbol('emitData') const EMITEND = Symbol('emitEnd') const EMITEND2 = Symbol('emitEnd2') const ASYNC = Symbol('async') const defer = fn => Promise.resolve().then(fn) // TODO remove when Node v8 support drops const doIter = global._MP_NO_ITERATOR_SYMBOLS_ !== '1' const ASYNCITERATOR = doIter && Symbol.asyncIterator || Symbol('asyncIterator not implemented') const ITERATOR = doIter && Symbol.iterator || Symbol('iterator not implemented') // events that mean 'the stream is over' // these are treated specially, and re-emitted // if they are listened for after emitting. const isEndish = ev => ev === 'end' || ev === 'finish' || ev === 'prefinish' const isArrayBuffer = b => b instanceof ArrayBuffer || typeof b === 'object' && b.constructor && b.constructor.name === 'ArrayBuffer' && b.byteLength >= 0 const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b) class Pipe { constructor (src, dest, opts) { this.src = src this.dest = dest this.opts = opts this.ondrain = () => src[RESUME]() dest.on('drain', this.ondrain) } unpipe () { this.dest.removeListener('drain', this.ondrain) } // istanbul ignore next - only here for the prototype proxyErrors () {} end () { this.unpipe() if (this.opts.end) this.dest.end() } } class PipeProxyErrors extends Pipe { unpipe () { this.src.removeListener('error', this.proxyErrors) super.unpipe() } constructor (src, dest, opts) { super(src, dest, opts) this.proxyErrors = er => dest.emit('error', er) src.on('error', this.proxyErrors) } } module.exports = class Minipass extends Stream { constructor (options) { super() this[FLOWING] = false // whether we're explicitly paused this[PAUSED] = false this.pipes = [] this.buffer = [] this[OBJECTMODE] = options && options.objectMode || false if (this[OBJECTMODE]) this[ENCODING] = null else this[ENCODING] = options && options.encoding || null if (this[ENCODING] === 'buffer') this[ENCODING] = null this[ASYNC] = options && !!options.async || false this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null this[EOF] = false this[EMITTED_END] = false this[EMITTING_END] = false this[CLOSED] = false this[EMITTED_ERROR] = null this.writable = true this.readable = true this[BUFFERLENGTH] = 0 this[DESTROYED] = false } get bufferLength () { return this[BUFFERLENGTH] } get encoding () { return this[ENCODING] } set encoding (enc) { if (this[OBJECTMODE]) throw new Error('cannot set encoding in objectMode') if (this[ENCODING] && enc !== this[ENCODING] && (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH])) throw new Error('cannot change encoding') if (this[ENCODING] !== enc) { this[DECODER] = enc ? new SD(enc) : null if (this.buffer.length) this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk)) } this[ENCODING] = enc } setEncoding (enc) { this.encoding = enc } get objectMode () { return this[OBJECTMODE] } set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om } get ['async'] () { return this[ASYNC] } set ['async'] (a) { this[ASYNC] = this[ASYNC] || !!a } write (chunk, encoding, cb) { if (this[EOF]) throw new Error('write after end') if (this[DESTROYED]) { this.emit('error', Object.assign( new Error('Cannot call write after a stream was destroyed'), { code: 'ERR_STREAM_DESTROYED' } )) return true } if (typeof encoding === 'function') cb = encoding, encoding = 'utf8' if (!encoding) encoding = 'utf8' const fn = this[ASYNC] ? defer : f => f() // convert array buffers and typed array views into buffers // at some point in the future, we may want to do the opposite! // leave strings and buffers as-is // anything else switches us into object mode if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { if (isArrayBufferView(chunk)) chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) else if (isArrayBuffer(chunk)) chunk = Buffer.from(chunk) else if (typeof chunk !== 'string') // use the setter so we throw if we have encoding set this.objectMode = true } // handle object mode up front, since it's simpler // this yields better performance, fewer checks later. if (this[OBJECTMODE]) { /* istanbul ignore if - maybe impossible? */ if (this.flowing && this[BUFFERLENGTH] !== 0) this[FLUSH](true) if (this.flowing) this.emit('data', chunk) else this[BUFFERPUSH](chunk) if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } // at this point the chunk is a buffer or string // don't buffer it up or send it to the decoder if (!chunk.length) { if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } // fast-path writing strings of same encoding to a stream with // an empty buffer, skipping the buffer/decoder dance if (typeof chunk === 'string' && // unless it is a string already ready for us to use !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) { chunk = Buffer.from(chunk, encoding) } if (Buffer.isBuffer(chunk) && this[ENCODING]) chunk = this[DECODER].write(chunk) // Note: flushing CAN potentially switch us into not-flowing mode if (this.flowing && this[BUFFERLENGTH] !== 0) this[FLUSH](true) if (this.flowing) this.emit('data', chunk) else this[BUFFERPUSH](chunk) if (this[BUFFERLENGTH] !== 0) this.emit('readable') if (cb) fn(cb) return this.flowing } read (n) { if (this[DESTROYED]) return null if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) { this[MAYBE_EMIT_END]() return null } if (this[OBJECTMODE]) n = null if (this.buffer.length > 1 && !this[OBJECTMODE]) { if (this.encoding) this.buffer = [this.buffer.join('')] else this.buffer = [Buffer.concat(this.buffer, this[BUFFERLENGTH])] } const ret = this[READ](n || null, this.buffer[0]) this[MAYBE_EMIT_END]() return ret } [READ] (n, chunk) { if (n === chunk.length || n === null) this[BUFFERSHIFT]() else { this.buffer[0] = chunk.slice(n) chunk = chunk.slice(0, n) this[BUFFERLENGTH] -= n } this.emit('data', chunk) if (!this.buffer.length && !this[EOF]) this.emit('drain') return chunk } end (chunk, encoding, cb) { if (typeof chunk === 'function') cb = chunk, chunk = null if (typeof encoding === 'function') cb = encoding, encoding = 'utf8' if (chunk) this.write(chunk, encoding) if (cb) this.once('end', cb) this[EOF] = true this.writable = false // if we haven't written anything, then go ahead and emit, // even if we're not reading. // we'll re-emit if a new 'end' listener is added anyway. // This makes MP more suitable to write-only use cases. if (this.flowing || !this[PAUSED]) this[MAYBE_EMIT_END]() return this } // don't let the internal resume be overwritten [RESUME] () { if (this[DESTROYED]) return this[PAUSED] = false this[FLOWING] = true this.emit('resume') if (this.buffer.length) this[FLUSH]() else if (this[EOF]) this[MAYBE_EMIT_END]() else this.emit('drain') } resume () { return this[RESUME]() } pause () { this[FLOWING] = false this[PAUSED] = true } get destroyed () { return this[DESTROYED] } get flowing () { return this[FLOWING] } get paused () { return this[PAUSED] } [BUFFERPUSH] (chunk) { if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1 else this[BUFFERLENGTH] += chunk.length this.buffer.push(chunk) } [BUFFERSHIFT] () { if (this.buffer.length) { if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1 else this[BUFFERLENGTH] -= this.buffer[0].length } return this.buffer.shift() } [FLUSH] (noDrain) { do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]())) if (!noDrain && !this.buffer.length && !this[EOF]) this.emit('drain') } [FLUSHCHUNK] (chunk) { return chunk ? (this.emit('data', chunk), this.flowing) : false } pipe (dest, opts) { if (this[DESTROYED]) return const ended = this[EMITTED_END] opts = opts || {} if (dest === proc.stdout || dest === proc.stderr) opts.end = false else opts.end = opts.end !== false opts.proxyErrors = !!opts.proxyErrors // piping an ended stream ends immediately if (ended) { if (opts.end) dest.end() } else { this.pipes.push(!opts.proxyErrors ? new Pipe(this, dest, opts) : new PipeProxyErrors(this, dest, opts)) if (this[ASYNC]) defer(() => this[RESUME]()) else this[RESUME]() } return dest } unpipe (dest) { const p = this.pipes.find(p => p.dest === dest) if (p) { this.pipes.splice(this.pipes.indexOf(p), 1) p.unpipe() } } addListener (ev, fn) { return this.on(ev, fn) } on (ev, fn) { const ret = super.on(ev, fn) if (ev === 'data' && !this.pipes.length && !this.flowing) this[RESUME]() else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) super.emit('readable') else if (isEndish(ev) && this[EMITTED_END]) { super.emit(ev) this.removeAllListeners(ev) } else if (ev === 'error' && this[EMITTED_ERROR]) { if (this[ASYNC]) defer(() => fn.call(this, this[EMITTED_ERROR])) else fn.call(this, this[EMITTED_ERROR]) } return ret } get emittedEnd () { return this[EMITTED_END] } [MAYBE_EMIT_END] () { if (!this[EMITTING_END] && !this[EMITTED_END] && !this[DESTROYED] && this.buffer.length === 0 && this[EOF]) { this[EMITTING_END] = true this.emit('end') this.emit('prefinish') this.emit('finish') if (this[CLOSED]) this.emit('close') this[EMITTING_END] = false } } emit (ev, data, ...extra) { // error and close are only events allowed after calling destroy() if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED]) return else if (ev === 'data') { return !data ? false : this[ASYNC] ? defer(() => this[EMITDATA](data)) : this[EMITDATA](data) } else if (ev === 'end') { return this[EMITEND]() } else if (ev === 'close') { this[CLOSED] = true // don't emit close before 'end' and 'finish' if (!this[EMITTED_END] && !this[DESTROYED]) return const ret = super.emit('close') this.removeAllListeners('close') return ret } else if (ev === 'error') { this[EMITTED_ERROR] = data const ret = super.emit('error', data) this[MAYBE_EMIT_END]() return ret } else if (ev === 'resume') { const ret = super.emit('resume') this[MAYBE_EMIT_END]() return ret } else if (ev === 'finish' || ev === 'prefinish') { const ret = super.emit(ev) this.removeAllListeners(ev) return ret } // Some other unknown event const ret = super.emit(ev, data, ...extra) this[MAYBE_EMIT_END]() return ret } [EMITDATA] (data) { for (const p of this.pipes) { if (p.dest.write(data) === false) this.pause() } const ret = super.emit('data', data) this[MAYBE_EMIT_END]() return ret } [EMITEND] () { if (this[EMITTED_END]) return this[EMITTED_END] = true this.readable = false if (this[ASYNC]) defer(() => this[EMITEND2]()) else this[EMITEND2]() } [EMITEND2] () { if (this[DECODER]) { const data = this[DECODER].end() if (data) { for (const p of this.pipes) { p.dest.write(data) } super.emit('data', data) } } for (const p of this.pipes) { p.end() } const ret = super.emit('end') this.removeAllListeners('end') return ret } // const all = await stream.collect() collect () { const buf = [] if (!this[OBJECTMODE]) buf.dataLength = 0 // set the promise first, in case an error is raised // by triggering the flow here. const p = this.promise() this.on('data', c => { buf.push(c) if (!this[OBJECTMODE]) buf.dataLength += c.length }) return p.then(() => buf) } // const data = await stream.concat() concat () { return this[OBJECTMODE] ? Promise.reject(new Error('cannot concat in objectMode')) : this.collect().then(buf => this[OBJECTMODE] ? Promise.reject(new Error('cannot concat in objectMode')) : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength)) } // stream.promise().then(() => done, er => emitted error) promise () { return new Promise((resolve, reject) => { this.on(DESTROYED, () => reject(new Error('stream destroyed'))) this.on('error', er => reject(er)) this.on('end', () => resolve()) }) } // for await (let chunk of stream) [ASYNCITERATOR] () { const next = () => { const res = this.read() if (res !== null) return Promise.resolve({ done: false, value: res }) if (this[EOF]) return Promise.resolve({ done: true }) let resolve = null let reject = null const onerr = er => { this.removeListener('data', ondata) this.removeListener('end', onend) reject(er) } const ondata = value => { this.removeListener('error', onerr) this.removeListener('end', onend) this.pause() resolve({ value: value, done: !!this[EOF] }) } const onend = () => { this.removeListener('error', onerr) this.removeListener('data', ondata) resolve({ done: true }) } const ondestroy = () => onerr(new Error('stream destroyed')) return new Promise((res, rej) => { reject = rej resolve = res this.once(DESTROYED, ondestroy) this.once('error', onerr) this.once('end', onend) this.once('data', ondata) }) } return { next } } // for (let chunk of stream) [ITERATOR] () { const next = () => { const value = this.read() const done = value === null return { value, done } } return { next } } destroy (er) { if (this[DESTROYED]) { if (er) this.emit('error', er) else this.emit(DESTROYED) return this } this[DESTROYED] = true // throw away all buffered data, it's never coming out this.buffer.length = 0 this[BUFFERLENGTH] = 0 if (typeof this.close === 'function' && !this[CLOSED]) this.close() if (er) this.emit('error', er) else // if no error to emit, still reject pending promises this.emit(DESTROYED) return this } static isStream (s) { return !!s && (s instanceof Minipass || s instanceof Stream || s instanceof EE && ( typeof s.pipe === 'function' || // readable (typeof s.write === 'function' && typeof s.end === 'function') // writable )) } } PK ~\aGWminipass-pipeline/LICENSEnu[The ISC License Copyright (c) Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\Ә(T T minipass-pipeline/index.jsnu[const Minipass = require('minipass') const EE = require('events') const isStream = s => s && s instanceof EE && ( typeof s.pipe === 'function' || // readable (typeof s.write === 'function' && typeof s.end === 'function') // writable ) const _head = Symbol('_head') const _tail = Symbol('_tail') const _linkStreams = Symbol('_linkStreams') const _setHead = Symbol('_setHead') const _setTail = Symbol('_setTail') const _onError = Symbol('_onError') const _onData = Symbol('_onData') const _onEnd = Symbol('_onEnd') const _onDrain = Symbol('_onDrain') const _streams = Symbol('_streams') class Pipeline extends Minipass { constructor (opts, ...streams) { if (isStream(opts)) { streams.unshift(opts) opts = {} } super(opts) this[_streams] = [] if (streams.length) this.push(...streams) } [_linkStreams] (streams) { // reduce takes (left,right), and we return right to make it the // new left value. return streams.reduce((src, dest) => { src.on('error', er => dest.emit('error', er)) src.pipe(dest) return dest }) } push (...streams) { this[_streams].push(...streams) if (this[_tail]) streams.unshift(this[_tail]) const linkRet = this[_linkStreams](streams) this[_setTail](linkRet) if (!this[_head]) this[_setHead](streams[0]) } unshift (...streams) { this[_streams].unshift(...streams) if (this[_head]) streams.push(this[_head]) const linkRet = this[_linkStreams](streams) this[_setHead](streams[0]) if (!this[_tail]) this[_setTail](linkRet) } destroy (er) { // set fire to the whole thing. this[_streams].forEach(s => typeof s.destroy === 'function' && s.destroy()) return super.destroy(er) } // readable interface -> tail [_setTail] (stream) { this[_tail] = stream stream.on('error', er => this[_onError](stream, er)) stream.on('data', chunk => this[_onData](stream, chunk)) stream.on('end', () => this[_onEnd](stream)) stream.on('finish', () => this[_onEnd](stream)) } // errors proxied down the pipeline // they're considered part of the "read" interface [_onError] (stream, er) { if (stream === this[_tail]) this.emit('error', er) } [_onData] (stream, chunk) { if (stream === this[_tail]) super.write(chunk) } [_onEnd] (stream) { if (stream === this[_tail]) super.end() } pause () { super.pause() return this[_tail] && this[_tail].pause && this[_tail].pause() } // NB: Minipass calls its internal private [RESUME] method during // pipe drains, to avoid hazards where stream.resume() is overridden. // Thus, we need to listen to the resume *event*, not override the // resume() method, and proxy *that* to the tail. emit (ev, ...args) { if (ev === 'resume' && this[_tail] && this[_tail].resume) this[_tail].resume() return super.emit(ev, ...args) } // writable interface -> head [_setHead] (stream) { this[_head] = stream stream.on('drain', () => this[_onDrain](stream)) } [_onDrain] (stream) { if (stream === this[_head]) this.emit('drain') } write (chunk, enc, cb) { return this[_head].write(chunk, enc, cb) && (this.flowing || this.buffer.length === 0) } end (chunk, enc, cb) { this[_head].end(chunk, enc, cb) return this } } module.exports = Pipeline PK ~\( minimatch/package.jsonnu[{ "_id": "minimatch@9.0.4", "_inBundle": true, "_location": "/npm/minimatch", "_phantomChildren": {}, "_requiredBy": [ "/npm", "/npm/@npmcli/arborist", "/npm/@npmcli/map-workspaces", "/npm/@tufjs/models", "/npm/glob", "/npm/ignore-walk", "/npm/libnpmdiff" ], "author": { "name": "Isaac Z. Schlueter", "email": "i@izs.me", "url": "http://blog.izs.me" }, "bugs": { "url": "https://github.com/isaacs/minimatch/issues" }, "dependencies": { "brace-expansion": "^2.0.1" }, "description": "a glob matcher in javascript", "devDependencies": { "@types/brace-expansion": "^1.1.0", "@types/node": "^18.15.11", "@types/tap": "^15.0.8", "eslint-config-prettier": "^8.6.0", "mkdirp": "1", "prettier": "^2.8.2", "tap": "^18.7.2", "ts-node": "^10.9.1", "tshy": "^1.12.0", "typedoc": "^0.23.21", "typescript": "^4.9.3" }, "engines": { "node": ">=16 || 14 >=14.17" }, "exports": { "./package.json": "./package.json", ".": { "import": { "types": "./dist/esm/index.d.ts", "default": "./dist/esm/index.js" }, "require": { "types": "./dist/commonjs/index.d.ts", "default": "./dist/commonjs/index.js" } } }, "files": [ "dist" ], "funding": { "url": "https://github.com/sponsors/isaacs" }, "homepage": "https://github.com/isaacs/minimatch#readme", "license": "ISC", "main": "./dist/commonjs/index.js", "name": "minimatch", "prettier": { "semi": false, "printWidth": 80, "tabWidth": 2, "useTabs": false, "singleQuote": true, "jsxSingleQuote": false, "bracketSameLine": true, "arrowParens": "avoid", "endOfLine": "lf" }, "repository": { "type": "git", "url": "git://github.com/isaacs/minimatch.git" }, "scripts": { "benchmark": "node benchmark/index.js", "format": "prettier --write . --loglevel warn", "postversion": "npm publish", "prepare": "tshy", "prepublishOnly": "git push origin --follow-tags", "presnap": "npm run prepare", "pretest": "npm run prepare", "preversion": "npm test", "snap": "tap", "test": "tap", "typedoc": "typedoc --tsconfig tsconfig-esm.json ./src/*.ts" }, "tshy": { "exports": { "./package.json": "./package.json", ".": "./src/index.ts" } }, "type": "module", "types": "./dist/commonjs/index.d.ts", "version": "9.0.4" } PK ~\dPminimatch/LICENSEnu[The ISC License Copyright (c) 2011-2023 Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. PK ~\zc!minimatch/dist/commonjs/escape.jsnu["use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.escape = void 0; /** * Escape all magic characters in a glob pattern. * * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape} * option is used, then characters are escaped by wrapping in `[]`, because * a magic character wrapped in a character class can only be satisfied by * that exact character. In this mode, `\` is _not_ escaped, because it is * not interpreted as a magic character, but instead as a path separator. */ const escape = (s, { windowsPathsNoEscape = false, } = {}) => { // don't need to escape +@! because we escape the parens // that make those magic, and escaping ! as [!] isn't valid, // because [!]] is a valid glob class meaning not ']'. return windowsPathsNoEscape ? s.replace(/[?*()[\]]/g, '[$&]') : s.replace(/[?*()[\]\\]/g, '\\$&'); }; exports.escape = escape; //# sourceMappingURL=escape.js.mapPK ~\T/minimatch/dist/commonjs/assert-valid-pattern.jsnu["use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.assertValidPattern = void 0; const MAX_PATTERN_LENGTH = 1024 * 64; const assertValidPattern = (pattern) => { if (typeof pattern !== 'string') { throw new TypeError('invalid pattern'); } if (pattern.length > MAX_PATTERN_LENGTH) { throw new TypeError('pattern is too long'); } }; exports.assertValidPattern = assertValidPattern; //# sourceMappingURL=assert-valid-pattern.js.mapPK ~\>$minimatch/dist/commonjs/package.jsonnu[{ "type": "commonjs" } PK ~\{R,minimatch/dist/commonjs/brace-expressions.jsnu["use strict"; // translate the various posix character classes into unicode properties // this works across all unicode locales Object.defineProperty(exports, "__esModule", { value: true }); exports.parseClass = void 0; // { : [, /u flag required, negated] const posixClasses = { '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true], '[:alpha:]': ['\\p{L}\\p{Nl}', true], '[:ascii:]': ['\\x' + '00-\\x' + '7f', false], '[:blank:]': ['\\p{Zs}\\t', true], '[:cntrl:]': ['\\p{Cc}', true], '[:digit:]': ['\\p{Nd}', true], '[:graph:]': ['\\p{Z}\\p{C}', true, true], '[:lower:]': ['\\p{Ll}', true], '[:print:]': ['\\p{C}', true], '[:punct:]': ['\\p{P}', true], '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true], '[:upper:]': ['\\p{Lu}', true], '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true], '[:xdigit:]': ['A-Fa-f0-9', false], }; // only need to escape a few things inside of brace expressions // escapes: [ \ ] - const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&'); // escape all regexp magic characters const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); // everything has already been escaped, we just have to join const rangesToString = (ranges) => ranges.join(''); // takes a glob string at a posix brace expression, and returns // an equivalent regular expression source, and boolean indicating // whether the /u flag needs to be applied, and the number of chars // consumed to parse the character class. // This also removes out of order ranges, and returns ($.) if the // entire class just no good. const parseClass = (glob, position) => { const pos = position; /* c8 ignore start */ if (glob.charAt(pos) !== '[') { throw new Error('not in a brace expression'); } /* c8 ignore stop */ const ranges = []; const negs = []; let i = pos + 1; let sawStart = false; let uflag = false; let escaping = false; let negate = false; let endPos = pos; let rangeStart = ''; WHILE: while (i < glob.length) { const c = glob.charAt(i); if ((c === '!' || c === '^') && i === pos + 1) { negate = true; i++; continue; } if (c === ']' && sawStart && !escaping) { endPos = i + 1; break; } sawStart = true; if (c === '\\') { if (!escaping) { escaping = true; i++; continue; } // escaped \ char, fall through and treat like normal char } if (c === '[' && !escaping) { // either a posix class, a collation equivalent, or just a [ for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) { if (glob.startsWith(cls, i)) { // invalid, [a-[] is fine, but not [a-[:alpha]] if (rangeStart) { return ['$.', false, glob.length - pos, true]; } i += cls.length; if (neg) negs.push(unip); else ranges.push(unip); uflag = uflag || u; continue WHILE; } } } // now it's just a normal character, effectively escaping = false; if (rangeStart) { // throw this range away if it's not valid, but others // can still match. if (c > rangeStart) { ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c)); } else if (c === rangeStart) { ranges.push(braceEscape(c)); } rangeStart = ''; i++; continue; } // now might be the start of a range. // can be either c-d or c-] or c] or c] at this point if (glob.startsWith('-]', i + 1)) { ranges.push(braceEscape(c + '-')); i += 2; continue; } if (glob.startsWith('-', i + 1)) { rangeStart = c; i += 2; continue; } // not the start of a range, just a single character ranges.push(braceEscape(c)); i++; } if (endPos < i) { // didn't see the end of the class, not a valid class, // but might still be valid as a literal match. return ['', false, 0, false]; } // if we got no ranges and no negates, then we have a range that // cannot possibly match anything, and that poisons the whole glob if (!ranges.length && !negs.length) { return ['$.', false, glob.length - pos, true]; } // if we got one positive range, and it's a single character, then that's // not actually a magic pattern, it's just that one literal character. // we should not treat that as "magic", we should just return the literal // character. [_] is a perfectly valid way to escape glob magic chars. if (negs.length === 0 && ranges.length === 1 && /^\\?.$/.test(ranges[0]) && !negate) { const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0]; return [regexpEscape(r), false, endPos - pos, false]; } const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']'; const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']'; const comb = ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')' : ranges.length ? sranges : snegs; return [comb, uflag, endPos - pos, true]; }; exports.parseClass = parseClass; //# sourceMappingURL=brace-expressions.js.mapPK ~\JT#minimatch/dist/commonjs/unescape.jsnu["use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.unescape = void 0; /** * Un-escape a string that has been escaped with {@link escape}. * * If the {@link windowsPathsNoEscape} option is used, then square-brace * escapes are removed, but not backslash escapes. For example, it will turn * the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`, * becuase `\` is a path separator in `windowsPathsNoEscape` mode. * * When `windowsPathsNoEscape` is not set, then both brace escapes and * backslash escapes are removed. * * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped * or unescaped. */ const unescape = (s, { windowsPathsNoEscape = false, } = {}) => { return windowsPathsNoEscape ? s.replace(/\[([^\/\\])\]/g, '$1') : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2').replace(/\\([^\/])/g, '$1'); }; exports.unescape = unescape; //# sourceMappingURL=unescape.js.mapPK ~\MUU minimatch/dist/commonjs/index.jsnu["use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.unescape = exports.escape = exports.AST = exports.Minimatch = exports.match = exports.makeRe = exports.braceExpand = exports.defaults = exports.filter = exports.GLOBSTAR = exports.sep = exports.minimatch = void 0; const brace_expansion_1 = __importDefault(require("brace-expansion")); const assert_valid_pattern_js_1 = require("./assert-valid-pattern.js"); const ast_js_1 = require("./ast.js"); const escape_js_1 = require("./escape.js"); const unescape_js_1 = require("./unescape.js"); const minimatch = (p, pattern, options = {}) => { (0, assert_valid_pattern_js_1.assertValidPattern)(pattern); // shortcut: comments match nothing. if (!options.nocomment && pattern.charAt(0) === '#') { return false; } return new Minimatch(pattern, options).match(p); }; exports.minimatch = minimatch; // Optimized checking for the most common glob patterns. const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/; const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext); const starDotExtTestDot = (ext) => (f) => f.endsWith(ext); const starDotExtTestNocase = (ext) => { ext = ext.toLowerCase(); return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext); }; const starDotExtTestNocaseDot = (ext) => { ext = ext.toLowerCase(); return (f) => f.toLowerCase().endsWith(ext); }; const starDotStarRE = /^\*+\.\*+$/; const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.'); const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.'); const dotStarRE = /^\.\*+$/; const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.'); const starRE = /^\*+$/; const starTest = (f) => f.length !== 0 && !f.startsWith('.'); const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..'; const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/; const qmarksTestNocase = ([$0, ext = '']) => { const noext = qmarksTestNoExt([$0]); if (!ext) return noext; ext = ext.toLowerCase(); return (f) => noext(f) && f.toLowerCase().endsWith(ext); }; const qmarksTestNocaseDot = ([$0, ext = '']) => { const noext = qmarksTestNoExtDot([$0]); if (!ext) return noext; ext = ext.toLowerCase(); return (f) => noext(f) && f.toLowerCase().endsWith(ext); }; const qmarksTestDot = ([$0, ext = '']) => { const noext = qmarksTestNoExtDot([$0]); return !ext ? noext : (f) => noext(f) && f.endsWith(ext); }; const qmarksTest = ([$0, ext = '']) => { const noext = qmarksTestNoExt([$0]); return !ext ? noext : (f) => noext(f) && f.endsWith(ext); }; const qmarksTestNoExt = ([$0]) => { const len = $0.length; return (f) => f.length === len && !f.startsWith('.'); }; const qmarksTestNoExtDot = ([$0]) => { const len = $0.length; return (f) => f.length === len && f !== '.' && f !== '..'; }; /* c8 ignore start */ const defaultPlatform = (typeof process === 'object' && process ? (typeof process.env === 'object' && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__) || process.platform : 'posix'); const path = { win32: { sep: '\\' }, posix: { sep: '/' }, }; /* c8 ignore stop */ exports.sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep; exports.minimatch.sep = exports.sep; exports.GLOBSTAR = Symbol('globstar **'); exports.minimatch.GLOBSTAR = exports.GLOBSTAR; // any single thing other than / // don't need to escape / when using new RegExp() const qmark = '[^/]'; // * => any number of characters const star = qmark + '*?'; // ** when dots are allowed. Anything goes, except .. and . // not (^ or / followed by one or two dots followed by $ or /), // followed by anything, any number of times. const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?'; // not a ^ or / followed by a dot, // followed by anything, any number of times. const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?'; const filter = (pattern, options = {}) => (p) => (0, exports.minimatch)(p, pattern, options); exports.filter = filter; exports.minimatch.filter = exports.filter; const ext = (a, b = {}) => Object.assign({}, a, b); const defaults = (def) => { if (!def || typeof def !== 'object' || !Object.keys(def).length) { return exports.minimatch; } const orig = exports.minimatch; const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options)); return Object.assign(m, { Minimatch: class Minimatch extends orig.Minimatch { constructor(pattern, options = {}) { super(pattern, ext(def, options)); } static defaults(options) { return orig.defaults(ext(def, options)).Minimatch; } }, AST: class AST extends orig.AST { /* c8 ignore start */ constructor(type, parent, options = {}) { super(type, parent, ext(def, options)); } /* c8 ignore stop */ static fromGlob(pattern, options = {}) { return orig.AST.fromGlob(pattern, ext(def, options)); } }, unescape: (s, options = {}) => orig.unescape(s, ext(def, options)), escape: (s, options = {}) => orig.escape(s, ext(def, options)), filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)), defaults: (options) => orig.defaults(ext(def, options)), makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)), braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)), match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)), sep: orig.sep, GLOBSTAR: exports.GLOBSTAR, }); }; exports.defaults = defaults; exports.minimatch.defaults = exports.defaults; // Brace expansion: // a{b,c}d -> abd acd // a{b,}c -> abc ac // a{0..3}d -> a0d a1d a2d a3d // a{b,c{d,e}f}g -> abg acdfg acefg // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg // // Invalid sets are not expanded. // a{2..}b -> a{2..}b // a{b}c -> a{b}c const braceExpand = (pattern, options = {}) => { (0, assert_valid_pattern_js_1.assertValidPattern)(pattern); // Thanks to Yeting Li for // improving this regexp to avoid a ReDOS vulnerability. if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { // shortcut. no need to expand. return [pattern]; } return (0, brace_expansion_1.default)(pattern); }; exports.braceExpand = braceExpand; exports.minimatch.braceExpand = exports.braceExpand; // parse a component of the expanded set. // At this point, no pattern may contain "/" in it // so we're going to return a 2d array, where each entry is the full // pattern, split on '/', and then turned into a regular expression. // A regexp is made at the end which joins each array with an // escaped /, and another full one which joins each regexp with |. // // Following the lead of Bash 4.1, note that "**" only has special meaning // when it is the *only* thing in a path portion. Otherwise, any series // of * is equivalent to a single *. Globstar behavior is enabled by // default, and can be disabled by setting options.noglobstar. const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe(); exports.makeRe = makeRe; exports.minimatch.makeRe = exports.makeRe; const match = (list, pattern, options = {}) => { const mm = new Minimatch(pattern, options); list = list.filter(f => mm.match(f)); if (mm.options.nonull && !list.length) { list.push(pattern); } return list; }; exports.match = match; exports.minimatch.match = exports.match; // replace stuff like \* with * const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/; const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); class Minimatch { options; set; pattern; windowsPathsNoEscape; nonegate; negate; comment; empty; preserveMultipleSlashes; partial; globSet; globParts; nocase; isWindows; platform; windowsNoMagicRoot; regexp; constructor(pattern, options = {}) { (0, assert_valid_pattern_js_1.assertValidPattern)(pattern); options = options || {}; this.options = options; this.pattern = pattern; this.platform = options.platform || defaultPlatform; this.isWindows = this.platform === 'win32'; this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false; if (this.windowsPathsNoEscape) { this.pattern = this.pattern.replace(/\\/g, '/'); } this.preserveMultipleSlashes = !!options.preserveMultipleSlashes; this.regexp = null; this.negate = false; this.nonegate = !!options.nonegate; this.comment = false; this.empty = false; this.partial = !!options.partial; this.nocase = !!this.options.nocase; this.windowsNoMagicRoot = options.windowsNoMagicRoot !== undefined ? options.windowsNoMagicRoot : !!(this.isWindows && this.nocase); this.globSet = []; this.globParts = []; this.set = []; // make the set of regexps etc. this.make(); } hasMagic() { if (this.options.magicalBraces && this.set.length > 1) { return true; } for (const pattern of this.set) { for (const part of pattern) { if (typeof part !== 'string') return true; } } return false; } debug(..._) { } make() { const pattern = this.pattern; const options = this.options; // empty patterns and comments match nothing. if (!options.nocomment && pattern.charAt(0) === '#') { this.comment = true; return; } if (!pattern) { this.empty = true; return; } // step 1: figure out negation, etc. this.parseNegate(); // step 2: expand braces this.globSet = [...new Set(this.braceExpand())]; if (options.debug) { this.debug = (...args) => console.error(...args); } this.debug(this.pattern, this.globSet); // step 3: now we have a set, so turn each one into a series of // path-portion matching patterns. // These will be regexps, except in the case of "**", which is // set to the GLOBSTAR object for globstar behavior, // and will not contain any / characters // // First, we preprocess to make the glob pattern sets a bit simpler // and deduped. There are some perf-killing patterns that can cause // problems with a glob walk, but we can simplify them down a bit. const rawGlobParts = this.globSet.map(s => this.slashSplit(s)); this.globParts = this.preprocess(rawGlobParts); this.debug(this.pattern, this.globParts); // glob --> regexps let set = this.globParts.map((s, _, __) => { if (this.isWindows && this.windowsNoMagicRoot) { // check if it's a drive or unc path. const isUNC = s[0] === '' && s[1] === '' && (s[2] === '?' || !globMagic.test(s[2])) && !globMagic.test(s[3]); const isDrive = /^[a-z]:/i.test(s[0]); if (isUNC) { return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))]; } else if (isDrive) { return [s[0], ...s.slice(1).map(ss => this.parse(ss))]; } } return s.map(ss => this.parse(ss)); }); this.debug(this.pattern, set); // filter out everything that didn't compile properly. this.set = set.filter(s => s.indexOf(false) === -1); // do not treat the ? in UNC paths as magic if (this.isWindows) { for (let i = 0; i < this.set.length; i++) { const p = this.set[i]; if (p[0] === '' && p[1] === '' && this.globParts[i][2] === '?' && typeof p[3] === 'string' && /^[a-z]:$/i.test(p[3])) { p[2] = '?'; } } } this.debug(this.pattern, this.set); } // various transforms to equivalent pattern sets that are // faster to process in a filesystem walk. The goal is to // eliminate what we can, and push all ** patterns as far // to the right as possible, even if it increases the number // of patterns that we have to process. preprocess(globParts) { // if we're not in globstar mode, then turn all ** into * if (this.options.noglobstar) { for (let i = 0; i < globParts.length; i++) { for (let j = 0; j < globParts[i].length; j++) { if (globParts[i][j] === '**') { globParts[i][j] = '*'; } } } } const { optimizationLevel = 1 } = this.options; if (optimizationLevel >= 2) { // aggressive optimization for the purpose of fs walking globParts = this.firstPhasePreProcess(globParts); globParts = this.secondPhasePreProcess(globParts); } else if (optimizationLevel >= 1) { // just basic optimizations to remove some .. parts globParts = this.levelOneOptimize(globParts); } else { // just collapse multiple ** portions into one globParts = this.adjascentGlobstarOptimize(globParts); } return globParts; } // just get rid of adjascent ** portions adjascentGlobstarOptimize(globParts) { return globParts.map(parts => { let gs = -1; while (-1 !== (gs = parts.indexOf('**', gs + 1))) { let i = gs; while (parts[i + 1] === '**') { i++; } if (i !== gs) { parts.splice(gs, i - gs); } } return parts; }); } // get rid of adjascent ** and resolve .. portions levelOneOptimize(globParts) { return globParts.map(parts => { parts = parts.reduce((set, part) => { const prev = set[set.length - 1]; if (part === '**' && prev === '**') { return set; } if (part === '..') { if (prev && prev !== '..' && prev !== '.' && prev !== '**') { set.pop(); return set; } } set.push(part); return set; }, []); return parts.length === 0 ? [''] : parts; }); } levelTwoFileOptimize(parts) { if (!Array.isArray(parts)) { parts = this.slashSplit(parts); } let didSomething = false; do { didSomething = false; //
// -> 
/
            if (!this.preserveMultipleSlashes) {
                for (let i = 1; i < parts.length - 1; i++) {
                    const p = parts[i];
                    // don't squeeze out UNC patterns
                    if (i === 1 && p === '' && parts[0] === '')
                        continue;
                    if (p === '.' || p === '') {
                        didSomething = true;
                        parts.splice(i, 1);
                        i--;
                    }
                }
                if (parts[0] === '.' &&
                    parts.length === 2 &&
                    (parts[1] === '.' || parts[1] === '')) {
                    didSomething = true;
                    parts.pop();
                }
            }
            // 
/

/../ ->

/
            let dd = 0;
            while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
                const p = parts[dd - 1];
                if (p && p !== '.' && p !== '..' && p !== '**') {
                    didSomething = true;
                    parts.splice(dd - 1, 2);
                    dd -= 2;
                }
            }
        } while (didSomething);
        return parts.length === 0 ? [''] : parts;
    }
    // First phase: single-pattern processing
    // 
 is 1 or more portions
    //  is 1 or more portions
    // 

is any portion other than ., .., '', or ** // is . or '' // // **/.. is *brutal* for filesystem walking performance, because // it effectively resets the recursive walk each time it occurs, // and ** cannot be reduced out by a .. pattern part like a regexp // or most strings (other than .., ., and '') can be. // //

/**/../

/

/ -> {

/../

/

/,

/**/

/

/} //

// -> 
/
    // 
/

/../ ->

/
    // **/**/ -> **/
    //
    // **/*/ -> */**/ <== not valid because ** doesn't follow
    // this WOULD be allowed if ** did follow symlinks, or * didn't
    firstPhasePreProcess(globParts) {
        let didSomething = false;
        do {
            didSomething = false;
            // 
/**/../

/

/ -> {

/../

/

/,

/**/

/

/} for (let parts of globParts) { let gs = -1; while (-1 !== (gs = parts.indexOf('**', gs + 1))) { let gss = gs; while (parts[gss + 1] === '**') { //

/**/**/ -> 
/**/
                        gss++;
                    }
                    // eg, if gs is 2 and gss is 4, that means we have 3 **
                    // parts, and can remove 2 of them.
                    if (gss > gs) {
                        parts.splice(gs + 1, gss - gs);
                    }
                    let next = parts[gs + 1];
                    const p = parts[gs + 2];
                    const p2 = parts[gs + 3];
                    if (next !== '..')
                        continue;
                    if (!p ||
                        p === '.' ||
                        p === '..' ||
                        !p2 ||
                        p2 === '.' ||
                        p2 === '..') {
                        continue;
                    }
                    didSomething = true;
                    // edit parts in place, and push the new one
                    parts.splice(gs, 1);
                    const other = parts.slice(0);
                    other[gs] = '**';
                    globParts.push(other);
                    gs--;
                }
                // 
// -> 
/
                if (!this.preserveMultipleSlashes) {
                    for (let i = 1; i < parts.length - 1; i++) {
                        const p = parts[i];
                        // don't squeeze out UNC patterns
                        if (i === 1 && p === '' && parts[0] === '')
                            continue;
                        if (p === '.' || p === '') {
                            didSomething = true;
                            parts.splice(i, 1);
                            i--;
                        }
                    }
                    if (parts[0] === '.' &&
                        parts.length === 2 &&
                        (parts[1] === '.' || parts[1] === '')) {
                        didSomething = true;
                        parts.pop();
                    }
                }
                // 
/

/../ ->

/
                let dd = 0;
                while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
                    const p = parts[dd - 1];
                    if (p && p !== '.' && p !== '..' && p !== '**') {
                        didSomething = true;
                        const needDot = dd === 1 && parts[dd + 1] === '**';
                        const splin = needDot ? ['.'] : [];
                        parts.splice(dd - 1, 2, ...splin);
                        if (parts.length === 0)
                            parts.push('');
                        dd -= 2;
                    }
                }
            }
        } while (didSomething);
        return globParts;
    }
    // second phase: multi-pattern dedupes
    // {
/*/,
/

/} ->

/*/
    // {
/,
/} -> 
/
    // {
/**/,
/} -> 
/**/
    //
    // {
/**/,
/**/

/} ->

/**/
    // ^-- not valid because ** doens't follow symlinks
    secondPhasePreProcess(globParts) {
        for (let i = 0; i < globParts.length - 1; i++) {
            for (let j = i + 1; j < globParts.length; j++) {
                const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
                if (!matched)
                    continue;
                globParts[i] = matched;
                globParts[j] = [];
            }
        }
        return globParts.filter(gs => gs.length);
    }
    partsMatch(a, b, emptyGSMatch = false) {
        let ai = 0;
        let bi = 0;
        let result = [];
        let which = '';
        while (ai < a.length && bi < b.length) {
            if (a[ai] === b[bi]) {
                result.push(which === 'b' ? b[bi] : a[ai]);
                ai++;
                bi++;
            }
            else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
                result.push(a[ai]);
                ai++;
            }
            else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
                result.push(b[bi]);
                bi++;
            }
            else if (a[ai] === '*' &&
                b[bi] &&
                (this.options.dot || !b[bi].startsWith('.')) &&
                b[bi] !== '**') {
                if (which === 'b')
                    return false;
                which = 'a';
                result.push(a[ai]);
                ai++;
                bi++;
            }
            else if (b[bi] === '*' &&
                a[ai] &&
                (this.options.dot || !a[ai].startsWith('.')) &&
                a[ai] !== '**') {
                if (which === 'a')
                    return false;
                which = 'b';
                result.push(b[bi]);
                ai++;
                bi++;
            }
            else {
                return false;
            }
        }
        // if we fall out of the loop, it means they two are identical
        // as long as their lengths match
        return a.length === b.length && result;
    }
    parseNegate() {
        if (this.nonegate)
            return;
        const pattern = this.pattern;
        let negate = false;
        let negateOffset = 0;
        for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
            negate = !negate;
            negateOffset++;
        }
        if (negateOffset)
            this.pattern = pattern.slice(negateOffset);
        this.negate = negate;
    }
    // set partial to true to test if, for example,
    // "/a/b" matches the start of "/*/b/*/d"
    // Partial means, if you run out of file before you run
    // out of pattern, then that's fine, as long as all
    // the parts match.
    matchOne(file, pattern, partial = false) {
        const options = this.options;
        // UNC paths like //?/X:/... can match X:/... and vice versa
        // Drive letters in absolute drive or unc paths are always compared
        // case-insensitively.
        if (this.isWindows) {
            const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
            const fileUNC = !fileDrive &&
                file[0] === '' &&
                file[1] === '' &&
                file[2] === '?' &&
                /^[a-z]:$/i.test(file[3]);
            const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
            const patternUNC = !patternDrive &&
                pattern[0] === '' &&
                pattern[1] === '' &&
                pattern[2] === '?' &&
                typeof pattern[3] === 'string' &&
                /^[a-z]:$/i.test(pattern[3]);
            const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined;
            const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined;
            if (typeof fdi === 'number' && typeof pdi === 'number') {
                const [fd, pd] = [file[fdi], pattern[pdi]];
                if (fd.toLowerCase() === pd.toLowerCase()) {
                    pattern[pdi] = fd;
                    if (pdi > fdi) {
                        pattern = pattern.slice(pdi);
                    }
                    else if (fdi > pdi) {
                        file = file.slice(fdi);
                    }
                }
            }
        }
        // resolve and reduce . and .. portions in the file as well.
        // dont' need to do the second phase, because it's only one string[]
        const { optimizationLevel = 1 } = this.options;
        if (optimizationLevel >= 2) {
            file = this.levelTwoFileOptimize(file);
        }
        this.debug('matchOne', this, { file, pattern });
        this.debug('matchOne', file.length, pattern.length);
        for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
            this.debug('matchOne loop');
            var p = pattern[pi];
            var f = file[fi];
            this.debug(pattern, p, f);
            // should be impossible.
            // some invalid regexp stuff in the set.
            /* c8 ignore start */
            if (p === false) {
                return false;
            }
            /* c8 ignore stop */
            if (p === exports.GLOBSTAR) {
                this.debug('GLOBSTAR', [pattern, p, f]);
                // "**"
                // a/**/b/**/c would match the following:
                // a/b/x/y/z/c
                // a/x/y/z/b/c
                // a/b/x/b/x/c
                // a/b/c
                // To do this, take the rest of the pattern after
                // the **, and see if it would match the file remainder.
                // If so, return success.
                // If not, the ** "swallows" a segment, and try again.
                // This is recursively awful.
                //
                // a/**/b/**/c matching a/b/x/y/z/c
                // - a matches a
                // - doublestar
                //   - matchOne(b/x/y/z/c, b/**/c)
                //     - b matches b
                //     - doublestar
                //       - matchOne(x/y/z/c, c) -> no
                //       - matchOne(y/z/c, c) -> no
                //       - matchOne(z/c, c) -> no
                //       - matchOne(c, c) yes, hit
                var fr = fi;
                var pr = pi + 1;
                if (pr === pl) {
                    this.debug('** at the end');
                    // a ** at the end will just swallow the rest.
                    // We have found a match.
                    // however, it will not swallow /.x, unless
                    // options.dot is set.
                    // . and .. are *never* matched by **, for explosively
                    // exponential reasons.
                    for (; fi < fl; fi++) {
                        if (file[fi] === '.' ||
                            file[fi] === '..' ||
                            (!options.dot && file[fi].charAt(0) === '.'))
                            return false;
                    }
                    return true;
                }
                // ok, let's see if we can swallow whatever we can.
                while (fr < fl) {
                    var swallowee = file[fr];
                    this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
                    // XXX remove this slice.  Just pass the start index.
                    if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
                        this.debug('globstar found match!', fr, fl, swallowee);
                        // found a match.
                        return true;
                    }
                    else {
                        // can't swallow "." or ".." ever.
                        // can only swallow ".foo" when explicitly asked.
                        if (swallowee === '.' ||
                            swallowee === '..' ||
                            (!options.dot && swallowee.charAt(0) === '.')) {
                            this.debug('dot detected!', file, fr, pattern, pr);
                            break;
                        }
                        // ** swallows a segment, and continue.
                        this.debug('globstar swallow a segment, and continue');
                        fr++;
                    }
                }
                // no match was found.
                // However, in partial mode, we can't say this is necessarily over.
                /* c8 ignore start */
                if (partial) {
                    // ran out of file
                    this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
                    if (fr === fl) {
                        return true;
                    }
                }
                /* c8 ignore stop */
                return false;
            }
            // something other than **
            // non-magic patterns just have to match exactly
            // patterns with magic have been turned into regexps.
            let hit;
            if (typeof p === 'string') {
                hit = f === p;
                this.debug('string match', p, f, hit);
            }
            else {
                hit = p.test(f);
                this.debug('pattern match', p, f, hit);
            }
            if (!hit)
                return false;
        }
        // Note: ending in / means that we'll get a final ""
        // at the end of the pattern.  This can only match a
        // corresponding "" at the end of the file.
        // If the file ends in /, then it can only match a
        // a pattern that ends in /, unless the pattern just
        // doesn't have any more for it. But, a/b/ should *not*
        // match "a/b/*", even though "" matches against the
        // [^/]*? pattern, except in partial mode, where it might
        // simply not be reached yet.
        // However, a/b/ should still satisfy a/*
        // now either we fell off the end of the pattern, or we're done.
        if (fi === fl && pi === pl) {
            // ran out of pattern and filename at the same time.
            // an exact hit!
            return true;
        }
        else if (fi === fl) {
            // ran out of file, but still had pattern left.
            // this is ok if we're doing the match as part of
            // a glob fs traversal.
            return partial;
        }
        else if (pi === pl) {
            // ran out of pattern, still have file left.
            // this is only acceptable if we're on the very last
            // empty segment of a file with a trailing slash.
            // a/* should match a/b/
            return fi === fl - 1 && file[fi] === '';
            /* c8 ignore start */
        }
        else {
            // should be unreachable.
            throw new Error('wtf?');
        }
        /* c8 ignore stop */
    }
    braceExpand() {
        return (0, exports.braceExpand)(this.pattern, this.options);
    }
    parse(pattern) {
        (0, assert_valid_pattern_js_1.assertValidPattern)(pattern);
        const options = this.options;
        // shortcuts
        if (pattern === '**')
            return exports.GLOBSTAR;
        if (pattern === '')
            return '';
        // far and away, the most common glob pattern parts are
        // *, *.*, and *.  Add a fast check method for those.
        let m;
        let fastTest = null;
        if ((m = pattern.match(starRE))) {
            fastTest = options.dot ? starTestDot : starTest;
        }
        else if ((m = pattern.match(starDotExtRE))) {
            fastTest = (options.nocase
                ? options.dot
                    ? starDotExtTestNocaseDot
                    : starDotExtTestNocase
                : options.dot
                    ? starDotExtTestDot
                    : starDotExtTest)(m[1]);
        }
        else if ((m = pattern.match(qmarksRE))) {
            fastTest = (options.nocase
                ? options.dot
                    ? qmarksTestNocaseDot
                    : qmarksTestNocase
                : options.dot
                    ? qmarksTestDot
                    : qmarksTest)(m);
        }
        else if ((m = pattern.match(starDotStarRE))) {
            fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
        }
        else if ((m = pattern.match(dotStarRE))) {
            fastTest = dotStarTest;
        }
        const re = ast_js_1.AST.fromGlob(pattern, this.options).toMMPattern();
        if (fastTest && typeof re === 'object') {
            // Avoids overriding in frozen environments
            Reflect.defineProperty(re, 'test', { value: fastTest });
        }
        return re;
    }
    makeRe() {
        if (this.regexp || this.regexp === false)
            return this.regexp;
        // at this point, this.set is a 2d array of partial
        // pattern strings, or "**".
        //
        // It's better to use .match().  This function shouldn't
        // be used, really, but it's pretty convenient sometimes,
        // when you just want to work with a regex.
        const set = this.set;
        if (!set.length) {
            this.regexp = false;
            return this.regexp;
        }
        const options = this.options;
        const twoStar = options.noglobstar
            ? star
            : options.dot
                ? twoStarDot
                : twoStarNoDot;
        const flags = new Set(options.nocase ? ['i'] : []);
        // regexpify non-globstar patterns
        // if ** is only item, then we just do one twoStar
        // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
        // if ** is last, append (\/twoStar|) to previous
        // if ** is in the middle, append (\/|\/twoStar\/) to previous
        // then filter out GLOBSTAR symbols
        let re = set
            .map(pattern => {
            const pp = pattern.map(p => {
                if (p instanceof RegExp) {
                    for (const f of p.flags.split(''))
                        flags.add(f);
                }
                return typeof p === 'string'
                    ? regExpEscape(p)
                    : p === exports.GLOBSTAR
                        ? exports.GLOBSTAR
                        : p._src;
            });
            pp.forEach((p, i) => {
                const next = pp[i + 1];
                const prev = pp[i - 1];
                if (p !== exports.GLOBSTAR || prev === exports.GLOBSTAR) {
                    return;
                }
                if (prev === undefined) {
                    if (next !== undefined && next !== exports.GLOBSTAR) {
                        pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
                    }
                    else {
                        pp[i] = twoStar;
                    }
                }
                else if (next === undefined) {
                    pp[i - 1] = prev + '(?:\\/|' + twoStar + ')?';
                }
                else if (next !== exports.GLOBSTAR) {
                    pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
                    pp[i + 1] = exports.GLOBSTAR;
                }
            });
            return pp.filter(p => p !== exports.GLOBSTAR).join('/');
        })
            .join('|');
        // need to wrap in parens if we had more than one thing with |,
        // otherwise only the first will be anchored to ^ and the last to $
        const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
        // must match entire pattern
        // ending in a * or ** will make it less strict.
        re = '^' + open + re + close + '$';
        // can match anything, as long as it's not this.
        if (this.negate)
            re = '^(?!' + re + ').+$';
        try {
            this.regexp = new RegExp(re, [...flags].join(''));
            /* c8 ignore start */
        }
        catch (ex) {
            // should be impossible
            this.regexp = false;
        }
        /* c8 ignore stop */
        return this.regexp;
    }
    slashSplit(p) {
        // if p starts with // on windows, we preserve that
        // so that UNC paths aren't broken.  Otherwise, any number of
        // / characters are coalesced into one, unless
        // preserveMultipleSlashes is set to true.
        if (this.preserveMultipleSlashes) {
            return p.split('/');
        }
        else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
            // add an extra '' for the one we lose
            return ['', ...p.split(/\/+/)];
        }
        else {
            return p.split(/\/+/);
        }
    }
    match(f, partial = this.partial) {
        this.debug('match', f, this.pattern);
        // short-circuit in the case of busted things.
        // comments, etc.
        if (this.comment) {
            return false;
        }
        if (this.empty) {
            return f === '';
        }
        if (f === '/' && partial) {
            return true;
        }
        const options = this.options;
        // windows: need to use /, not \
        if (this.isWindows) {
            f = f.split('\\').join('/');
        }
        // treat the test path as a set of pathparts.
        const ff = this.slashSplit(f);
        this.debug(this.pattern, 'split', ff);
        // just ONE of the pattern sets in this.set needs to match
        // in order for it to be valid.  If negating, then just one
        // match means that we have failed.
        // Either way, return on the first hit.
        const set = this.set;
        this.debug(this.pattern, 'set', set);
        // Find the basename of the path by looking for the last non-empty segment
        let filename = ff[ff.length - 1];
        if (!filename) {
            for (let i = ff.length - 2; !filename && i >= 0; i--) {
                filename = ff[i];
            }
        }
        for (let i = 0; i < set.length; i++) {
            const pattern = set[i];
            let file = ff;
            if (options.matchBase && pattern.length === 1) {
                file = [filename];
            }
            const hit = this.matchOne(file, pattern, partial);
            if (hit) {
                if (options.flipNegate) {
                    return true;
                }
                return !this.negate;
            }
        }
        // didn't get any hits.  this is success if it's a negative
        // pattern, failure otherwise.
        if (options.flipNegate) {
            return false;
        }
        return this.negate;
    }
    static defaults(def) {
        return exports.minimatch.defaults(def).Minimatch;
    }
}
exports.Minimatch = Minimatch;
/* c8 ignore start */
var ast_js_2 = require("./ast.js");
Object.defineProperty(exports, "AST", { enumerable: true, get: function () { return ast_js_2.AST; } });
var escape_js_2 = require("./escape.js");
Object.defineProperty(exports, "escape", { enumerable: true, get: function () { return escape_js_2.escape; } });
var unescape_js_2 = require("./unescape.js");
Object.defineProperty(exports, "unescape", { enumerable: true, get: function () { return unescape_js_2.unescape; } });
/* c8 ignore stop */
exports.minimatch.AST = ast_js_1.AST;
exports.minimatch.Minimatch = Minimatch;
exports.minimatch.escape = escape_js_1.escape;
exports.minimatch.unescape = unescape_js_1.unescape;
//# sourceMappingURL=index.js.mapPK~\*i&Y&Yminimatch/dist/commonjs/ast.jsnu["use strict";
// parse a single path portion
Object.defineProperty(exports, "__esModule", { value: true });
exports.AST = void 0;
const brace_expressions_js_1 = require("./brace-expressions.js");
const unescape_js_1 = require("./unescape.js");
const types = new Set(['!', '?', '+', '*', '@']);
const isExtglobType = (c) => types.has(c);
// Patterns that get prepended to bind to the start of either the
// entire string, or just a single path portion, to prevent dots
// and/or traversal patterns, when needed.
// Exts don't need the ^ or / bit, because the root binds that already.
const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
const startNoDot = '(?!\\.)';
// characters that indicate a start of pattern needs the "no dots" bit,
// because a dot *might* be matched. ( is not in the list, because in
// the case of a child extglob, it will handle the prevention itself.
const addPatternStart = new Set(['[', '.']);
// cases where traversal is A-OK, no dot prevention needed
const justDots = new Set(['..', '.']);
const reSpecials = new Set('().*{}+?[]^$\\!');
const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
// any single thing other than /
const qmark = '[^/]';
// * => any number of characters
const star = qmark + '*?';
// use + when we need to ensure that *something* matches, because the * is
// the only thing in the path portion.
const starNoEmpty = qmark + '+?';
// remove the \ chars that we added if we end up doing a nonmagic compare
// const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
class AST {
    type;
    #root;
    #hasMagic;
    #uflag = false;
    #parts = [];
    #parent;
    #parentIndex;
    #negs;
    #filledNegs = false;
    #options;
    #toString;
    // set to true if it's an extglob with no children
    // (which really means one child of '')
    #emptyExt = false;
    constructor(type, parent, options = {}) {
        this.type = type;
        // extglobs are inherently magical
        if (type)
            this.#hasMagic = true;
        this.#parent = parent;
        this.#root = this.#parent ? this.#parent.#root : this;
        this.#options = this.#root === this ? options : this.#root.#options;
        this.#negs = this.#root === this ? [] : this.#root.#negs;
        if (type === '!' && !this.#root.#filledNegs)
            this.#negs.push(this);
        this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
    }
    get hasMagic() {
        /* c8 ignore start */
        if (this.#hasMagic !== undefined)
            return this.#hasMagic;
        /* c8 ignore stop */
        for (const p of this.#parts) {
            if (typeof p === 'string')
                continue;
            if (p.type || p.hasMagic)
                return (this.#hasMagic = true);
        }
        // note: will be undefined until we generate the regexp src and find out
        return this.#hasMagic;
    }
    // reconstructs the pattern
    toString() {
        if (this.#toString !== undefined)
            return this.#toString;
        if (!this.type) {
            return (this.#toString = this.#parts.map(p => String(p)).join(''));
        }
        else {
            return (this.#toString =
                this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')');
        }
    }
    #fillNegs() {
        /* c8 ignore start */
        if (this !== this.#root)
            throw new Error('should only call on root');
        if (this.#filledNegs)
            return this;
        /* c8 ignore stop */
        // call toString() once to fill this out
        this.toString();
        this.#filledNegs = true;
        let n;
        while ((n = this.#negs.pop())) {
            if (n.type !== '!')
                continue;
            // walk up the tree, appending everthing that comes AFTER parentIndex
            let p = n;
            let pp = p.#parent;
            while (pp) {
                for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
                    for (const part of n.#parts) {
                        /* c8 ignore start */
                        if (typeof part === 'string') {
                            throw new Error('string part in extglob AST??');
                        }
                        /* c8 ignore stop */
                        part.copyIn(pp.#parts[i]);
                    }
                }
                p = pp;
                pp = p.#parent;
            }
        }
        return this;
    }
    push(...parts) {
        for (const p of parts) {
            if (p === '')
                continue;
            /* c8 ignore start */
            if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {
                throw new Error('invalid part: ' + p);
            }
            /* c8 ignore stop */
            this.#parts.push(p);
        }
    }
    toJSON() {
        const ret = this.type === null
            ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))
            : [this.type, ...this.#parts.map(p => p.toJSON())];
        if (this.isStart() && !this.type)
            ret.unshift([]);
        if (this.isEnd() &&
            (this === this.#root ||
                (this.#root.#filledNegs && this.#parent?.type === '!'))) {
            ret.push({});
        }
        return ret;
    }
    isStart() {
        if (this.#root === this)
            return true;
        // if (this.type) return !!this.#parent?.isStart()
        if (!this.#parent?.isStart())
            return false;
        if (this.#parentIndex === 0)
            return true;
        // if everything AHEAD of this is a negation, then it's still the "start"
        const p = this.#parent;
        for (let i = 0; i < this.#parentIndex; i++) {
            const pp = p.#parts[i];
            if (!(pp instanceof AST && pp.type === '!')) {
                return false;
            }
        }
        return true;
    }
    isEnd() {
        if (this.#root === this)
            return true;
        if (this.#parent?.type === '!')
            return true;
        if (!this.#parent?.isEnd())
            return false;
        if (!this.type)
            return this.#parent?.isEnd();
        // if not root, it'll always have a parent
        /* c8 ignore start */
        const pl = this.#parent ? this.#parent.#parts.length : 0;
        /* c8 ignore stop */
        return this.#parentIndex === pl - 1;
    }
    copyIn(part) {
        if (typeof part === 'string')
            this.push(part);
        else
            this.push(part.clone(this));
    }
    clone(parent) {
        const c = new AST(this.type, parent);
        for (const p of this.#parts) {
            c.copyIn(p);
        }
        return c;
    }
    static #parseAST(str, ast, pos, opt) {
        let escaping = false;
        let inBrace = false;
        let braceStart = -1;
        let braceNeg = false;
        if (ast.type === null) {
            // outside of a extglob, append until we find a start
            let i = pos;
            let acc = '';
            while (i < str.length) {
                const c = str.charAt(i++);
                // still accumulate escapes at this point, but we do ignore
                // starts that are escaped
                if (escaping || c === '\\') {
                    escaping = !escaping;
                    acc += c;
                    continue;
                }
                if (inBrace) {
                    if (i === braceStart + 1) {
                        if (c === '^' || c === '!') {
                            braceNeg = true;
                        }
                    }
                    else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
                        inBrace = false;
                    }
                    acc += c;
                    continue;
                }
                else if (c === '[') {
                    inBrace = true;
                    braceStart = i;
                    braceNeg = false;
                    acc += c;
                    continue;
                }
                if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {
                    ast.push(acc);
                    acc = '';
                    const ext = new AST(c, ast);
                    i = AST.#parseAST(str, ext, i, opt);
                    ast.push(ext);
                    continue;
                }
                acc += c;
            }
            ast.push(acc);
            return i;
        }
        // some kind of extglob, pos is at the (
        // find the next | or )
        let i = pos + 1;
        let part = new AST(null, ast);
        const parts = [];
        let acc = '';
        while (i < str.length) {
            const c = str.charAt(i++);
            // still accumulate escapes at this point, but we do ignore
            // starts that are escaped
            if (escaping || c === '\\') {
                escaping = !escaping;
                acc += c;
                continue;
            }
            if (inBrace) {
                if (i === braceStart + 1) {
                    if (c === '^' || c === '!') {
                        braceNeg = true;
                    }
                }
                else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
                    inBrace = false;
                }
                acc += c;
                continue;
            }
            else if (c === '[') {
                inBrace = true;
                braceStart = i;
                braceNeg = false;
                acc += c;
                continue;
            }
            if (isExtglobType(c) && str.charAt(i) === '(') {
                part.push(acc);
                acc = '';
                const ext = new AST(c, part);
                part.push(ext);
                i = AST.#parseAST(str, ext, i, opt);
                continue;
            }
            if (c === '|') {
                part.push(acc);
                acc = '';
                parts.push(part);
                part = new AST(null, ast);
                continue;
            }
            if (c === ')') {
                if (acc === '' && ast.#parts.length === 0) {
                    ast.#emptyExt = true;
                }
                part.push(acc);
                acc = '';
                ast.push(...parts, part);
                return i;
            }
            acc += c;
        }
        // unfinished extglob
        // if we got here, it was a malformed extglob! not an extglob, but
        // maybe something else in there.
        ast.type = null;
        ast.#hasMagic = undefined;
        ast.#parts = [str.substring(pos - 1)];
        return i;
    }
    static fromGlob(pattern, options = {}) {
        const ast = new AST(null, undefined, options);
        AST.#parseAST(pattern, ast, 0, options);
        return ast;
    }
    // returns the regular expression if there's magic, or the unescaped
    // string if not.
    toMMPattern() {
        // should only be called on root
        /* c8 ignore start */
        if (this !== this.#root)
            return this.#root.toMMPattern();
        /* c8 ignore stop */
        const glob = this.toString();
        const [re, body, hasMagic, uflag] = this.toRegExpSource();
        // if we're in nocase mode, and not nocaseMagicOnly, then we do
        // still need a regular expression if we have to case-insensitively
        // match capital/lowercase characters.
        const anyMagic = hasMagic ||
            this.#hasMagic ||
            (this.#options.nocase &&
                !this.#options.nocaseMagicOnly &&
                glob.toUpperCase() !== glob.toLowerCase());
        if (!anyMagic) {
            return body;
        }
        const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
        return Object.assign(new RegExp(`^${re}$`, flags), {
            _src: re,
            _glob: glob,
        });
    }
    get options() {
        return this.#options;
    }
    // returns the string match, the regexp source, whether there's magic
    // in the regexp (so a regular expression is required) and whether or
    // not the uflag is needed for the regular expression (for posix classes)
    // TODO: instead of injecting the start/end at this point, just return
    // the BODY of the regexp, along with the start/end portions suitable
    // for binding the start/end in either a joined full-path makeRe context
    // (where we bind to (^|/), or a standalone matchPart context (where
    // we bind to ^, and not /).  Otherwise slashes get duped!
    //
    // In part-matching mode, the start is:
    // - if not isStart: nothing
    // - if traversal possible, but not allowed: ^(?!\.\.?$)
    // - if dots allowed or not possible: ^
    // - if dots possible and not allowed: ^(?!\.)
    // end is:
    // - if not isEnd(): nothing
    // - else: $
    //
    // In full-path matching mode, we put the slash at the START of the
    // pattern, so start is:
    // - if first pattern: same as part-matching mode
    // - if not isStart(): nothing
    // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
    // - if dots allowed or not possible: /
    // - if dots possible and not allowed: /(?!\.)
    // end is:
    // - if last pattern, same as part-matching mode
    // - else nothing
    //
    // Always put the (?:$|/) on negated tails, though, because that has to be
    // there to bind the end of the negated pattern portion, and it's easier to
    // just stick it in now rather than try to inject it later in the middle of
    // the pattern.
    //
    // We can just always return the same end, and leave it up to the caller
    // to know whether it's going to be used joined or in parts.
    // And, if the start is adjusted slightly, can do the same there:
    // - if not isStart: nothing
    // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
    // - if dots allowed or not possible: (?:/|^)
    // - if dots possible and not allowed: (?:/|^)(?!\.)
    //
    // But it's better to have a simpler binding without a conditional, for
    // performance, so probably better to return both start options.
    //
    // Then the caller just ignores the end if it's not the first pattern,
    // and the start always gets applied.
    //
    // But that's always going to be $ if it's the ending pattern, or nothing,
    // so the caller can just attach $ at the end of the pattern when building.
    //
    // So the todo is:
    // - better detect what kind of start is needed
    // - return both flavors of starting pattern
    // - attach $ at the end of the pattern when creating the actual RegExp
    //
    // Ah, but wait, no, that all only applies to the root when the first pattern
    // is not an extglob. If the first pattern IS an extglob, then we need all
    // that dot prevention biz to live in the extglob portions, because eg
    // +(*|.x*) can match .xy but not .yx.
    //
    // So, return the two flavors if it's #root and the first child is not an
    // AST, otherwise leave it to the child AST to handle it, and there,
    // use the (?:^|/) style of start binding.
    //
    // Even simplified further:
    // - Since the start for a join is eg /(?!\.) and the start for a part
    // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
    // or start or whatever) and prepend ^ or / at the Regexp construction.
    toRegExpSource(allowDot) {
        const dot = allowDot ?? !!this.#options.dot;
        if (this.#root === this)
            this.#fillNegs();
        if (!this.type) {
            const noEmpty = this.isStart() && this.isEnd();
            const src = this.#parts
                .map(p => {
                const [re, _, hasMagic, uflag] = typeof p === 'string'
                    ? AST.#parseGlob(p, this.#hasMagic, noEmpty)
                    : p.toRegExpSource(allowDot);
                this.#hasMagic = this.#hasMagic || hasMagic;
                this.#uflag = this.#uflag || uflag;
                return re;
            })
                .join('');
            let start = '';
            if (this.isStart()) {
                if (typeof this.#parts[0] === 'string') {
                    // this is the string that will match the start of the pattern,
                    // so we need to protect against dots and such.
                    // '.' and '..' cannot match unless the pattern is that exactly,
                    // even if it starts with . or dot:true is set.
                    const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
                    if (!dotTravAllowed) {
                        const aps = addPatternStart;
                        // check if we have a possibility of matching . or ..,
                        // and prevent that.
                        const needNoTrav = 
                        // dots are allowed, and the pattern starts with [ or .
                        (dot && aps.has(src.charAt(0))) ||
                            // the pattern starts with \., and then [ or .
                            (src.startsWith('\\.') && aps.has(src.charAt(2))) ||
                            // the pattern starts with \.\., and then [ or .
                            (src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
                        // no need to prevent dots if it can't match a dot, or if a
                        // sub-pattern will be preventing it anyway.
                        const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
                        start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : '';
                    }
                }
            }
            // append the "end of path portion" pattern to negation tails
            let end = '';
            if (this.isEnd() &&
                this.#root.#filledNegs &&
                this.#parent?.type === '!') {
                end = '(?:$|\\/)';
            }
            const final = start + src + end;
            return [
                final,
                (0, unescape_js_1.unescape)(src),
                (this.#hasMagic = !!this.#hasMagic),
                this.#uflag,
            ];
        }
        // We need to calculate the body *twice* if it's a repeat pattern
        // at the start, once in nodot mode, then again in dot mode, so a
        // pattern like *(?) can match 'x.y'
        const repeated = this.type === '*' || this.type === '+';
        // some kind of extglob
        const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
        let body = this.#partsToRegExp(dot);
        if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
            // invalid extglob, has to at least be *something* present, if it's
            // the entire path portion.
            const s = this.toString();
            this.#parts = [s];
            this.type = null;
            this.#hasMagic = undefined;
            return [s, (0, unescape_js_1.unescape)(this.toString()), false, false];
        }
        // XXX abstract out this map method
        let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot
            ? ''
            : this.#partsToRegExp(true);
        if (bodyDotAllowed === body) {
            bodyDotAllowed = '';
        }
        if (bodyDotAllowed) {
            body = `(?:${body})(?:${bodyDotAllowed})*?`;
        }
        // an empty !() is exactly equivalent to a starNoEmpty
        let final = '';
        if (this.type === '!' && this.#emptyExt) {
            final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
        }
        else {
            const close = this.type === '!'
                ? // !() must match something,but !(x) can match ''
                    '))' +
                        (this.isStart() && !dot && !allowDot ? startNoDot : '') +
                        star +
                        ')'
                : this.type === '@'
                    ? ')'
                    : this.type === '?'
                        ? ')?'
                        : this.type === '+' && bodyDotAllowed
                            ? ')'
                            : this.type === '*' && bodyDotAllowed
                                ? `)?`
                                : `)${this.type}`;
            final = start + body + close;
        }
        return [
            final,
            (0, unescape_js_1.unescape)(body),
            (this.#hasMagic = !!this.#hasMagic),
            this.#uflag,
        ];
    }
    #partsToRegExp(dot) {
        return this.#parts
            .map(p => {
            // extglob ASTs should only contain parent ASTs
            /* c8 ignore start */
            if (typeof p === 'string') {
                throw new Error('string type in extglob ast??');
            }
            /* c8 ignore stop */
            // can ignore hasMagic, because extglobs are already always magic
            const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
            this.#uflag = this.#uflag || uflag;
            return re;
        })
            .filter(p => !(this.isStart() && this.isEnd()) || !!p)
            .join('|');
    }
    static #parseGlob(glob, hasMagic, noEmpty = false) {
        let escaping = false;
        let re = '';
        let uflag = false;
        for (let i = 0; i < glob.length; i++) {
            const c = glob.charAt(i);
            if (escaping) {
                escaping = false;
                re += (reSpecials.has(c) ? '\\' : '') + c;
                continue;
            }
            if (c === '\\') {
                if (i === glob.length - 1) {
                    re += '\\\\';
                }
                else {
                    escaping = true;
                }
                continue;
            }
            if (c === '[') {
                const [src, needUflag, consumed, magic] = (0, brace_expressions_js_1.parseClass)(glob, i);
                if (consumed) {
                    re += src;
                    uflag = uflag || needUflag;
                    i += consumed - 1;
                    hasMagic = hasMagic || magic;
                    continue;
                }
            }
            if (c === '*') {
                if (noEmpty && glob === '*')
                    re += starNoEmpty;
                else
                    re += star;
                hasMagic = true;
                continue;
            }
            if (c === '?') {
                re += qmark;
                hasMagic = true;
                continue;
            }
            re += regExpEscape(c);
        }
        return [re, (0, unescape_js_1.unescape)(glob), !!hasMagic, uflag];
    }
}
exports.AST = AST;
//# sourceMappingURL=ast.js.mapPK~\FEPPminimatch/dist/esm/escape.jsnu[/**
 * Escape all magic characters in a glob pattern.
 *
 * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}
 * option is used, then characters are escaped by wrapping in `[]`, because
 * a magic character wrapped in a character class can only be satisfied by
 * that exact character.  In this mode, `\` is _not_ escaped, because it is
 * not interpreted as a magic character, but instead as a path separator.
 */
export const escape = (s, { windowsPathsNoEscape = false, } = {}) => {
    // don't need to escape +@! because we escape the parens
    // that make those magic, and escaping ! as [!] isn't valid,
    // because [!]] is a valid glob class meaning not ']'.
    return windowsPathsNoEscape
        ? s.replace(/[?*()[\]]/g, '[$&]')
        : s.replace(/[?*()[\]\\]/g, '\\$&');
};
//# sourceMappingURL=escape.js.mapPK~\[EPP*minimatch/dist/esm/assert-valid-pattern.jsnu[const MAX_PATTERN_LENGTH = 1024 * 64;
export const assertValidPattern = (pattern) => {
    if (typeof pattern !== 'string') {
        throw new TypeError('invalid pattern');
    }
    if (pattern.length > MAX_PATTERN_LENGTH) {
        throw new TypeError('pattern is too long');
    }
};
//# sourceMappingURL=assert-valid-pattern.js.mapPK~\xminimatch/dist/esm/package.jsonnu[{
  "type": "module"
}
PK~\'minimatch/dist/esm/brace-expressions.jsnu[// translate the various posix character classes into unicode properties
// this works across all unicode locales
// { : [, /u flag required, negated]
const posixClasses = {
    '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
    '[:alpha:]': ['\\p{L}\\p{Nl}', true],
    '[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
    '[:blank:]': ['\\p{Zs}\\t', true],
    '[:cntrl:]': ['\\p{Cc}', true],
    '[:digit:]': ['\\p{Nd}', true],
    '[:graph:]': ['\\p{Z}\\p{C}', true, true],
    '[:lower:]': ['\\p{Ll}', true],
    '[:print:]': ['\\p{C}', true],
    '[:punct:]': ['\\p{P}', true],
    '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
    '[:upper:]': ['\\p{Lu}', true],
    '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
    '[:xdigit:]': ['A-Fa-f0-9', false],
};
// only need to escape a few things inside of brace expressions
// escapes: [ \ ] -
const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
// escape all regexp magic characters
const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
// everything has already been escaped, we just have to join
const rangesToString = (ranges) => ranges.join('');
// takes a glob string at a posix brace expression, and returns
// an equivalent regular expression source, and boolean indicating
// whether the /u flag needs to be applied, and the number of chars
// consumed to parse the character class.
// This also removes out of order ranges, and returns ($.) if the
// entire class just no good.
export const parseClass = (glob, position) => {
    const pos = position;
    /* c8 ignore start */
    if (glob.charAt(pos) !== '[') {
        throw new Error('not in a brace expression');
    }
    /* c8 ignore stop */
    const ranges = [];
    const negs = [];
    let i = pos + 1;
    let sawStart = false;
    let uflag = false;
    let escaping = false;
    let negate = false;
    let endPos = pos;
    let rangeStart = '';
    WHILE: while (i < glob.length) {
        const c = glob.charAt(i);
        if ((c === '!' || c === '^') && i === pos + 1) {
            negate = true;
            i++;
            continue;
        }
        if (c === ']' && sawStart && !escaping) {
            endPos = i + 1;
            break;
        }
        sawStart = true;
        if (c === '\\') {
            if (!escaping) {
                escaping = true;
                i++;
                continue;
            }
            // escaped \ char, fall through and treat like normal char
        }
        if (c === '[' && !escaping) {
            // either a posix class, a collation equivalent, or just a [
            for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
                if (glob.startsWith(cls, i)) {
                    // invalid, [a-[] is fine, but not [a-[:alpha]]
                    if (rangeStart) {
                        return ['$.', false, glob.length - pos, true];
                    }
                    i += cls.length;
                    if (neg)
                        negs.push(unip);
                    else
                        ranges.push(unip);
                    uflag = uflag || u;
                    continue WHILE;
                }
            }
        }
        // now it's just a normal character, effectively
        escaping = false;
        if (rangeStart) {
            // throw this range away if it's not valid, but others
            // can still match.
            if (c > rangeStart) {
                ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
            }
            else if (c === rangeStart) {
                ranges.push(braceEscape(c));
            }
            rangeStart = '';
            i++;
            continue;
        }
        // now might be the start of a range.
        // can be either c-d or c-] or c] or c] at this point
        if (glob.startsWith('-]', i + 1)) {
            ranges.push(braceEscape(c + '-'));
            i += 2;
            continue;
        }
        if (glob.startsWith('-', i + 1)) {
            rangeStart = c;
            i += 2;
            continue;
        }
        // not the start of a range, just a single character
        ranges.push(braceEscape(c));
        i++;
    }
    if (endPos < i) {
        // didn't see the end of the class, not a valid class,
        // but might still be valid as a literal match.
        return ['', false, 0, false];
    }
    // if we got no ranges and no negates, then we have a range that
    // cannot possibly match anything, and that poisons the whole glob
    if (!ranges.length && !negs.length) {
        return ['$.', false, glob.length - pos, true];
    }
    // if we got one positive range, and it's a single character, then that's
    // not actually a magic pattern, it's just that one literal character.
    // we should not treat that as "magic", we should just return the literal
    // character. [_] is a perfectly valid way to escape glob magic chars.
    if (negs.length === 0 &&
        ranges.length === 1 &&
        /^\\?.$/.test(ranges[0]) &&
        !negate) {
        const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
        return [regexpEscape(r), false, endPos - pos, false];
    }
    const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
    const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
    const comb = ranges.length && negs.length
        ? '(' + sranges + '|' + snegs + ')'
        : ranges.length
            ? sranges
            : snegs;
    return [comb, uflag, endPos - pos, true];
};
//# sourceMappingURL=brace-expressions.js.mapPK~\'7~OOminimatch/dist/esm/unescape.jsnu[/**
 * Un-escape a string that has been escaped with {@link escape}.
 *
 * If the {@link windowsPathsNoEscape} option is used, then square-brace
 * escapes are removed, but not backslash escapes.  For example, it will turn
 * the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`,
 * becuase `\` is a path separator in `windowsPathsNoEscape` mode.
 *
 * When `windowsPathsNoEscape` is not set, then both brace escapes and
 * backslash escapes are removed.
 *
 * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
 * or unescaped.
 */
export const unescape = (s, { windowsPathsNoEscape = false, } = {}) => {
    return windowsPathsNoEscape
        ? s.replace(/\[([^\/\\])\]/g, '$1')
        : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2').replace(/\\([^\/])/g, '$1');
};
//# sourceMappingURL=unescape.js.mapPK~\.$minimatch/dist/esm/index.jsnu[import expand from 'brace-expansion';
import { assertValidPattern } from './assert-valid-pattern.js';
import { AST } from './ast.js';
import { escape } from './escape.js';
import { unescape } from './unescape.js';
export const minimatch = (p, pattern, options = {}) => {
    assertValidPattern(pattern);
    // shortcut: comments match nothing.
    if (!options.nocomment && pattern.charAt(0) === '#') {
        return false;
    }
    return new Minimatch(pattern, options).match(p);
};
// Optimized checking for the most common glob patterns.
const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext);
const starDotExtTestDot = (ext) => (f) => f.endsWith(ext);
const starDotExtTestNocase = (ext) => {
    ext = ext.toLowerCase();
    return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext);
};
const starDotExtTestNocaseDot = (ext) => {
    ext = ext.toLowerCase();
    return (f) => f.toLowerCase().endsWith(ext);
};
const starDotStarRE = /^\*+\.\*+$/;
const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.');
const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.');
const dotStarRE = /^\.\*+$/;
const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.');
const starRE = /^\*+$/;
const starTest = (f) => f.length !== 0 && !f.startsWith('.');
const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..';
const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
const qmarksTestNocase = ([$0, ext = '']) => {
    const noext = qmarksTestNoExt([$0]);
    if (!ext)
        return noext;
    ext = ext.toLowerCase();
    return (f) => noext(f) && f.toLowerCase().endsWith(ext);
};
const qmarksTestNocaseDot = ([$0, ext = '']) => {
    const noext = qmarksTestNoExtDot([$0]);
    if (!ext)
        return noext;
    ext = ext.toLowerCase();
    return (f) => noext(f) && f.toLowerCase().endsWith(ext);
};
const qmarksTestDot = ([$0, ext = '']) => {
    const noext = qmarksTestNoExtDot([$0]);
    return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
};
const qmarksTest = ([$0, ext = '']) => {
    const noext = qmarksTestNoExt([$0]);
    return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
};
const qmarksTestNoExt = ([$0]) => {
    const len = $0.length;
    return (f) => f.length === len && !f.startsWith('.');
};
const qmarksTestNoExtDot = ([$0]) => {
    const len = $0.length;
    return (f) => f.length === len && f !== '.' && f !== '..';
};
/* c8 ignore start */
const defaultPlatform = (typeof process === 'object' && process
    ? (typeof process.env === 'object' &&
        process.env &&
        process.env.__MINIMATCH_TESTING_PLATFORM__) ||
        process.platform
    : 'posix');
const path = {
    win32: { sep: '\\' },
    posix: { sep: '/' },
};
/* c8 ignore stop */
export const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep;
minimatch.sep = sep;
export const GLOBSTAR = Symbol('globstar **');
minimatch.GLOBSTAR = GLOBSTAR;
// any single thing other than /
// don't need to escape / when using new RegExp()
const qmark = '[^/]';
// * => any number of characters
const star = qmark + '*?';
// ** when dots are allowed.  Anything goes, except .. and .
// not (^ or / followed by one or two dots followed by $ or /),
// followed by anything, any number of times.
const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?';
// not a ^ or / followed by a dot,
// followed by anything, any number of times.
const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?';
export const filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
minimatch.filter = filter;
const ext = (a, b = {}) => Object.assign({}, a, b);
export const defaults = (def) => {
    if (!def || typeof def !== 'object' || !Object.keys(def).length) {
        return minimatch;
    }
    const orig = minimatch;
    const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
    return Object.assign(m, {
        Minimatch: class Minimatch extends orig.Minimatch {
            constructor(pattern, options = {}) {
                super(pattern, ext(def, options));
            }
            static defaults(options) {
                return orig.defaults(ext(def, options)).Minimatch;
            }
        },
        AST: class AST extends orig.AST {
            /* c8 ignore start */
            constructor(type, parent, options = {}) {
                super(type, parent, ext(def, options));
            }
            /* c8 ignore stop */
            static fromGlob(pattern, options = {}) {
                return orig.AST.fromGlob(pattern, ext(def, options));
            }
        },
        unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
        escape: (s, options = {}) => orig.escape(s, ext(def, options)),
        filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
        defaults: (options) => orig.defaults(ext(def, options)),
        makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
        braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
        match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
        sep: orig.sep,
        GLOBSTAR: GLOBSTAR,
    });
};
minimatch.defaults = defaults;
// Brace expansion:
// a{b,c}d -> abd acd
// a{b,}c -> abc ac
// a{0..3}d -> a0d a1d a2d a3d
// a{b,c{d,e}f}g -> abg acdfg acefg
// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
//
// Invalid sets are not expanded.
// a{2..}b -> a{2..}b
// a{b}c -> a{b}c
export const braceExpand = (pattern, options = {}) => {
    assertValidPattern(pattern);
    // Thanks to Yeting Li  for
    // improving this regexp to avoid a ReDOS vulnerability.
    if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
        // shortcut. no need to expand.
        return [pattern];
    }
    return expand(pattern);
};
minimatch.braceExpand = braceExpand;
// parse a component of the expanded set.
// At this point, no pattern may contain "/" in it
// so we're going to return a 2d array, where each entry is the full
// pattern, split on '/', and then turned into a regular expression.
// A regexp is made at the end which joins each array with an
// escaped /, and another full one which joins each regexp with |.
//
// Following the lead of Bash 4.1, note that "**" only has special meaning
// when it is the *only* thing in a path portion.  Otherwise, any series
// of * is equivalent to a single *.  Globstar behavior is enabled by
// default, and can be disabled by setting options.noglobstar.
export const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
minimatch.makeRe = makeRe;
export const match = (list, pattern, options = {}) => {
    const mm = new Minimatch(pattern, options);
    list = list.filter(f => mm.match(f));
    if (mm.options.nonull && !list.length) {
        list.push(pattern);
    }
    return list;
};
minimatch.match = match;
// replace stuff like \* with *
const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
export class Minimatch {
    options;
    set;
    pattern;
    windowsPathsNoEscape;
    nonegate;
    negate;
    comment;
    empty;
    preserveMultipleSlashes;
    partial;
    globSet;
    globParts;
    nocase;
    isWindows;
    platform;
    windowsNoMagicRoot;
    regexp;
    constructor(pattern, options = {}) {
        assertValidPattern(pattern);
        options = options || {};
        this.options = options;
        this.pattern = pattern;
        this.platform = options.platform || defaultPlatform;
        this.isWindows = this.platform === 'win32';
        this.windowsPathsNoEscape =
            !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
        if (this.windowsPathsNoEscape) {
            this.pattern = this.pattern.replace(/\\/g, '/');
        }
        this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
        this.regexp = null;
        this.negate = false;
        this.nonegate = !!options.nonegate;
        this.comment = false;
        this.empty = false;
        this.partial = !!options.partial;
        this.nocase = !!this.options.nocase;
        this.windowsNoMagicRoot =
            options.windowsNoMagicRoot !== undefined
                ? options.windowsNoMagicRoot
                : !!(this.isWindows && this.nocase);
        this.globSet = [];
        this.globParts = [];
        this.set = [];
        // make the set of regexps etc.
        this.make();
    }
    hasMagic() {
        if (this.options.magicalBraces && this.set.length > 1) {
            return true;
        }
        for (const pattern of this.set) {
            for (const part of pattern) {
                if (typeof part !== 'string')
                    return true;
            }
        }
        return false;
    }
    debug(..._) { }
    make() {
        const pattern = this.pattern;
        const options = this.options;
        // empty patterns and comments match nothing.
        if (!options.nocomment && pattern.charAt(0) === '#') {
            this.comment = true;
            return;
        }
        if (!pattern) {
            this.empty = true;
            return;
        }
        // step 1: figure out negation, etc.
        this.parseNegate();
        // step 2: expand braces
        this.globSet = [...new Set(this.braceExpand())];
        if (options.debug) {
            this.debug = (...args) => console.error(...args);
        }
        this.debug(this.pattern, this.globSet);
        // step 3: now we have a set, so turn each one into a series of
        // path-portion matching patterns.
        // These will be regexps, except in the case of "**", which is
        // set to the GLOBSTAR object for globstar behavior,
        // and will not contain any / characters
        //
        // First, we preprocess to make the glob pattern sets a bit simpler
        // and deduped.  There are some perf-killing patterns that can cause
        // problems with a glob walk, but we can simplify them down a bit.
        const rawGlobParts = this.globSet.map(s => this.slashSplit(s));
        this.globParts = this.preprocess(rawGlobParts);
        this.debug(this.pattern, this.globParts);
        // glob --> regexps
        let set = this.globParts.map((s, _, __) => {
            if (this.isWindows && this.windowsNoMagicRoot) {
                // check if it's a drive or unc path.
                const isUNC = s[0] === '' &&
                    s[1] === '' &&
                    (s[2] === '?' || !globMagic.test(s[2])) &&
                    !globMagic.test(s[3]);
                const isDrive = /^[a-z]:/i.test(s[0]);
                if (isUNC) {
                    return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))];
                }
                else if (isDrive) {
                    return [s[0], ...s.slice(1).map(ss => this.parse(ss))];
                }
            }
            return s.map(ss => this.parse(ss));
        });
        this.debug(this.pattern, set);
        // filter out everything that didn't compile properly.
        this.set = set.filter(s => s.indexOf(false) === -1);
        // do not treat the ? in UNC paths as magic
        if (this.isWindows) {
            for (let i = 0; i < this.set.length; i++) {
                const p = this.set[i];
                if (p[0] === '' &&
                    p[1] === '' &&
                    this.globParts[i][2] === '?' &&
                    typeof p[3] === 'string' &&
                    /^[a-z]:$/i.test(p[3])) {
                    p[2] = '?';
                }
            }
        }
        this.debug(this.pattern, this.set);
    }
    // various transforms to equivalent pattern sets that are
    // faster to process in a filesystem walk.  The goal is to
    // eliminate what we can, and push all ** patterns as far
    // to the right as possible, even if it increases the number
    // of patterns that we have to process.
    preprocess(globParts) {
        // if we're not in globstar mode, then turn all ** into *
        if (this.options.noglobstar) {
            for (let i = 0; i < globParts.length; i++) {
                for (let j = 0; j < globParts[i].length; j++) {
                    if (globParts[i][j] === '**') {
                        globParts[i][j] = '*';
                    }
                }
            }
        }
        const { optimizationLevel = 1 } = this.options;
        if (optimizationLevel >= 2) {
            // aggressive optimization for the purpose of fs walking
            globParts = this.firstPhasePreProcess(globParts);
            globParts = this.secondPhasePreProcess(globParts);
        }
        else if (optimizationLevel >= 1) {
            // just basic optimizations to remove some .. parts
            globParts = this.levelOneOptimize(globParts);
        }
        else {
            // just collapse multiple ** portions into one
            globParts = this.adjascentGlobstarOptimize(globParts);
        }
        return globParts;
    }
    // just get rid of adjascent ** portions
    adjascentGlobstarOptimize(globParts) {
        return globParts.map(parts => {
            let gs = -1;
            while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
                let i = gs;
                while (parts[i + 1] === '**') {
                    i++;
                }
                if (i !== gs) {
                    parts.splice(gs, i - gs);
                }
            }
            return parts;
        });
    }
    // get rid of adjascent ** and resolve .. portions
    levelOneOptimize(globParts) {
        return globParts.map(parts => {
            parts = parts.reduce((set, part) => {
                const prev = set[set.length - 1];
                if (part === '**' && prev === '**') {
                    return set;
                }
                if (part === '..') {
                    if (prev && prev !== '..' && prev !== '.' && prev !== '**') {
                        set.pop();
                        return set;
                    }
                }
                set.push(part);
                return set;
            }, []);
            return parts.length === 0 ? [''] : parts;
        });
    }
    levelTwoFileOptimize(parts) {
        if (!Array.isArray(parts)) {
            parts = this.slashSplit(parts);
        }
        let didSomething = false;
        do {
            didSomething = false;
            // 
// -> 
/
            if (!this.preserveMultipleSlashes) {
                for (let i = 1; i < parts.length - 1; i++) {
                    const p = parts[i];
                    // don't squeeze out UNC patterns
                    if (i === 1 && p === '' && parts[0] === '')
                        continue;
                    if (p === '.' || p === '') {
                        didSomething = true;
                        parts.splice(i, 1);
                        i--;
                    }
                }
                if (parts[0] === '.' &&
                    parts.length === 2 &&
                    (parts[1] === '.' || parts[1] === '')) {
                    didSomething = true;
                    parts.pop();
                }
            }
            // 
/

/../ ->

/
            let dd = 0;
            while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
                const p = parts[dd - 1];
                if (p && p !== '.' && p !== '..' && p !== '**') {
                    didSomething = true;
                    parts.splice(dd - 1, 2);
                    dd -= 2;
                }
            }
        } while (didSomething);
        return parts.length === 0 ? [''] : parts;
    }
    // First phase: single-pattern processing
    // 
 is 1 or more portions
    //  is 1 or more portions
    // 

is any portion other than ., .., '', or ** // is . or '' // // **/.. is *brutal* for filesystem walking performance, because // it effectively resets the recursive walk each time it occurs, // and ** cannot be reduced out by a .. pattern part like a regexp // or most strings (other than .., ., and '') can be. // //

/**/../

/

/ -> {

/../

/

/,

/**/

/

/} //

// -> 
/
    // 
/

/../ ->

/
    // **/**/ -> **/
    //
    // **/*/ -> */**/ <== not valid because ** doesn't follow
    // this WOULD be allowed if ** did follow symlinks, or * didn't
    firstPhasePreProcess(globParts) {
        let didSomething = false;
        do {
            didSomething = false;
            // 
/**/../

/

/ -> {

/../

/

/,

/**/

/

/} for (let parts of globParts) { let gs = -1; while (-1 !== (gs = parts.indexOf('**', gs + 1))) { let gss = gs; while (parts[gss + 1] === '**') { //

/**/**/ -> 
/**/
                        gss++;
                    }
                    // eg, if gs is 2 and gss is 4, that means we have 3 **
                    // parts, and can remove 2 of them.
                    if (gss > gs) {
                        parts.splice(gs + 1, gss - gs);
                    }
                    let next = parts[gs + 1];
                    const p = parts[gs + 2];
                    const p2 = parts[gs + 3];
                    if (next !== '..')
                        continue;
                    if (!p ||
                        p === '.' ||
                        p === '..' ||
                        !p2 ||
                        p2 === '.' ||
                        p2 === '..') {
                        continue;
                    }
                    didSomething = true;
                    // edit parts in place, and push the new one
                    parts.splice(gs, 1);
                    const other = parts.slice(0);
                    other[gs] = '**';
                    globParts.push(other);
                    gs--;
                }
                // 
// -> 
/
                if (!this.preserveMultipleSlashes) {
                    for (let i = 1; i < parts.length - 1; i++) {
                        const p = parts[i];
                        // don't squeeze out UNC patterns
                        if (i === 1 && p === '' && parts[0] === '')
                            continue;
                        if (p === '.' || p === '') {
                            didSomething = true;
                            parts.splice(i, 1);
                            i--;
                        }
                    }
                    if (parts[0] === '.' &&
                        parts.length === 2 &&
                        (parts[1] === '.' || parts[1] === '')) {
                        didSomething = true;
                        parts.pop();
                    }
                }
                // 
/

/../ ->

/
                let dd = 0;
                while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
                    const p = parts[dd - 1];
                    if (p && p !== '.' && p !== '..' && p !== '**') {
                        didSomething = true;
                        const needDot = dd === 1 && parts[dd + 1] === '**';
                        const splin = needDot ? ['.'] : [];
                        parts.splice(dd - 1, 2, ...splin);
                        if (parts.length === 0)
                            parts.push('');
                        dd -= 2;
                    }
                }
            }
        } while (didSomething);
        return globParts;
    }
    // second phase: multi-pattern dedupes
    // {
/*/,
/

/} ->

/*/
    // {
/,
/} -> 
/
    // {
/**/,
/} -> 
/**/
    //
    // {
/**/,
/**/

/} ->

/**/
    // ^-- not valid because ** doens't follow symlinks
    secondPhasePreProcess(globParts) {
        for (let i = 0; i < globParts.length - 1; i++) {
            for (let j = i + 1; j < globParts.length; j++) {
                const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
                if (!matched)
                    continue;
                globParts[i] = matched;
                globParts[j] = [];
            }
        }
        return globParts.filter(gs => gs.length);
    }
    partsMatch(a, b, emptyGSMatch = false) {
        let ai = 0;
        let bi = 0;
        let result = [];
        let which = '';
        while (ai < a.length && bi < b.length) {
            if (a[ai] === b[bi]) {
                result.push(which === 'b' ? b[bi] : a[ai]);
                ai++;
                bi++;
            }
            else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
                result.push(a[ai]);
                ai++;
            }
            else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
                result.push(b[bi]);
                bi++;
            }
            else if (a[ai] === '*' &&
                b[bi] &&
                (this.options.dot || !b[bi].startsWith('.')) &&
                b[bi] !== '**') {
                if (which === 'b')
                    return false;
                which = 'a';
                result.push(a[ai]);
                ai++;
                bi++;
            }
            else if (b[bi] === '*' &&
                a[ai] &&
                (this.options.dot || !a[ai].startsWith('.')) &&
                a[ai] !== '**') {
                if (which === 'a')
                    return false;
                which = 'b';
                result.push(b[bi]);
                ai++;
                bi++;
            }
            else {
                return false;
            }
        }
        // if we fall out of the loop, it means they two are identical
        // as long as their lengths match
        return a.length === b.length && result;
    }
    parseNegate() {
        if (this.nonegate)
            return;
        const pattern = this.pattern;
        let negate = false;
        let negateOffset = 0;
        for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
            negate = !negate;
            negateOffset++;
        }
        if (negateOffset)
            this.pattern = pattern.slice(negateOffset);
        this.negate = negate;
    }
    // set partial to true to test if, for example,
    // "/a/b" matches the start of "/*/b/*/d"
    // Partial means, if you run out of file before you run
    // out of pattern, then that's fine, as long as all
    // the parts match.
    matchOne(file, pattern, partial = false) {
        const options = this.options;
        // UNC paths like //?/X:/... can match X:/... and vice versa
        // Drive letters in absolute drive or unc paths are always compared
        // case-insensitively.
        if (this.isWindows) {
            const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
            const fileUNC = !fileDrive &&
                file[0] === '' &&
                file[1] === '' &&
                file[2] === '?' &&
                /^[a-z]:$/i.test(file[3]);
            const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
            const patternUNC = !patternDrive &&
                pattern[0] === '' &&
                pattern[1] === '' &&
                pattern[2] === '?' &&
                typeof pattern[3] === 'string' &&
                /^[a-z]:$/i.test(pattern[3]);
            const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined;
            const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined;
            if (typeof fdi === 'number' && typeof pdi === 'number') {
                const [fd, pd] = [file[fdi], pattern[pdi]];
                if (fd.toLowerCase() === pd.toLowerCase()) {
                    pattern[pdi] = fd;
                    if (pdi > fdi) {
                        pattern = pattern.slice(pdi);
                    }
                    else if (fdi > pdi) {
                        file = file.slice(fdi);
                    }
                }
            }
        }
        // resolve and reduce . and .. portions in the file as well.
        // dont' need to do the second phase, because it's only one string[]
        const { optimizationLevel = 1 } = this.options;
        if (optimizationLevel >= 2) {
            file = this.levelTwoFileOptimize(file);
        }
        this.debug('matchOne', this, { file, pattern });
        this.debug('matchOne', file.length, pattern.length);
        for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
            this.debug('matchOne loop');
            var p = pattern[pi];
            var f = file[fi];
            this.debug(pattern, p, f);
            // should be impossible.
            // some invalid regexp stuff in the set.
            /* c8 ignore start */
            if (p === false) {
                return false;
            }
            /* c8 ignore stop */
            if (p === GLOBSTAR) {
                this.debug('GLOBSTAR', [pattern, p, f]);
                // "**"
                // a/**/b/**/c would match the following:
                // a/b/x/y/z/c
                // a/x/y/z/b/c
                // a/b/x/b/x/c
                // a/b/c
                // To do this, take the rest of the pattern after
                // the **, and see if it would match the file remainder.
                // If so, return success.
                // If not, the ** "swallows" a segment, and try again.
                // This is recursively awful.
                //
                // a/**/b/**/c matching a/b/x/y/z/c
                // - a matches a
                // - doublestar
                //   - matchOne(b/x/y/z/c, b/**/c)
                //     - b matches b
                //     - doublestar
                //       - matchOne(x/y/z/c, c) -> no
                //       - matchOne(y/z/c, c) -> no
                //       - matchOne(z/c, c) -> no
                //       - matchOne(c, c) yes, hit
                var fr = fi;
                var pr = pi + 1;
                if (pr === pl) {
                    this.debug('** at the end');
                    // a ** at the end will just swallow the rest.
                    // We have found a match.
                    // however, it will not swallow /.x, unless
                    // options.dot is set.
                    // . and .. are *never* matched by **, for explosively
                    // exponential reasons.
                    for (; fi < fl; fi++) {
                        if (file[fi] === '.' ||
                            file[fi] === '..' ||
                            (!options.dot && file[fi].charAt(0) === '.'))
                            return false;
                    }
                    return true;
                }
                // ok, let's see if we can swallow whatever we can.
                while (fr < fl) {
                    var swallowee = file[fr];
                    this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
                    // XXX remove this slice.  Just pass the start index.
                    if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
                        this.debug('globstar found match!', fr, fl, swallowee);
                        // found a match.
                        return true;
                    }
                    else {
                        // can't swallow "." or ".." ever.
                        // can only swallow ".foo" when explicitly asked.
                        if (swallowee === '.' ||
                            swallowee === '..' ||
                            (!options.dot && swallowee.charAt(0) === '.')) {
                            this.debug('dot detected!', file, fr, pattern, pr);
                            break;
                        }
                        // ** swallows a segment, and continue.
                        this.debug('globstar swallow a segment, and continue');
                        fr++;
                    }
                }
                // no match was found.
                // However, in partial mode, we can't say this is necessarily over.
                /* c8 ignore start */
                if (partial) {
                    // ran out of file
                    this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
                    if (fr === fl) {
                        return true;
                    }
                }
                /* c8 ignore stop */
                return false;
            }
            // something other than **
            // non-magic patterns just have to match exactly
            // patterns with magic have been turned into regexps.
            let hit;
            if (typeof p === 'string') {
                hit = f === p;
                this.debug('string match', p, f, hit);
            }
            else {
                hit = p.test(f);
                this.debug('pattern match', p, f, hit);
            }
            if (!hit)
                return false;
        }
        // Note: ending in / means that we'll get a final ""
        // at the end of the pattern.  This can only match a
        // corresponding "" at the end of the file.
        // If the file ends in /, then it can only match a
        // a pattern that ends in /, unless the pattern just
        // doesn't have any more for it. But, a/b/ should *not*
        // match "a/b/*", even though "" matches against the
        // [^/]*? pattern, except in partial mode, where it might
        // simply not be reached yet.
        // However, a/b/ should still satisfy a/*
        // now either we fell off the end of the pattern, or we're done.
        if (fi === fl && pi === pl) {
            // ran out of pattern and filename at the same time.
            // an exact hit!
            return true;
        }
        else if (fi === fl) {
            // ran out of file, but still had pattern left.
            // this is ok if we're doing the match as part of
            // a glob fs traversal.
            return partial;
        }
        else if (pi === pl) {
            // ran out of pattern, still have file left.
            // this is only acceptable if we're on the very last
            // empty segment of a file with a trailing slash.
            // a/* should match a/b/
            return fi === fl - 1 && file[fi] === '';
            /* c8 ignore start */
        }
        else {
            // should be unreachable.
            throw new Error('wtf?');
        }
        /* c8 ignore stop */
    }
    braceExpand() {
        return braceExpand(this.pattern, this.options);
    }
    parse(pattern) {
        assertValidPattern(pattern);
        const options = this.options;
        // shortcuts
        if (pattern === '**')
            return GLOBSTAR;
        if (pattern === '')
            return '';
        // far and away, the most common glob pattern parts are
        // *, *.*, and *.  Add a fast check method for those.
        let m;
        let fastTest = null;
        if ((m = pattern.match(starRE))) {
            fastTest = options.dot ? starTestDot : starTest;
        }
        else if ((m = pattern.match(starDotExtRE))) {
            fastTest = (options.nocase
                ? options.dot
                    ? starDotExtTestNocaseDot
                    : starDotExtTestNocase
                : options.dot
                    ? starDotExtTestDot
                    : starDotExtTest)(m[1]);
        }
        else if ((m = pattern.match(qmarksRE))) {
            fastTest = (options.nocase
                ? options.dot
                    ? qmarksTestNocaseDot
                    : qmarksTestNocase
                : options.dot
                    ? qmarksTestDot
                    : qmarksTest)(m);
        }
        else if ((m = pattern.match(starDotStarRE))) {
            fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
        }
        else if ((m = pattern.match(dotStarRE))) {
            fastTest = dotStarTest;
        }
        const re = AST.fromGlob(pattern, this.options).toMMPattern();
        if (fastTest && typeof re === 'object') {
            // Avoids overriding in frozen environments
            Reflect.defineProperty(re, 'test', { value: fastTest });
        }
        return re;
    }
    makeRe() {
        if (this.regexp || this.regexp === false)
            return this.regexp;
        // at this point, this.set is a 2d array of partial
        // pattern strings, or "**".
        //
        // It's better to use .match().  This function shouldn't
        // be used, really, but it's pretty convenient sometimes,
        // when you just want to work with a regex.
        const set = this.set;
        if (!set.length) {
            this.regexp = false;
            return this.regexp;
        }
        const options = this.options;
        const twoStar = options.noglobstar
            ? star
            : options.dot
                ? twoStarDot
                : twoStarNoDot;
        const flags = new Set(options.nocase ? ['i'] : []);
        // regexpify non-globstar patterns
        // if ** is only item, then we just do one twoStar
        // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
        // if ** is last, append (\/twoStar|) to previous
        // if ** is in the middle, append (\/|\/twoStar\/) to previous
        // then filter out GLOBSTAR symbols
        let re = set
            .map(pattern => {
            const pp = pattern.map(p => {
                if (p instanceof RegExp) {
                    for (const f of p.flags.split(''))
                        flags.add(f);
                }
                return typeof p === 'string'
                    ? regExpEscape(p)
                    : p === GLOBSTAR
                        ? GLOBSTAR
                        : p._src;
            });
            pp.forEach((p, i) => {
                const next = pp[i + 1];
                const prev = pp[i - 1];
                if (p !== GLOBSTAR || prev === GLOBSTAR) {
                    return;
                }
                if (prev === undefined) {
                    if (next !== undefined && next !== GLOBSTAR) {
                        pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
                    }
                    else {
                        pp[i] = twoStar;
                    }
                }
                else if (next === undefined) {
                    pp[i - 1] = prev + '(?:\\/|' + twoStar + ')?';
                }
                else if (next !== GLOBSTAR) {
                    pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
                    pp[i + 1] = GLOBSTAR;
                }
            });
            return pp.filter(p => p !== GLOBSTAR).join('/');
        })
            .join('|');
        // need to wrap in parens if we had more than one thing with |,
        // otherwise only the first will be anchored to ^ and the last to $
        const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
        // must match entire pattern
        // ending in a * or ** will make it less strict.
        re = '^' + open + re + close + '$';
        // can match anything, as long as it's not this.
        if (this.negate)
            re = '^(?!' + re + ').+$';
        try {
            this.regexp = new RegExp(re, [...flags].join(''));
            /* c8 ignore start */
        }
        catch (ex) {
            // should be impossible
            this.regexp = false;
        }
        /* c8 ignore stop */
        return this.regexp;
    }
    slashSplit(p) {
        // if p starts with // on windows, we preserve that
        // so that UNC paths aren't broken.  Otherwise, any number of
        // / characters are coalesced into one, unless
        // preserveMultipleSlashes is set to true.
        if (this.preserveMultipleSlashes) {
            return p.split('/');
        }
        else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
            // add an extra '' for the one we lose
            return ['', ...p.split(/\/+/)];
        }
        else {
            return p.split(/\/+/);
        }
    }
    match(f, partial = this.partial) {
        this.debug('match', f, this.pattern);
        // short-circuit in the case of busted things.
        // comments, etc.
        if (this.comment) {
            return false;
        }
        if (this.empty) {
            return f === '';
        }
        if (f === '/' && partial) {
            return true;
        }
        const options = this.options;
        // windows: need to use /, not \
        if (this.isWindows) {
            f = f.split('\\').join('/');
        }
        // treat the test path as a set of pathparts.
        const ff = this.slashSplit(f);
        this.debug(this.pattern, 'split', ff);
        // just ONE of the pattern sets in this.set needs to match
        // in order for it to be valid.  If negating, then just one
        // match means that we have failed.
        // Either way, return on the first hit.
        const set = this.set;
        this.debug(this.pattern, 'set', set);
        // Find the basename of the path by looking for the last non-empty segment
        let filename = ff[ff.length - 1];
        if (!filename) {
            for (let i = ff.length - 2; !filename && i >= 0; i--) {
                filename = ff[i];
            }
        }
        for (let i = 0; i < set.length; i++) {
            const pattern = set[i];
            let file = ff;
            if (options.matchBase && pattern.length === 1) {
                file = [filename];
            }
            const hit = this.matchOne(file, pattern, partial);
            if (hit) {
                if (options.flipNegate) {
                    return true;
                }
                return !this.negate;
            }
        }
        // didn't get any hits.  this is success if it's a negative
        // pattern, failure otherwise.
        if (options.flipNegate) {
            return false;
        }
        return this.negate;
    }
    static defaults(def) {
        return minimatch.defaults(def).Minimatch;
    }
}
/* c8 ignore start */
export { AST } from './ast.js';
export { escape } from './escape.js';
export { unescape } from './unescape.js';
/* c8 ignore stop */
minimatch.AST = AST;
minimatch.Minimatch = Minimatch;
minimatch.escape = escape;
minimatch.unescape = unescape;
//# sourceMappingURL=index.js.mapPK~\K7
 types.has(c);
// Patterns that get prepended to bind to the start of either the
// entire string, or just a single path portion, to prevent dots
// and/or traversal patterns, when needed.
// Exts don't need the ^ or / bit, because the root binds that already.
const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
const startNoDot = '(?!\\.)';
// characters that indicate a start of pattern needs the "no dots" bit,
// because a dot *might* be matched. ( is not in the list, because in
// the case of a child extglob, it will handle the prevention itself.
const addPatternStart = new Set(['[', '.']);
// cases where traversal is A-OK, no dot prevention needed
const justDots = new Set(['..', '.']);
const reSpecials = new Set('().*{}+?[]^$\\!');
const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
// any single thing other than /
const qmark = '[^/]';
// * => any number of characters
const star = qmark + '*?';
// use + when we need to ensure that *something* matches, because the * is
// the only thing in the path portion.
const starNoEmpty = qmark + '+?';
// remove the \ chars that we added if we end up doing a nonmagic compare
// const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
export class AST {
    type;
    #root;
    #hasMagic;
    #uflag = false;
    #parts = [];
    #parent;
    #parentIndex;
    #negs;
    #filledNegs = false;
    #options;
    #toString;
    // set to true if it's an extglob with no children
    // (which really means one child of '')
    #emptyExt = false;
    constructor(type, parent, options = {}) {
        this.type = type;
        // extglobs are inherently magical
        if (type)
            this.#hasMagic = true;
        this.#parent = parent;
        this.#root = this.#parent ? this.#parent.#root : this;
        this.#options = this.#root === this ? options : this.#root.#options;
        this.#negs = this.#root === this ? [] : this.#root.#negs;
        if (type === '!' && !this.#root.#filledNegs)
            this.#negs.push(this);
        this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
    }
    get hasMagic() {
        /* c8 ignore start */
        if (this.#hasMagic !== undefined)
            return this.#hasMagic;
        /* c8 ignore stop */
        for (const p of this.#parts) {
            if (typeof p === 'string')
                continue;
            if (p.type || p.hasMagic)
                return (this.#hasMagic = true);
        }
        // note: will be undefined until we generate the regexp src and find out
        return this.#hasMagic;
    }
    // reconstructs the pattern
    toString() {
        if (this.#toString !== undefined)
            return this.#toString;
        if (!this.type) {
            return (this.#toString = this.#parts.map(p => String(p)).join(''));
        }
        else {
            return (this.#toString =
                this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')');
        }
    }
    #fillNegs() {
        /* c8 ignore start */
        if (this !== this.#root)
            throw new Error('should only call on root');
        if (this.#filledNegs)
            return this;
        /* c8 ignore stop */
        // call toString() once to fill this out
        this.toString();
        this.#filledNegs = true;
        let n;
        while ((n = this.#negs.pop())) {
            if (n.type !== '!')
                continue;
            // walk up the tree, appending everthing that comes AFTER parentIndex
            let p = n;
            let pp = p.#parent;
            while (pp) {
                for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
                    for (const part of n.#parts) {
                        /* c8 ignore start */
                        if (typeof part === 'string') {
                            throw new Error('string part in extglob AST??');
                        }
                        /* c8 ignore stop */
                        part.copyIn(pp.#parts[i]);
                    }
                }
                p = pp;
                pp = p.#parent;
            }
        }
        return this;
    }
    push(...parts) {
        for (const p of parts) {
            if (p === '')
                continue;
            /* c8 ignore start */
            if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {
                throw new Error('invalid part: ' + p);
            }
            /* c8 ignore stop */
            this.#parts.push(p);
        }
    }
    toJSON() {
        const ret = this.type === null
            ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))
            : [this.type, ...this.#parts.map(p => p.toJSON())];
        if (this.isStart() && !this.type)
            ret.unshift([]);
        if (this.isEnd() &&
            (this === this.#root ||
                (this.#root.#filledNegs && this.#parent?.type === '!'))) {
            ret.push({});
        }
        return ret;
    }
    isStart() {
        if (this.#root === this)
            return true;
        // if (this.type) return !!this.#parent?.isStart()
        if (!this.#parent?.isStart())
            return false;
        if (this.#parentIndex === 0)
            return true;
        // if everything AHEAD of this is a negation, then it's still the "start"
        const p = this.#parent;
        for (let i = 0; i < this.#parentIndex; i++) {
            const pp = p.#parts[i];
            if (!(pp instanceof AST && pp.type === '!')) {
                return false;
            }
        }
        return true;
    }
    isEnd() {
        if (this.#root === this)
            return true;
        if (this.#parent?.type === '!')
            return true;
        if (!this.#parent?.isEnd())
            return false;
        if (!this.type)
            return this.#parent?.isEnd();
        // if not root, it'll always have a parent
        /* c8 ignore start */
        const pl = this.#parent ? this.#parent.#parts.length : 0;
        /* c8 ignore stop */
        return this.#parentIndex === pl - 1;
    }
    copyIn(part) {
        if (typeof part === 'string')
            this.push(part);
        else
            this.push(part.clone(this));
    }
    clone(parent) {
        const c = new AST(this.type, parent);
        for (const p of this.#parts) {
            c.copyIn(p);
        }
        return c;
    }
    static #parseAST(str, ast, pos, opt) {
        let escaping = false;
        let inBrace = false;
        let braceStart = -1;
        let braceNeg = false;
        if (ast.type === null) {
            // outside of a extglob, append until we find a start
            let i = pos;
            let acc = '';
            while (i < str.length) {
                const c = str.charAt(i++);
                // still accumulate escapes at this point, but we do ignore
                // starts that are escaped
                if (escaping || c === '\\') {
                    escaping = !escaping;
                    acc += c;
                    continue;
                }
                if (inBrace) {
                    if (i === braceStart + 1) {
                        if (c === '^' || c === '!') {
                            braceNeg = true;
                        }
                    }
                    else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
                        inBrace = false;
                    }
                    acc += c;
                    continue;
                }
                else if (c === '[') {
                    inBrace = true;
                    braceStart = i;
                    braceNeg = false;
                    acc += c;
                    continue;
                }
                if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {
                    ast.push(acc);
                    acc = '';
                    const ext = new AST(c, ast);
                    i = AST.#parseAST(str, ext, i, opt);
                    ast.push(ext);
                    continue;
                }
                acc += c;
            }
            ast.push(acc);
            return i;
        }
        // some kind of extglob, pos is at the (
        // find the next | or )
        let i = pos + 1;
        let part = new AST(null, ast);
        const parts = [];
        let acc = '';
        while (i < str.length) {
            const c = str.charAt(i++);
            // still accumulate escapes at this point, but we do ignore
            // starts that are escaped
            if (escaping || c === '\\') {
                escaping = !escaping;
                acc += c;
                continue;
            }
            if (inBrace) {
                if (i === braceStart + 1) {
                    if (c === '^' || c === '!') {
                        braceNeg = true;
                    }
                }
                else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
                    inBrace = false;
                }
                acc += c;
                continue;
            }
            else if (c === '[') {
                inBrace = true;
                braceStart = i;
                braceNeg = false;
                acc += c;
                continue;
            }
            if (isExtglobType(c) && str.charAt(i) === '(') {
                part.push(acc);
                acc = '';
                const ext = new AST(c, part);
                part.push(ext);
                i = AST.#parseAST(str, ext, i, opt);
                continue;
            }
            if (c === '|') {
                part.push(acc);
                acc = '';
                parts.push(part);
                part = new AST(null, ast);
                continue;
            }
            if (c === ')') {
                if (acc === '' && ast.#parts.length === 0) {
                    ast.#emptyExt = true;
                }
                part.push(acc);
                acc = '';
                ast.push(...parts, part);
                return i;
            }
            acc += c;
        }
        // unfinished extglob
        // if we got here, it was a malformed extglob! not an extglob, but
        // maybe something else in there.
        ast.type = null;
        ast.#hasMagic = undefined;
        ast.#parts = [str.substring(pos - 1)];
        return i;
    }
    static fromGlob(pattern, options = {}) {
        const ast = new AST(null, undefined, options);
        AST.#parseAST(pattern, ast, 0, options);
        return ast;
    }
    // returns the regular expression if there's magic, or the unescaped
    // string if not.
    toMMPattern() {
        // should only be called on root
        /* c8 ignore start */
        if (this !== this.#root)
            return this.#root.toMMPattern();
        /* c8 ignore stop */
        const glob = this.toString();
        const [re, body, hasMagic, uflag] = this.toRegExpSource();
        // if we're in nocase mode, and not nocaseMagicOnly, then we do
        // still need a regular expression if we have to case-insensitively
        // match capital/lowercase characters.
        const anyMagic = hasMagic ||
            this.#hasMagic ||
            (this.#options.nocase &&
                !this.#options.nocaseMagicOnly &&
                glob.toUpperCase() !== glob.toLowerCase());
        if (!anyMagic) {
            return body;
        }
        const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
        return Object.assign(new RegExp(`^${re}$`, flags), {
            _src: re,
            _glob: glob,
        });
    }
    get options() {
        return this.#options;
    }
    // returns the string match, the regexp source, whether there's magic
    // in the regexp (so a regular expression is required) and whether or
    // not the uflag is needed for the regular expression (for posix classes)
    // TODO: instead of injecting the start/end at this point, just return
    // the BODY of the regexp, along with the start/end portions suitable
    // for binding the start/end in either a joined full-path makeRe context
    // (where we bind to (^|/), or a standalone matchPart context (where
    // we bind to ^, and not /).  Otherwise slashes get duped!
    //
    // In part-matching mode, the start is:
    // - if not isStart: nothing
    // - if traversal possible, but not allowed: ^(?!\.\.?$)
    // - if dots allowed or not possible: ^
    // - if dots possible and not allowed: ^(?!\.)
    // end is:
    // - if not isEnd(): nothing
    // - else: $
    //
    // In full-path matching mode, we put the slash at the START of the
    // pattern, so start is:
    // - if first pattern: same as part-matching mode
    // - if not isStart(): nothing
    // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
    // - if dots allowed or not possible: /
    // - if dots possible and not allowed: /(?!\.)
    // end is:
    // - if last pattern, same as part-matching mode
    // - else nothing
    //
    // Always put the (?:$|/) on negated tails, though, because that has to be
    // there to bind the end of the negated pattern portion, and it's easier to
    // just stick it in now rather than try to inject it later in the middle of
    // the pattern.
    //
    // We can just always return the same end, and leave it up to the caller
    // to know whether it's going to be used joined or in parts.
    // And, if the start is adjusted slightly, can do the same there:
    // - if not isStart: nothing
    // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
    // - if dots allowed or not possible: (?:/|^)
    // - if dots possible and not allowed: (?:/|^)(?!\.)
    //
    // But it's better to have a simpler binding without a conditional, for
    // performance, so probably better to return both start options.
    //
    // Then the caller just ignores the end if it's not the first pattern,
    // and the start always gets applied.
    //
    // But that's always going to be $ if it's the ending pattern, or nothing,
    // so the caller can just attach $ at the end of the pattern when building.
    //
    // So the todo is:
    // - better detect what kind of start is needed
    // - return both flavors of starting pattern
    // - attach $ at the end of the pattern when creating the actual RegExp
    //
    // Ah, but wait, no, that all only applies to the root when the first pattern
    // is not an extglob. If the first pattern IS an extglob, then we need all
    // that dot prevention biz to live in the extglob portions, because eg
    // +(*|.x*) can match .xy but not .yx.
    //
    // So, return the two flavors if it's #root and the first child is not an
    // AST, otherwise leave it to the child AST to handle it, and there,
    // use the (?:^|/) style of start binding.
    //
    // Even simplified further:
    // - Since the start for a join is eg /(?!\.) and the start for a part
    // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
    // or start or whatever) and prepend ^ or / at the Regexp construction.
    toRegExpSource(allowDot) {
        const dot = allowDot ?? !!this.#options.dot;
        if (this.#root === this)
            this.#fillNegs();
        if (!this.type) {
            const noEmpty = this.isStart() && this.isEnd();
            const src = this.#parts
                .map(p => {
                const [re, _, hasMagic, uflag] = typeof p === 'string'
                    ? AST.#parseGlob(p, this.#hasMagic, noEmpty)
                    : p.toRegExpSource(allowDot);
                this.#hasMagic = this.#hasMagic || hasMagic;
                this.#uflag = this.#uflag || uflag;
                return re;
            })
                .join('');
            let start = '';
            if (this.isStart()) {
                if (typeof this.#parts[0] === 'string') {
                    // this is the string that will match the start of the pattern,
                    // so we need to protect against dots and such.
                    // '.' and '..' cannot match unless the pattern is that exactly,
                    // even if it starts with . or dot:true is set.
                    const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
                    if (!dotTravAllowed) {
                        const aps = addPatternStart;
                        // check if we have a possibility of matching . or ..,
                        // and prevent that.
                        const needNoTrav = 
                        // dots are allowed, and the pattern starts with [ or .
                        (dot && aps.has(src.charAt(0))) ||
                            // the pattern starts with \., and then [ or .
                            (src.startsWith('\\.') && aps.has(src.charAt(2))) ||
                            // the pattern starts with \.\., and then [ or .
                            (src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
                        // no need to prevent dots if it can't match a dot, or if a
                        // sub-pattern will be preventing it anyway.
                        const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
                        start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : '';
                    }
                }
            }
            // append the "end of path portion" pattern to negation tails
            let end = '';
            if (this.isEnd() &&
                this.#root.#filledNegs &&
                this.#parent?.type === '!') {
                end = '(?:$|\\/)';
            }
            const final = start + src + end;
            return [
                final,
                unescape(src),
                (this.#hasMagic = !!this.#hasMagic),
                this.#uflag,
            ];
        }
        // We need to calculate the body *twice* if it's a repeat pattern
        // at the start, once in nodot mode, then again in dot mode, so a
        // pattern like *(?) can match 'x.y'
        const repeated = this.type === '*' || this.type === '+';
        // some kind of extglob
        const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
        let body = this.#partsToRegExp(dot);
        if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
            // invalid extglob, has to at least be *something* present, if it's
            // the entire path portion.
            const s = this.toString();
            this.#parts = [s];
            this.type = null;
            this.#hasMagic = undefined;
            return [s, unescape(this.toString()), false, false];
        }
        // XXX abstract out this map method
        let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot
            ? ''
            : this.#partsToRegExp(true);
        if (bodyDotAllowed === body) {
            bodyDotAllowed = '';
        }
        if (bodyDotAllowed) {
            body = `(?:${body})(?:${bodyDotAllowed})*?`;
        }
        // an empty !() is exactly equivalent to a starNoEmpty
        let final = '';
        if (this.type === '!' && this.#emptyExt) {
            final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
        }
        else {
            const close = this.type === '!'
                ? // !() must match something,but !(x) can match ''
                    '))' +
                        (this.isStart() && !dot && !allowDot ? startNoDot : '') +
                        star +
                        ')'
                : this.type === '@'
                    ? ')'
                    : this.type === '?'
                        ? ')?'
                        : this.type === '+' && bodyDotAllowed
                            ? ')'
                            : this.type === '*' && bodyDotAllowed
                                ? `)?`
                                : `)${this.type}`;
            final = start + body + close;
        }
        return [
            final,
            unescape(body),
            (this.#hasMagic = !!this.#hasMagic),
            this.#uflag,
        ];
    }
    #partsToRegExp(dot) {
        return this.#parts
            .map(p => {
            // extglob ASTs should only contain parent ASTs
            /* c8 ignore start */
            if (typeof p === 'string') {
                throw new Error('string type in extglob ast??');
            }
            /* c8 ignore stop */
            // can ignore hasMagic, because extglobs are already always magic
            const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
            this.#uflag = this.#uflag || uflag;
            return re;
        })
            .filter(p => !(this.isStart() && this.isEnd()) || !!p)
            .join('|');
    }
    static #parseGlob(glob, hasMagic, noEmpty = false) {
        let escaping = false;
        let re = '';
        let uflag = false;
        for (let i = 0; i < glob.length; i++) {
            const c = glob.charAt(i);
            if (escaping) {
                escaping = false;
                re += (reSpecials.has(c) ? '\\' : '') + c;
                continue;
            }
            if (c === '\\') {
                if (i === glob.length - 1) {
                    re += '\\\\';
                }
                else {
                    escaping = true;
                }
                continue;
            }
            if (c === '[') {
                const [src, needUflag, consumed, magic] = parseClass(glob, i);
                if (consumed) {
                    re += src;
                    uflag = uflag || needUflag;
                    i += consumed - 1;
                    hasMagic = hasMagic || magic;
                    continue;
                }
            }
            if (c === '*') {
                if (noEmpty && glob === '*')
                    re += starNoEmpty;
                else
                    re += star;
                hasMagic = true;
                continue;
            }
            if (c === '?') {
                re += qmark;
                hasMagic = true;
                continue;
            }
            re += regExpEscape(c);
        }
        return [re, unescape(glob), !!hasMagic, uflag];
    }
}
//# sourceMappingURL=ast.js.mapPK~\1
nopt/package.jsonnu[{
  "_id": "nopt@7.2.1",
  "_inBundle": true,
  "_location": "/npm/nopt",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm",
    "/npm/@npmcli/arborist",
    "/npm/@npmcli/config",
    "/npm/node-gyp"
  ],
  "author": {
    "name": "GitHub Inc."
  },
  "bin": {
    "nopt": "bin/nopt.js"
  },
  "bugs": {
    "url": "https://github.com/npm/nopt/issues"
  },
  "dependencies": {
    "abbrev": "^2.0.0"
  },
  "description": "Option parsing for Node, supporting types, shorthands, etc. Used by npm.",
  "devDependencies": {
    "@npmcli/eslint-config": "^4.0.0",
    "@npmcli/template-oss": "4.22.0",
    "tap": "^16.3.0"
  },
  "engines": {
    "node": "^14.17.0 || ^16.13.0 || >=18.0.0"
  },
  "files": [
    "bin/",
    "lib/"
  ],
  "homepage": "https://github.com/npm/nopt#readme",
  "license": "ISC",
  "main": "lib/nopt.js",
  "name": "nopt",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/nopt.git"
  },
  "scripts": {
    "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"",
    "lintfix": "npm run lint -- --fix",
    "postlint": "template-oss-check",
    "posttest": "npm run lint",
    "snap": "tap",
    "template-oss-apply": "template-oss-apply --force",
    "test": "tap"
  },
  "tap": {
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "windowsCI": false,
    "version": "4.22.0",
    "publish": true
  },
  "version": "7.2.1"
}
PK~\< nopt/lib/nopt.jsnu[const lib = require('./nopt-lib')
const defaultTypeDefs = require('./type-defs')

// This is the version of nopt's API that requires setting typeDefs and invalidHandler
// on the required `nopt` object since it is a singleton. To not do a breaking change
// an API that requires all options be passed in is located in `nopt-lib.js` and
// exported here as lib.
// TODO(breaking): make API only work in non-singleton mode

module.exports = exports = nopt
exports.clean = clean
exports.typeDefs = defaultTypeDefs
exports.lib = lib

function nopt (types, shorthands, args = process.argv, slice = 2) {
  return lib.nopt(args.slice(slice), {
    types: types || {},
    shorthands: shorthands || {},
    typeDefs: exports.typeDefs,
    invalidHandler: exports.invalidHandler,
  })
}

function clean (data, types, typeDefs = exports.typeDefs) {
  return lib.clean(data, {
    types: types || {},
    typeDefs,
    invalidHandler: exports.invalidHandler,
  })
}
PK~\(nopt/lib/type-defs.jsnu[const url = require('url')
const path = require('path')
const Stream = require('stream').Stream
const os = require('os')
const debug = require('./debug')

function validateString (data, k, val) {
  data[k] = String(val)
}

function validatePath (data, k, val) {
  if (val === true) {
    return false
  }
  if (val === null) {
    return true
  }

  val = String(val)

  const isWin = process.platform === 'win32'
  const homePattern = isWin ? /^~(\/|\\)/ : /^~\//
  const home = os.homedir()

  if (home && val.match(homePattern)) {
    data[k] = path.resolve(home, val.slice(2))
  } else {
    data[k] = path.resolve(val)
  }
  return true
}

function validateNumber (data, k, val) {
  debug('validate Number %j %j %j', k, val, isNaN(val))
  if (isNaN(val)) {
    return false
  }
  data[k] = +val
}

function validateDate (data, k, val) {
  const s = Date.parse(val)
  debug('validate Date %j %j %j', k, val, s)
  if (isNaN(s)) {
    return false
  }
  data[k] = new Date(val)
}

function validateBoolean (data, k, val) {
  if (typeof val === 'string') {
    if (!isNaN(val)) {
      val = !!(+val)
    } else if (val === 'null' || val === 'false') {
      val = false
    } else {
      val = true
    }
  } else {
    val = !!val
  }
  data[k] = val
}

function validateUrl (data, k, val) {
  // Changing this would be a breaking change in the npm cli
  /* eslint-disable-next-line node/no-deprecated-api */
  val = url.parse(String(val))
  if (!val.host) {
    return false
  }
  data[k] = val.href
}

function validateStream (data, k, val) {
  if (!(val instanceof Stream)) {
    return false
  }
  data[k] = val
}

module.exports = {
  String: { type: String, validate: validateString },
  Boolean: { type: Boolean, validate: validateBoolean },
  url: { type: url, validate: validateUrl },
  Number: { type: Number, validate: validateNumber },
  path: { type: path, validate: validatePath },
  Stream: { type: Stream, validate: validateStream },
  Date: { type: Date, validate: validateDate },
  Array: { type: Array },
}
PK~\k-22nopt/lib/nopt-lib.jsnu[const abbrev = require('abbrev')
const debug = require('./debug')
const defaultTypeDefs = require('./type-defs')

const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k)

const getType = (k, { types, dynamicTypes }) => {
  let hasType = hasOwn(types, k)
  let type = types[k]
  if (!hasType && typeof dynamicTypes === 'function') {
    const matchedType = dynamicTypes(k)
    if (matchedType !== undefined) {
      type = matchedType
      hasType = true
    }
  }
  return [hasType, type]
}

const isTypeDef = (type, def) => def && type === def
const hasTypeDef = (type, def) => def && type.indexOf(def) !== -1
const doesNotHaveTypeDef = (type, def) => def && !hasTypeDef(type, def)

function nopt (args, {
  types,
  shorthands,
  typeDefs,
  invalidHandler,
  typeDefault,
  dynamicTypes,
} = {}) {
  debug(types, shorthands, args, typeDefs)

  const data = {}
  const argv = {
    remain: [],
    cooked: args,
    original: args.slice(0),
  }

  parse(args, data, argv.remain, { typeDefs, types, dynamicTypes, shorthands })

  // now data is full
  clean(data, { types, dynamicTypes, typeDefs, invalidHandler, typeDefault })
  data.argv = argv

  Object.defineProperty(data.argv, 'toString', {
    value: function () {
      return this.original.map(JSON.stringify).join(' ')
    },
    enumerable: false,
  })

  return data
}

function clean (data, {
  types = {},
  typeDefs = {},
  dynamicTypes,
  invalidHandler,
  typeDefault,
} = {}) {
  const StringType = typeDefs.String?.type
  const NumberType = typeDefs.Number?.type
  const ArrayType = typeDefs.Array?.type
  const BooleanType = typeDefs.Boolean?.type
  const DateType = typeDefs.Date?.type

  const hasTypeDefault = typeof typeDefault !== 'undefined'
  if (!hasTypeDefault) {
    typeDefault = [false, true, null]
    if (StringType) {
      typeDefault.push(StringType)
    }
    if (ArrayType) {
      typeDefault.push(ArrayType)
    }
  }

  const remove = {}

  Object.keys(data).forEach((k) => {
    if (k === 'argv') {
      return
    }
    let val = data[k]
    debug('val=%j', val)
    const isArray = Array.isArray(val)
    let [hasType, rawType] = getType(k, { types, dynamicTypes })
    let type = rawType
    if (!isArray) {
      val = [val]
    }
    if (!type) {
      type = typeDefault
    }
    if (isTypeDef(type, ArrayType)) {
      type = typeDefault.concat(ArrayType)
    }
    if (!Array.isArray(type)) {
      type = [type]
    }

    debug('val=%j', val)
    debug('types=', type)
    val = val.map((v) => {
      // if it's an unknown value, then parse false/true/null/numbers/dates
      if (typeof v === 'string') {
        debug('string %j', v)
        v = v.trim()
        if ((v === 'null' && ~type.indexOf(null))
            || (v === 'true' &&
               (~type.indexOf(true) || hasTypeDef(type, BooleanType)))
            || (v === 'false' &&
               (~type.indexOf(false) || hasTypeDef(type, BooleanType)))) {
          v = JSON.parse(v)
          debug('jsonable %j', v)
        } else if (hasTypeDef(type, NumberType) && !isNaN(v)) {
          debug('convert to number', v)
          v = +v
        } else if (hasTypeDef(type, DateType) && !isNaN(Date.parse(v))) {
          debug('convert to date', v)
          v = new Date(v)
        }
      }

      if (!hasType) {
        if (!hasTypeDefault) {
          return v
        }
        // if the default type has been passed in then we want to validate the
        // unknown data key instead of bailing out earlier. we also set the raw
        // type which is passed to the invalid handler so that it can be
        // determined if during validation if it is unknown vs invalid
        rawType = typeDefault
      }

      // allow `--no-blah` to set 'blah' to null if null is allowed
      if (v === false && ~type.indexOf(null) &&
          !(~type.indexOf(false) || hasTypeDef(type, BooleanType))) {
        v = null
      }

      const d = {}
      d[k] = v
      debug('prevalidated val', d, v, rawType)
      if (!validate(d, k, v, rawType, { typeDefs })) {
        if (invalidHandler) {
          invalidHandler(k, v, rawType, data)
        } else if (invalidHandler !== false) {
          debug('invalid: ' + k + '=' + v, rawType)
        }
        return remove
      }
      debug('validated v', d, v, rawType)
      return d[k]
    }).filter((v) => v !== remove)

    // if we allow Array specifically, then an empty array is how we
    // express 'no value here', not null.  Allow it.
    if (!val.length && doesNotHaveTypeDef(type, ArrayType)) {
      debug('VAL HAS NO LENGTH, DELETE IT', val, k, type.indexOf(ArrayType))
      delete data[k]
    } else if (isArray) {
      debug(isArray, data[k], val)
      data[k] = val
    } else {
      data[k] = val[0]
    }

    debug('k=%s val=%j', k, val, data[k])
  })
}

function validate (data, k, val, type, { typeDefs } = {}) {
  const ArrayType = typeDefs?.Array?.type
  // arrays are lists of types.
  if (Array.isArray(type)) {
    for (let i = 0, l = type.length; i < l; i++) {
      if (isTypeDef(type[i], ArrayType)) {
        continue
      }
      if (validate(data, k, val, type[i], { typeDefs })) {
        return true
      }
    }
    delete data[k]
    return false
  }

  // an array of anything?
  if (isTypeDef(type, ArrayType)) {
    return true
  }

  // Original comment:
  // NaN is poisonous.  Means that something is not allowed.
  // New comment: Changing this to an isNaN check breaks a lot of tests.
  // Something is being assumed here that is not actually what happens in
  // practice.  Fixing it is outside the scope of getting linting to pass in
  // this repo. Leaving as-is for now.
  /* eslint-disable-next-line no-self-compare */
  if (type !== type) {
    debug('Poison NaN', k, val, type)
    delete data[k]
    return false
  }

  // explicit list of values
  if (val === type) {
    debug('Explicitly allowed %j', val)
    data[k] = val
    return true
  }

  // now go through the list of typeDefs, validate against each one.
  let ok = false
  const types = Object.keys(typeDefs)
  for (let i = 0, l = types.length; i < l; i++) {
    debug('test type %j %j %j', k, val, types[i])
    const t = typeDefs[types[i]]
    if (t && (
      (type && type.name && t.type && t.type.name) ?
        (type.name === t.type.name) :
        (type === t.type)
    )) {
      const d = {}
      ok = t.validate(d, k, val) !== false
      val = d[k]
      if (ok) {
        data[k] = val
        break
      }
    }
  }
  debug('OK? %j (%j %j %j)', ok, k, val, types[types.length - 1])

  if (!ok) {
    delete data[k]
  }
  return ok
}

function parse (args, data, remain, {
  types = {},
  typeDefs = {},
  shorthands = {},
  dynamicTypes,
} = {}) {
  const StringType = typeDefs.String?.type
  const NumberType = typeDefs.Number?.type
  const ArrayType = typeDefs.Array?.type
  const BooleanType = typeDefs.Boolean?.type

  debug('parse', args, data, remain)

  const abbrevs = abbrev(Object.keys(types))
  debug('abbrevs=%j', abbrevs)
  const shortAbbr = abbrev(Object.keys(shorthands))

  for (let i = 0; i < args.length; i++) {
    let arg = args[i]
    debug('arg', arg)

    if (arg.match(/^-{2,}$/)) {
      // done with keys.
      // the rest are args.
      remain.push.apply(remain, args.slice(i + 1))
      args[i] = '--'
      break
    }
    let hadEq = false
    if (arg.charAt(0) === '-' && arg.length > 1) {
      const at = arg.indexOf('=')
      if (at > -1) {
        hadEq = true
        const v = arg.slice(at + 1)
        arg = arg.slice(0, at)
        args.splice(i, 1, arg, v)
      }

      // see if it's a shorthand
      // if so, splice and back up to re-parse it.
      const shRes = resolveShort(arg, shortAbbr, abbrevs, { shorthands })
      debug('arg=%j shRes=%j', arg, shRes)
      if (shRes) {
        args.splice.apply(args, [i, 1].concat(shRes))
        if (arg !== shRes[0]) {
          i--
          continue
        }
      }
      arg = arg.replace(/^-+/, '')
      let no = null
      while (arg.toLowerCase().indexOf('no-') === 0) {
        no = !no
        arg = arg.slice(3)
      }

      if (abbrevs[arg]) {
        arg = abbrevs[arg]
      }

      let [hasType, argType] = getType(arg, { types, dynamicTypes })
      let isTypeArray = Array.isArray(argType)
      if (isTypeArray && argType.length === 1) {
        isTypeArray = false
        argType = argType[0]
      }

      let isArray = isTypeDef(argType, ArrayType) ||
        isTypeArray && hasTypeDef(argType, ArrayType)

      // allow unknown things to be arrays if specified multiple times.
      if (!hasType && hasOwn(data, arg)) {
        if (!Array.isArray(data[arg])) {
          data[arg] = [data[arg]]
        }
        isArray = true
      }

      let val
      let la = args[i + 1]

      const isBool = typeof no === 'boolean' ||
        isTypeDef(argType, BooleanType) ||
        isTypeArray && hasTypeDef(argType, BooleanType) ||
        (typeof argType === 'undefined' && !hadEq) ||
        (la === 'false' &&
         (argType === null ||
          isTypeArray && ~argType.indexOf(null)))

      if (isBool) {
        // just set and move along
        val = !no
        // however, also support --bool true or --bool false
        if (la === 'true' || la === 'false') {
          val = JSON.parse(la)
          la = null
          if (no) {
            val = !val
          }
          i++
        }

        // also support "foo":[Boolean, "bar"] and "--foo bar"
        if (isTypeArray && la) {
          if (~argType.indexOf(la)) {
            // an explicit type
            val = la
            i++
          } else if (la === 'null' && ~argType.indexOf(null)) {
            // null allowed
            val = null
            i++
          } else if (!la.match(/^-{2,}[^-]/) &&
                      !isNaN(la) &&
                      hasTypeDef(argType, NumberType)) {
            // number
            val = +la
            i++
          } else if (!la.match(/^-[^-]/) && hasTypeDef(argType, StringType)) {
            // string
            val = la
            i++
          }
        }

        if (isArray) {
          (data[arg] = data[arg] || []).push(val)
        } else {
          data[arg] = val
        }

        continue
      }

      if (isTypeDef(argType, StringType)) {
        if (la === undefined) {
          la = ''
        } else if (la.match(/^-{1,2}[^-]+/)) {
          la = ''
          i--
        }
      }

      if (la && la.match(/^-{2,}$/)) {
        la = undefined
        i--
      }

      val = la === undefined ? true : la
      if (isArray) {
        (data[arg] = data[arg] || []).push(val)
      } else {
        data[arg] = val
      }

      i++
      continue
    }
    remain.push(arg)
  }
}

const SINGLES = Symbol('singles')
const singleCharacters = (arg, shorthands) => {
  let singles = shorthands[SINGLES]
  if (!singles) {
    singles = Object.keys(shorthands).filter((s) => s.length === 1).reduce((l, r) => {
      l[r] = true
      return l
    }, {})
    shorthands[SINGLES] = singles
    debug('shorthand singles', singles)
  }
  const chrs = arg.split('').filter((c) => singles[c])
  return chrs.join('') === arg ? chrs : null
}

function resolveShort (arg, ...rest) {
  const { types = {}, shorthands = {} } = rest.length ? rest.pop() : {}
  const shortAbbr = rest[0] ?? abbrev(Object.keys(shorthands))
  const abbrevs = rest[1] ?? abbrev(Object.keys(types))

  // handle single-char shorthands glommed together, like
  // npm ls -glp, but only if there is one dash, and only if
  // all of the chars are single-char shorthands, and it's
  // not a match to some other abbrev.
  arg = arg.replace(/^-+/, '')

  // if it's an exact known option, then don't go any further
  if (abbrevs[arg] === arg) {
    return null
  }

  // if it's an exact known shortopt, same deal
  if (shorthands[arg]) {
    // make it an array, if it's a list of words
    if (shorthands[arg] && !Array.isArray(shorthands[arg])) {
      shorthands[arg] = shorthands[arg].split(/\s+/)
    }

    return shorthands[arg]
  }

  // first check to see if this arg is a set of single-char shorthands
  const chrs = singleCharacters(arg, shorthands)
  if (chrs) {
    return chrs.map((c) => shorthands[c]).reduce((l, r) => l.concat(r), [])
  }

  // if it's an arg abbrev, and not a literal shorthand, then prefer the arg
  if (abbrevs[arg] && !shorthands[arg]) {
    return null
  }

  // if it's an abbr for a shorthand, then use that
  if (shortAbbr[arg]) {
    arg = shortAbbr[arg]
  }

  // make it an array, if it's a list of words
  if (shorthands[arg] && !Array.isArray(shorthands[arg])) {
    shorthands[arg] = shorthands[arg].split(/\s+/)
  }

  return shorthands[arg]
}

module.exports = {
  nopt,
  clean,
  parse,
  validate,
  resolveShort,
  typeDefs: defaultTypeDefs,
}
PK~\Hnopt/lib/debug.jsnu[/* istanbul ignore next */
module.exports = process.env.DEBUG_NOPT || process.env.NOPT_DEBUG
  // eslint-disable-next-line no-console
  ? (...a) => console.error(...a)
  : () => {}
PK~\aGWnopt/LICENSEnu[The ISC License

Copyright (c) Isaac Z. Schlueter and Contributors

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
PK~\;Bnopt/bin/nopt.jsnu[#!/usr/bin/env node
const nopt = require('../lib/nopt')
const path = require('path')
console.log('parsed', nopt({
  num: Number,
  bool: Boolean,
  help: Boolean,
  list: Array,
  'num-list': [Number, Array],
  'str-list': [String, Array],
  'bool-list': [Boolean, Array],
  str: String,
  clear: Boolean,
  config: Boolean,
  length: Number,
  file: path,
}, {
  s: ['--str', 'astring'],
  b: ['--bool'],
  nb: ['--no-bool'],
  tft: ['--bool-list', '--no-bool-list', '--bool-list', 'true'],
  '?': ['--help'],
  h: ['--help'],
  H: ['--help'],
  n: ['--num', '125'],
  c: ['--config'],
  l: ['--length'],
  f: ['--file'],
}, process.argv, 2))
PK~\snopt/README.mdnu[If you want to write an option parser, and have it be good, there are
two ways to do it.  The Right Way, and the Wrong Way.

The Wrong Way is to sit down and write an option parser.  We've all done
that.

The Right Way is to write some complex configurable program with so many
options that you hit the limit of your frustration just trying to
manage them all, and defer it with duct-tape solutions until you see
exactly to the core of the problem, and finally snap and write an
awesome option parser.

If you want to write an option parser, don't write an option parser.
Write a package manager, or a source control system, or a service
restarter, or an operating system.  You probably won't end up with a
good one of those, but if you don't give up, and you are relentless and
diligent enough in your procrastination, you may just end up with a very
nice option parser.

## USAGE

```javascript
// my-program.js
var nopt = require("nopt")
  , Stream = require("stream").Stream
  , path = require("path")
  , knownOpts = { "foo" : [String, null]
                , "bar" : [Stream, Number]
                , "baz" : path
                , "bloo" : [ "big", "medium", "small" ]
                , "flag" : Boolean
                , "pick" : Boolean
                , "many1" : [String, Array]
                , "many2" : [path, Array]
                }
  , shortHands = { "foofoo" : ["--foo", "Mr. Foo"]
                 , "b7" : ["--bar", "7"]
                 , "m" : ["--bloo", "medium"]
                 , "p" : ["--pick"]
                 , "f" : ["--flag"]
                 }
             // everything is optional.
             // knownOpts and shorthands default to {}
             // arg list defaults to process.argv
             // slice defaults to 2
  , parsed = nopt(knownOpts, shortHands, process.argv, 2)
console.log(parsed)
```

This would give you support for any of the following:

```console
$ node my-program.js --foo "blerp" --no-flag
{ "foo" : "blerp", "flag" : false }

$ node my-program.js ---bar 7 --foo "Mr. Hand" --flag
{ bar: 7, foo: "Mr. Hand", flag: true }

$ node my-program.js --foo "blerp" -f -----p
{ foo: "blerp", flag: true, pick: true }

$ node my-program.js -fp --foofoo
{ foo: "Mr. Foo", flag: true, pick: true }

$ node my-program.js --foofoo -- -fp  # -- stops the flag parsing.
{ foo: "Mr. Foo", argv: { remain: ["-fp"] } }

$ node my-program.js --blatzk -fp # unknown opts are ok.
{ blatzk: true, flag: true, pick: true }

$ node my-program.js --blatzk=1000 -fp # but you need to use = if they have a value
{ blatzk: 1000, flag: true, pick: true }

$ node my-program.js --no-blatzk -fp # unless they start with "no-"
{ blatzk: false, flag: true, pick: true }

$ node my-program.js --baz b/a/z # known paths are resolved.
{ baz: "/Users/isaacs/b/a/z" }

# if Array is one of the types, then it can take many
# values, and will always be an array.  The other types provided
# specify what types are allowed in the list.

$ node my-program.js --many1 5 --many1 null --many1 foo
{ many1: ["5", "null", "foo"] }

$ node my-program.js --many2 foo --many2 bar
{ many2: ["/path/to/foo", "path/to/bar"] }
```

Read the tests at the bottom of `lib/nopt.js` for more examples of
what this puppy can do.

## Types

The following types are supported, and defined on `nopt.typeDefs`

* String: A normal string.  No parsing is done.
* path: A file system path.  Gets resolved against cwd if not absolute.
* url: A url.  If it doesn't parse, it isn't accepted.
* Number: Must be numeric.
* Date: Must parse as a date. If it does, and `Date` is one of the options,
  then it will return a Date object, not a string.
* Boolean: Must be either `true` or `false`.  If an option is a boolean,
  then it does not need a value, and its presence will imply `true` as
  the value.  To negate boolean flags, do `--no-whatever` or `--whatever
  false`
* NaN: Means that the option is strictly not allowed.  Any value will
  fail.
* Stream: An object matching the "Stream" class in node.  Valuable
  for use when validating programmatically.  (npm uses this to let you
  supply any WriteStream on the `outfd` and `logfd` config options.)
* Array: If `Array` is specified as one of the types, then the value
  will be parsed as a list of options.  This means that multiple values
  can be specified, and that the value will always be an array.

If a type is an array of values not on this list, then those are
considered valid values.  For instance, in the example above, the
`--bloo` option can only be one of `"big"`, `"medium"`, or `"small"`,
and any other value will be rejected.

When parsing unknown fields, `"true"`, `"false"`, and `"null"` will be
interpreted as their JavaScript equivalents.

You can also mix types and values, or multiple types, in a list.  For
instance `{ blah: [Number, null] }` would allow a value to be set to
either a Number or null.  When types are ordered, this implies a
preference, and the first type that can be used to properly interpret
the value will be used.

To define a new type, add it to `nopt.typeDefs`.  Each item in that
hash is an object with a `type` member and a `validate` method.  The
`type` member is an object that matches what goes in the type list.  The
`validate` method is a function that gets called with `validate(data,
key, val)`.  Validate methods should assign `data[key]` to the valid
value of `val` if it can be handled properly, or return boolean
`false` if it cannot.

You can also call `nopt.clean(data, types, typeDefs)` to clean up a
config object and remove its invalid properties.

## Error Handling

By default, nopt outputs a warning to standard error when invalid values for
known options are found.  You can change this behavior by assigning a method
to `nopt.invalidHandler`.  This method will be called with
the offending `nopt.invalidHandler(key, val, types)`.

If no `nopt.invalidHandler` is assigned, then it will console.error
its whining.  If it is assigned to boolean `false` then the warning is
suppressed.

## Abbreviations

Yes, they are supported.  If you define options like this:

```javascript
{ "foolhardyelephants" : Boolean
, "pileofmonkeys" : Boolean }
```

Then this will work:

```bash
node program.js --foolhar --pil
node program.js --no-f --pileofmon
# etc.
```

## Shorthands

Shorthands are a hash of shorter option names to a snippet of args that
they expand to.

If multiple one-character shorthands are all combined, and the
combination does not unambiguously match any other option or shorthand,
then they will be broken up into their constituent parts.  For example:

```json
{ "s" : ["--loglevel", "silent"]
, "g" : "--global"
, "f" : "--force"
, "p" : "--parseable"
, "l" : "--long"
}
```

```bash
npm ls -sgflp
# just like doing this:
npm ls --loglevel silent --global --force --long --parseable
```

## The Rest of the args

The config object returned by nopt is given a special member called
`argv`, which is an object with the following fields:

* `remain`: The remaining args after all the parsing has occurred.
* `original`: The args as they originally appeared.
* `cooked`: The args after flags and shorthands are expanded.

## Slicing

Node programs are called with more or less the exact argv as it appears
in C land, after the v8 and node-specific options have been plucked off.
As such, `argv[0]` is always `node` and `argv[1]` is always the
JavaScript program being run.

That's usually not very useful to you.  So they're sliced off by
default.  If you want them, then you can pass in `0` as the last
argument, or any other number that you'd like to slice off the start of
the list.
PK~\Z%graceful-fs/clone.jsnu['use strict'

module.exports = clone

var getPrototypeOf = Object.getPrototypeOf || function (obj) {
  return obj.__proto__
}

function clone (obj) {
  if (obj === null || typeof obj !== 'object')
    return obj

  if (obj instanceof Object)
    var copy = { __proto__: getPrototypeOf(obj) }
  else
    var copy = Object.create(null)

  Object.getOwnPropertyNames(obj).forEach(function (key) {
    Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key))
  })

  return copy
}
PK~\KKgraceful-fs/package.jsonnu[{
  "_id": "graceful-fs@4.2.11",
  "_inBundle": true,
  "_location": "/npm/graceful-fs",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm",
    "/npm/node-gyp"
  ],
  "bugs": {
    "url": "https://github.com/isaacs/node-graceful-fs/issues"
  },
  "description": "A drop-in replacement for fs, making various improvements.",
  "devDependencies": {
    "import-fresh": "^2.0.0",
    "mkdirp": "^0.5.0",
    "rimraf": "^2.2.8",
    "tap": "^16.3.4"
  },
  "directories": {
    "test": "test"
  },
  "files": [
    "fs.js",
    "graceful-fs.js",
    "legacy-streams.js",
    "polyfills.js",
    "clone.js"
  ],
  "homepage": "https://github.com/isaacs/node-graceful-fs#readme",
  "keywords": [
    "fs",
    "module",
    "reading",
    "retry",
    "retries",
    "queue",
    "error",
    "errors",
    "handling",
    "EMFILE",
    "EAGAIN",
    "EINVAL",
    "EPERM",
    "EACCESS"
  ],
  "license": "ISC",
  "main": "graceful-fs.js",
  "name": "graceful-fs",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/isaacs/node-graceful-fs.git"
  },
  "scripts": {
    "postpublish": "git push origin --follow-tags",
    "posttest": "nyc report",
    "postversion": "npm publish",
    "preversion": "npm test",
    "test": "nyc --silent node test.js | tap -c -"
  },
  "tap": {
    "reporter": "classic"
  },
  "version": "4.2.11"
}
PK~\+H_
_
graceful-fs/legacy-streams.jsnu[var Stream = require('stream').Stream

module.exports = legacy

function legacy (fs) {
  return {
    ReadStream: ReadStream,
    WriteStream: WriteStream
  }

  function ReadStream (path, options) {
    if (!(this instanceof ReadStream)) return new ReadStream(path, options);

    Stream.call(this);

    var self = this;

    this.path = path;
    this.fd = null;
    this.readable = true;
    this.paused = false;

    this.flags = 'r';
    this.mode = 438; /*=0666*/
    this.bufferSize = 64 * 1024;

    options = options || {};

    // Mixin options into this
    var keys = Object.keys(options);
    for (var index = 0, length = keys.length; index < length; index++) {
      var key = keys[index];
      this[key] = options[key];
    }

    if (this.encoding) this.setEncoding(this.encoding);

    if (this.start !== undefined) {
      if ('number' !== typeof this.start) {
        throw TypeError('start must be a Number');
      }
      if (this.end === undefined) {
        this.end = Infinity;
      } else if ('number' !== typeof this.end) {
        throw TypeError('end must be a Number');
      }

      if (this.start > this.end) {
        throw new Error('start must be <= end');
      }

      this.pos = this.start;
    }

    if (this.fd !== null) {
      process.nextTick(function() {
        self._read();
      });
      return;
    }

    fs.open(this.path, this.flags, this.mode, function (err, fd) {
      if (err) {
        self.emit('error', err);
        self.readable = false;
        return;
      }

      self.fd = fd;
      self.emit('open', fd);
      self._read();
    })
  }

  function WriteStream (path, options) {
    if (!(this instanceof WriteStream)) return new WriteStream(path, options);

    Stream.call(this);

    this.path = path;
    this.fd = null;
    this.writable = true;

    this.flags = 'w';
    this.encoding = 'binary';
    this.mode = 438; /*=0666*/
    this.bytesWritten = 0;

    options = options || {};

    // Mixin options into this
    var keys = Object.keys(options);
    for (var index = 0, length = keys.length; index < length; index++) {
      var key = keys[index];
      this[key] = options[key];
    }

    if (this.start !== undefined) {
      if ('number' !== typeof this.start) {
        throw TypeError('start must be a Number');
      }
      if (this.start < 0) {
        throw new Error('start must be >= zero');
      }

      this.pos = this.start;
    }

    this.busy = false;
    this._queue = [];

    if (this.fd === null) {
      this._open = fs.open;
      this._queue.push([this._open, this.path, this.flags, this.mode, undefined]);
      this.flush();
    }
  }
}
PK~\graceful-fs/LICENSEnu[The ISC License

Copyright (c) 2011-2022 Isaac Z. Schlueter, Ben Noordhuis, and Contributors

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
PK~\u''graceful-fs/polyfills.jsnu[var constants = require('constants')

var origCwd = process.cwd
var cwd = null

var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform

process.cwd = function() {
  if (!cwd)
    cwd = origCwd.call(process)
  return cwd
}
try {
  process.cwd()
} catch (er) {}

// This check is needed until node.js 12 is required
if (typeof process.chdir === 'function') {
  var chdir = process.chdir
  process.chdir = function (d) {
    cwd = null
    chdir.call(process, d)
  }
  if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir)
}

module.exports = patch

function patch (fs) {
  // (re-)implement some things that are known busted or missing.

  // lchmod, broken prior to 0.6.2
  // back-port the fix here.
  if (constants.hasOwnProperty('O_SYMLINK') &&
      process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
    patchLchmod(fs)
  }

  // lutimes implementation, or no-op
  if (!fs.lutimes) {
    patchLutimes(fs)
  }

  // https://github.com/isaacs/node-graceful-fs/issues/4
  // Chown should not fail on einval or eperm if non-root.
  // It should not fail on enosys ever, as this just indicates
  // that a fs doesn't support the intended operation.

  fs.chown = chownFix(fs.chown)
  fs.fchown = chownFix(fs.fchown)
  fs.lchown = chownFix(fs.lchown)

  fs.chmod = chmodFix(fs.chmod)
  fs.fchmod = chmodFix(fs.fchmod)
  fs.lchmod = chmodFix(fs.lchmod)

  fs.chownSync = chownFixSync(fs.chownSync)
  fs.fchownSync = chownFixSync(fs.fchownSync)
  fs.lchownSync = chownFixSync(fs.lchownSync)

  fs.chmodSync = chmodFixSync(fs.chmodSync)
  fs.fchmodSync = chmodFixSync(fs.fchmodSync)
  fs.lchmodSync = chmodFixSync(fs.lchmodSync)

  fs.stat = statFix(fs.stat)
  fs.fstat = statFix(fs.fstat)
  fs.lstat = statFix(fs.lstat)

  fs.statSync = statFixSync(fs.statSync)
  fs.fstatSync = statFixSync(fs.fstatSync)
  fs.lstatSync = statFixSync(fs.lstatSync)

  // if lchmod/lchown do not exist, then make them no-ops
  if (fs.chmod && !fs.lchmod) {
    fs.lchmod = function (path, mode, cb) {
      if (cb) process.nextTick(cb)
    }
    fs.lchmodSync = function () {}
  }
  if (fs.chown && !fs.lchown) {
    fs.lchown = function (path, uid, gid, cb) {
      if (cb) process.nextTick(cb)
    }
    fs.lchownSync = function () {}
  }

  // on Windows, A/V software can lock the directory, causing this
  // to fail with an EACCES or EPERM if the directory contains newly
  // created files.  Try again on failure, for up to 60 seconds.

  // Set the timeout this long because some Windows Anti-Virus, such as Parity
  // bit9, may lock files for up to a minute, causing npm package install
  // failures. Also, take care to yield the scheduler. Windows scheduling gives
  // CPU to a busy looping process, which can cause the program causing the lock
  // contention to be starved of CPU by node, so the contention doesn't resolve.
  if (platform === "win32") {
    fs.rename = typeof fs.rename !== 'function' ? fs.rename
    : (function (fs$rename) {
      function rename (from, to, cb) {
        var start = Date.now()
        var backoff = 0;
        fs$rename(from, to, function CB (er) {
          if (er
              && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY")
              && Date.now() - start < 60000) {
            setTimeout(function() {
              fs.stat(to, function (stater, st) {
                if (stater && stater.code === "ENOENT")
                  fs$rename(from, to, CB);
                else
                  cb(er)
              })
            }, backoff)
            if (backoff < 100)
              backoff += 10;
            return;
          }
          if (cb) cb(er)
        })
      }
      if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename)
      return rename
    })(fs.rename)
  }

  // if read() returns EAGAIN, then just try it again.
  fs.read = typeof fs.read !== 'function' ? fs.read
  : (function (fs$read) {
    function read (fd, buffer, offset, length, position, callback_) {
      var callback
      if (callback_ && typeof callback_ === 'function') {
        var eagCounter = 0
        callback = function (er, _, __) {
          if (er && er.code === 'EAGAIN' && eagCounter < 10) {
            eagCounter ++
            return fs$read.call(fs, fd, buffer, offset, length, position, callback)
          }
          callback_.apply(this, arguments)
        }
      }
      return fs$read.call(fs, fd, buffer, offset, length, position, callback)
    }

    // This ensures `util.promisify` works as it does for native `fs.read`.
    if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read)
    return read
  })(fs.read)

  fs.readSync = typeof fs.readSync !== 'function' ? fs.readSync
  : (function (fs$readSync) { return function (fd, buffer, offset, length, position) {
    var eagCounter = 0
    while (true) {
      try {
        return fs$readSync.call(fs, fd, buffer, offset, length, position)
      } catch (er) {
        if (er.code === 'EAGAIN' && eagCounter < 10) {
          eagCounter ++
          continue
        }
        throw er
      }
    }
  }})(fs.readSync)

  function patchLchmod (fs) {
    fs.lchmod = function (path, mode, callback) {
      fs.open( path
             , constants.O_WRONLY | constants.O_SYMLINK
             , mode
             , function (err, fd) {
        if (err) {
          if (callback) callback(err)
          return
        }
        // prefer to return the chmod error, if one occurs,
        // but still try to close, and report closing errors if they occur.
        fs.fchmod(fd, mode, function (err) {
          fs.close(fd, function(err2) {
            if (callback) callback(err || err2)
          })
        })
      })
    }

    fs.lchmodSync = function (path, mode) {
      var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode)

      // prefer to return the chmod error, if one occurs,
      // but still try to close, and report closing errors if they occur.
      var threw = true
      var ret
      try {
        ret = fs.fchmodSync(fd, mode)
        threw = false
      } finally {
        if (threw) {
          try {
            fs.closeSync(fd)
          } catch (er) {}
        } else {
          fs.closeSync(fd)
        }
      }
      return ret
    }
  }

  function patchLutimes (fs) {
    if (constants.hasOwnProperty("O_SYMLINK") && fs.futimes) {
      fs.lutimes = function (path, at, mt, cb) {
        fs.open(path, constants.O_SYMLINK, function (er, fd) {
          if (er) {
            if (cb) cb(er)
            return
          }
          fs.futimes(fd, at, mt, function (er) {
            fs.close(fd, function (er2) {
              if (cb) cb(er || er2)
            })
          })
        })
      }

      fs.lutimesSync = function (path, at, mt) {
        var fd = fs.openSync(path, constants.O_SYMLINK)
        var ret
        var threw = true
        try {
          ret = fs.futimesSync(fd, at, mt)
          threw = false
        } finally {
          if (threw) {
            try {
              fs.closeSync(fd)
            } catch (er) {}
          } else {
            fs.closeSync(fd)
          }
        }
        return ret
      }

    } else if (fs.futimes) {
      fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) }
      fs.lutimesSync = function () {}
    }
  }

  function chmodFix (orig) {
    if (!orig) return orig
    return function (target, mode, cb) {
      return orig.call(fs, target, mode, function (er) {
        if (chownErOk(er)) er = null
        if (cb) cb.apply(this, arguments)
      })
    }
  }

  function chmodFixSync (orig) {
    if (!orig) return orig
    return function (target, mode) {
      try {
        return orig.call(fs, target, mode)
      } catch (er) {
        if (!chownErOk(er)) throw er
      }
    }
  }


  function chownFix (orig) {
    if (!orig) return orig
    return function (target, uid, gid, cb) {
      return orig.call(fs, target, uid, gid, function (er) {
        if (chownErOk(er)) er = null
        if (cb) cb.apply(this, arguments)
      })
    }
  }

  function chownFixSync (orig) {
    if (!orig) return orig
    return function (target, uid, gid) {
      try {
        return orig.call(fs, target, uid, gid)
      } catch (er) {
        if (!chownErOk(er)) throw er
      }
    }
  }

  function statFix (orig) {
    if (!orig) return orig
    // Older versions of Node erroneously returned signed integers for
    // uid + gid.
    return function (target, options, cb) {
      if (typeof options === 'function') {
        cb = options
        options = null
      }
      function callback (er, stats) {
        if (stats) {
          if (stats.uid < 0) stats.uid += 0x100000000
          if (stats.gid < 0) stats.gid += 0x100000000
        }
        if (cb) cb.apply(this, arguments)
      }
      return options ? orig.call(fs, target, options, callback)
        : orig.call(fs, target, callback)
    }
  }

  function statFixSync (orig) {
    if (!orig) return orig
    // Older versions of Node erroneously returned signed integers for
    // uid + gid.
    return function (target, options) {
      var stats = options ? orig.call(fs, target, options)
        : orig.call(fs, target)
      if (stats) {
        if (stats.uid < 0) stats.uid += 0x100000000
        if (stats.gid < 0) stats.gid += 0x100000000
      }
      return stats;
    }
  }

  // ENOSYS means that the fs doesn't support the op. Just ignore
  // that, because it doesn't matter.
  //
  // if there's no getuid, or if getuid() is something other
  // than 0, and the error is EINVAL or EPERM, then just ignore
  // it.
  //
  // This specific case is a silent failure in cp, install, tar,
  // and most other unix tools that manage permissions.
  //
  // When running as root, or if other types of errors are
  // encountered, then it's strict.
  function chownErOk (er) {
    if (!er)
      return true

    if (er.code === "ENOSYS")
      return true

    var nonroot = !process.getuid || process.getuid() !== 0
    if (nonroot) {
      if (er.code === "EINVAL" || er.code === "EPERM")
        return true
    }

    return false
  }
}
PK~\h]711graceful-fs/graceful-fs.jsnu[var fs = require('fs')
var polyfills = require('./polyfills.js')
var legacy = require('./legacy-streams.js')
var clone = require('./clone.js')

var util = require('util')

/* istanbul ignore next - node 0.x polyfill */
var gracefulQueue
var previousSymbol

/* istanbul ignore else - node 0.x polyfill */
if (typeof Symbol === 'function' && typeof Symbol.for === 'function') {
  gracefulQueue = Symbol.for('graceful-fs.queue')
  // This is used in testing by future versions
  previousSymbol = Symbol.for('graceful-fs.previous')
} else {
  gracefulQueue = '___graceful-fs.queue'
  previousSymbol = '___graceful-fs.previous'
}

function noop () {}

function publishQueue(context, queue) {
  Object.defineProperty(context, gracefulQueue, {
    get: function() {
      return queue
    }
  })
}

var debug = noop
if (util.debuglog)
  debug = util.debuglog('gfs4')
else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ''))
  debug = function() {
    var m = util.format.apply(util, arguments)
    m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ')
    console.error(m)
  }

// Once time initialization
if (!fs[gracefulQueue]) {
  // This queue can be shared by multiple loaded instances
  var queue = global[gracefulQueue] || []
  publishQueue(fs, queue)

  // Patch fs.close/closeSync to shared queue version, because we need
  // to retry() whenever a close happens *anywhere* in the program.
  // This is essential when multiple graceful-fs instances are
  // in play at the same time.
  fs.close = (function (fs$close) {
    function close (fd, cb) {
      return fs$close.call(fs, fd, function (err) {
        // This function uses the graceful-fs shared queue
        if (!err) {
          resetQueue()
        }

        if (typeof cb === 'function')
          cb.apply(this, arguments)
      })
    }

    Object.defineProperty(close, previousSymbol, {
      value: fs$close
    })
    return close
  })(fs.close)

  fs.closeSync = (function (fs$closeSync) {
    function closeSync (fd) {
      // This function uses the graceful-fs shared queue
      fs$closeSync.apply(fs, arguments)
      resetQueue()
    }

    Object.defineProperty(closeSync, previousSymbol, {
      value: fs$closeSync
    })
    return closeSync
  })(fs.closeSync)

  if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) {
    process.on('exit', function() {
      debug(fs[gracefulQueue])
      require('assert').equal(fs[gracefulQueue].length, 0)
    })
  }
}

if (!global[gracefulQueue]) {
  publishQueue(global, fs[gracefulQueue]);
}

module.exports = patch(clone(fs))
if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) {
    module.exports = patch(fs)
    fs.__patched = true;
}

function patch (fs) {
  // Everything that references the open() function needs to be in here
  polyfills(fs)
  fs.gracefulify = patch

  fs.createReadStream = createReadStream
  fs.createWriteStream = createWriteStream
  var fs$readFile = fs.readFile
  fs.readFile = readFile
  function readFile (path, options, cb) {
    if (typeof options === 'function')
      cb = options, options = null

    return go$readFile(path, options, cb)

    function go$readFile (path, options, cb, startTime) {
      return fs$readFile(path, options, function (err) {
        if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
          enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()])
        else {
          if (typeof cb === 'function')
            cb.apply(this, arguments)
        }
      })
    }
  }

  var fs$writeFile = fs.writeFile
  fs.writeFile = writeFile
  function writeFile (path, data, options, cb) {
    if (typeof options === 'function')
      cb = options, options = null

    return go$writeFile(path, data, options, cb)

    function go$writeFile (path, data, options, cb, startTime) {
      return fs$writeFile(path, data, options, function (err) {
        if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
          enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()])
        else {
          if (typeof cb === 'function')
            cb.apply(this, arguments)
        }
      })
    }
  }

  var fs$appendFile = fs.appendFile
  if (fs$appendFile)
    fs.appendFile = appendFile
  function appendFile (path, data, options, cb) {
    if (typeof options === 'function')
      cb = options, options = null

    return go$appendFile(path, data, options, cb)

    function go$appendFile (path, data, options, cb, startTime) {
      return fs$appendFile(path, data, options, function (err) {
        if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
          enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()])
        else {
          if (typeof cb === 'function')
            cb.apply(this, arguments)
        }
      })
    }
  }

  var fs$copyFile = fs.copyFile
  if (fs$copyFile)
    fs.copyFile = copyFile
  function copyFile (src, dest, flags, cb) {
    if (typeof flags === 'function') {
      cb = flags
      flags = 0
    }
    return go$copyFile(src, dest, flags, cb)

    function go$copyFile (src, dest, flags, cb, startTime) {
      return fs$copyFile(src, dest, flags, function (err) {
        if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
          enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()])
        else {
          if (typeof cb === 'function')
            cb.apply(this, arguments)
        }
      })
    }
  }

  var fs$readdir = fs.readdir
  fs.readdir = readdir
  var noReaddirOptionVersions = /^v[0-5]\./
  function readdir (path, options, cb) {
    if (typeof options === 'function')
      cb = options, options = null

    var go$readdir = noReaddirOptionVersions.test(process.version)
      ? function go$readdir (path, options, cb, startTime) {
        return fs$readdir(path, fs$readdirCallback(
          path, options, cb, startTime
        ))
      }
      : function go$readdir (path, options, cb, startTime) {
        return fs$readdir(path, options, fs$readdirCallback(
          path, options, cb, startTime
        ))
      }

    return go$readdir(path, options, cb)

    function fs$readdirCallback (path, options, cb, startTime) {
      return function (err, files) {
        if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
          enqueue([
            go$readdir,
            [path, options, cb],
            err,
            startTime || Date.now(),
            Date.now()
          ])
        else {
          if (files && files.sort)
            files.sort()

          if (typeof cb === 'function')
            cb.call(this, err, files)
        }
      }
    }
  }

  if (process.version.substr(0, 4) === 'v0.8') {
    var legStreams = legacy(fs)
    ReadStream = legStreams.ReadStream
    WriteStream = legStreams.WriteStream
  }

  var fs$ReadStream = fs.ReadStream
  if (fs$ReadStream) {
    ReadStream.prototype = Object.create(fs$ReadStream.prototype)
    ReadStream.prototype.open = ReadStream$open
  }

  var fs$WriteStream = fs.WriteStream
  if (fs$WriteStream) {
    WriteStream.prototype = Object.create(fs$WriteStream.prototype)
    WriteStream.prototype.open = WriteStream$open
  }

  Object.defineProperty(fs, 'ReadStream', {
    get: function () {
      return ReadStream
    },
    set: function (val) {
      ReadStream = val
    },
    enumerable: true,
    configurable: true
  })
  Object.defineProperty(fs, 'WriteStream', {
    get: function () {
      return WriteStream
    },
    set: function (val) {
      WriteStream = val
    },
    enumerable: true,
    configurable: true
  })

  // legacy names
  var FileReadStream = ReadStream
  Object.defineProperty(fs, 'FileReadStream', {
    get: function () {
      return FileReadStream
    },
    set: function (val) {
      FileReadStream = val
    },
    enumerable: true,
    configurable: true
  })
  var FileWriteStream = WriteStream
  Object.defineProperty(fs, 'FileWriteStream', {
    get: function () {
      return FileWriteStream
    },
    set: function (val) {
      FileWriteStream = val
    },
    enumerable: true,
    configurable: true
  })

  function ReadStream (path, options) {
    if (this instanceof ReadStream)
      return fs$ReadStream.apply(this, arguments), this
    else
      return ReadStream.apply(Object.create(ReadStream.prototype), arguments)
  }

  function ReadStream$open () {
    var that = this
    open(that.path, that.flags, that.mode, function (err, fd) {
      if (err) {
        if (that.autoClose)
          that.destroy()

        that.emit('error', err)
      } else {
        that.fd = fd
        that.emit('open', fd)
        that.read()
      }
    })
  }

  function WriteStream (path, options) {
    if (this instanceof WriteStream)
      return fs$WriteStream.apply(this, arguments), this
    else
      return WriteStream.apply(Object.create(WriteStream.prototype), arguments)
  }

  function WriteStream$open () {
    var that = this
    open(that.path, that.flags, that.mode, function (err, fd) {
      if (err) {
        that.destroy()
        that.emit('error', err)
      } else {
        that.fd = fd
        that.emit('open', fd)
      }
    })
  }

  function createReadStream (path, options) {
    return new fs.ReadStream(path, options)
  }

  function createWriteStream (path, options) {
    return new fs.WriteStream(path, options)
  }

  var fs$open = fs.open
  fs.open = open
  function open (path, flags, mode, cb) {
    if (typeof mode === 'function')
      cb = mode, mode = null

    return go$open(path, flags, mode, cb)

    function go$open (path, flags, mode, cb, startTime) {
      return fs$open(path, flags, mode, function (err, fd) {
        if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
          enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()])
        else {
          if (typeof cb === 'function')
            cb.apply(this, arguments)
        }
      })
    }
  }

  return fs
}

function enqueue (elem) {
  debug('ENQUEUE', elem[0].name, elem[1])
  fs[gracefulQueue].push(elem)
  retry()
}

// keep track of the timeout between retry() calls
var retryTimer

// reset the startTime and lastTime to now
// this resets the start of the 60 second overall timeout as well as the
// delay between attempts so that we'll retry these jobs sooner
function resetQueue () {
  var now = Date.now()
  for (var i = 0; i < fs[gracefulQueue].length; ++i) {
    // entries that are only a length of 2 are from an older version, don't
    // bother modifying those since they'll be retried anyway.
    if (fs[gracefulQueue][i].length > 2) {
      fs[gracefulQueue][i][3] = now // startTime
      fs[gracefulQueue][i][4] = now // lastTime
    }
  }
  // call retry to make sure we're actively processing the queue
  retry()
}

function retry () {
  // clear the timer and remove it to help prevent unintended concurrency
  clearTimeout(retryTimer)
  retryTimer = undefined

  if (fs[gracefulQueue].length === 0)
    return

  var elem = fs[gracefulQueue].shift()
  var fn = elem[0]
  var args = elem[1]
  // these items may be unset if they were added by an older graceful-fs
  var err = elem[2]
  var startTime = elem[3]
  var lastTime = elem[4]

  // if we don't have a startTime we have no way of knowing if we've waited
  // long enough, so go ahead and retry this item now
  if (startTime === undefined) {
    debug('RETRY', fn.name, args)
    fn.apply(null, args)
  } else if (Date.now() - startTime >= 60000) {
    // it's been more than 60 seconds total, bail now
    debug('TIMEOUT', fn.name, args)
    var cb = args.pop()
    if (typeof cb === 'function')
      cb.call(null, err)
  } else {
    // the amount of time between the last attempt and right now
    var sinceAttempt = Date.now() - lastTime
    // the amount of time between when we first tried, and when we last tried
    // rounded up to at least 1
    var sinceStart = Math.max(lastTime - startTime, 1)
    // backoff. wait longer than the total time we've been retrying, but only
    // up to a maximum of 100ms
    var desiredDelay = Math.min(sinceStart * 1.2, 100)
    // it's been long enough since the last retry, do it again
    if (sinceAttempt >= desiredDelay) {
      debug('RETRY', fn.name, args)
      fn.apply(null, args.concat([startTime]))
    } else {
      // if we can't do this job yet, push it to the end of the queue
      // and let the next iteration check again
      fs[gracefulQueue].push(elem)
    }
  }

  // schedule our next run if one isn't already scheduled
  if (retryTimer === undefined) {
    retryTimer = setTimeout(retry, 0)
  }
}
PK~\Cbblibnpmorg/package.jsonnu[{
  "_id": "libnpmorg@6.0.6",
  "_inBundle": true,
  "_location": "/npm/libnpmorg",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm"
  ],
  "author": {
    "name": "GitHub Inc."
  },
  "bugs": {
    "url": "https://github.com/npm/libnpmorg/issues"
  },
  "dependencies": {
    "aproba": "^2.0.0",
    "npm-registry-fetch": "^17.0.1"
  },
  "description": "Programmatic api for `npm org` commands",
  "devDependencies": {
    "@npmcli/eslint-config": "^4.0.0",
    "@npmcli/template-oss": "4.22.0",
    "minipass": "^7.1.1",
    "nock": "^13.3.3",
    "tap": "^16.3.8"
  },
  "engines": {
    "node": "^16.14.0 || >=18.0.0"
  },
  "files": [
    "bin/",
    "lib/"
  ],
  "homepage": "https://npmjs.com/package/libnpmorg",
  "keywords": [
    "libnpm",
    "npm",
    "package manager",
    "api",
    "orgs",
    "teams"
  ],
  "license": "ISC",
  "main": "lib/index.js",
  "name": "libnpmorg",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/cli.git",
    "directory": "workspaces/libnpmorg"
  },
  "scripts": {
    "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"",
    "lintfix": "npm run lint -- --fix",
    "postlint": "template-oss-check",
    "posttest": "npm run lint",
    "snap": "tap",
    "template-oss-apply": "template-oss-apply --force",
    "test": "tap"
  },
  "tap": {
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.22.0",
    "content": "../../scripts/template-oss/index.js"
  },
  "version": "6.0.6"
}
PK~\\}libnpmorg/lib/index.jsnu['use strict'

const eu = encodeURIComponent
const fetch = require('npm-registry-fetch')
const validate = require('aproba')

// From https://github.com/npm/registry/blob/master/docs/orgs/memberships.md
const cmd = module.exports

class MembershipDetail {}
cmd.set = (org, user, role, opts = {}) => {
  if (
    typeof role === 'object' &&
    Object.keys(opts).length === 0
  ) {
    opts = role
    role = undefined
  }
  validate('SSSO|SSZO', [org, user, role, opts])
  user = user.replace(/^@?/, '')
  org = org.replace(/^@?/, '')
  return fetch.json(`/-/org/${eu(org)}/user`, {
    ...opts,
    method: 'PUT',
    body: { user, role },
  }).then(ret => Object.assign(new MembershipDetail(), ret))
}

cmd.rm = (org, user, opts = {}) => {
  validate('SSO', [org, user, opts])
  user = user.replace(/^@?/, '')
  org = org.replace(/^@?/, '')
  return fetch(`/-/org/${eu(org)}/user`, {
    ...opts,
    method: 'DELETE',
    body: { user },
    ignoreBody: true,
  }).then(() => null)
}

class Roster {}
cmd.ls = (org, opts = {}) => {
  return cmd.ls.stream(org, opts)
    .collect()
    .then(data => data.reduce((acc, [key, val]) => {
      if (!acc) {
        acc = {}
      }
      acc[key] = val
      return acc
    }, null))
    .then(ret => Object.assign(new Roster(), ret))
}

cmd.ls.stream = (org, opts = {}) => {
  validate('SO', [org, opts])
  org = org.replace(/^@?/, '')
  return fetch.json.stream(`/-/org/${eu(org)}/user`, '*', {
    ...opts,
    mapJSON: (value, [key]) => {
      return [key, value]
    },
  })
}
PK~\gXlibnpmorg/LICENSEnu[Copyright npm, Inc

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
PK~\q|-ůlibnpmorg/README.mdnu[# libnpmorg

[![npm version](https://img.shields.io/npm/v/libnpmorg.svg)](https://npm.im/libnpmorg)
[![license](https://img.shields.io/npm/l/libnpmorg.svg)](https://npm.im/libnpmorg)
[![CI - libnpmorg](https://github.com/npm/cli/actions/workflows/ci-libnpmorg.yml/badge.svg)](https://github.com/npm/cli/actions/workflows/ci-libnpmorg.yml)

[`libnpmorg`](https://github.com/npm/libnpmorg) is a Node.js library for
programmatically accessing the [npm Org membership
API](https://github.com/npm/registry/blob/master/docs/orgs/memberships.md#membership-detail).

## Table of Contents

* [Example](#example)
* [Install](#install)
* [Contributing](#contributing)
* [API](#api)
  * [hook opts](#opts)
  * [`set()`](#set)
  * [`rm()`](#rm)
  * [`ls()`](#ls)
  * [`ls.stream()`](#ls-stream)

## Example

```js
const org = require('libnpmorg')

console.log(await org.ls('myorg', {token: 'deadbeef'}))
=>
Roster {
  zkat: 'developer',
  iarna: 'admin',
  isaacs: 'owner'
}
```

## Install

`$ npm install libnpmorg`

### API

####  `opts` for `libnpmorg` commands

`libnpmorg` uses [`npm-registry-fetch`](https://npm.im/npm-registry-fetch).
All options are passed through directly to that library, so please refer to [its
own `opts`
documentation](https://www.npmjs.com/package/npm-registry-fetch#fetch-options)
for options that can be passed in.

A couple of options of note for those in a hurry:

* `opts.token` - can be passed in and will be used as the authentication token for the registry. For other ways to pass in auth details, see the n-r-f docs.
* `opts.otp` - certain operations will require an OTP token to be passed in. If a `libnpmorg` command fails with `err.code === EOTP`, please retry the request with `{otp: <2fa token>}`

####  `> org.set(org, user, [role], [opts]) -> Promise`

The returned Promise resolves to a [Membership
Detail](https://github.com/npm/registry/blob/master/docs/orgs/memberships.md#membership-detail)
object.

The `role` is optional and should be one of `admin`, `owner`, or `developer`.
`developer` is the default if no `role` is provided.

`org` and `user` must be scope names for the org name and user name
respectively. They can optionally be prefixed with `@`.

See also: [`PUT
/-/org/:scope/user`](https://github.com/npm/registry/blob/master/docs/orgs/memberships.md#org-membership-replace)

##### Example

```javascript
await org.set('@myorg', '@myuser', 'admin', {token: 'deadbeef'})
=>
MembershipDetail {
  org: {
    name: 'myorg',
    size: 15
  },
  user: 'myuser',
  role: 'admin'
}
```

####  `> org.rm(org, user, [opts]) -> Promise`

The Promise resolves to `null` on success.

`org` and `user` must be scope names for the org name and user name
respectively. They can optionally be prefixed with `@`.

See also: [`DELETE
/-/org/:scope/user`](https://github.com/npm/registry/blob/master/docs/orgs/memberships.md#org-membership-delete)

##### Example

```javascript
await org.rm('myorg', 'myuser', {token: 'deadbeef'})
```

####  `> org.ls(org, [opts]) -> Promise`

The Promise resolves to a
[Roster](https://github.com/npm/registry/blob/master/docs/orgs/memberships.md#roster)
object.

`org` must be a scope name for an org, and can be optionally prefixed with `@`.

See also: [`GET
/-/org/:scope/user`](https://github.com/npm/registry/blob/master/docs/orgs/memberships.md#org-roster)

##### Example

```javascript
await org.ls('myorg', {token: 'deadbeef'})
=>
Roster {
  zkat: 'developer',
  iarna: 'admin',
  isaacs: 'owner'
}
```

####  `> org.ls.stream(org, [opts]) -> Stream`

Returns a stream of entries for a
[Roster](https://github.com/npm/registry/blob/master/docs/orgs/memberships.md#roster),
with each emitted entry in `[key, value]` format.

`org` must be a scope name for an org, and can be optionally prefixed with `@`.

The returned stream is a valid `Symbol.asyncIterator`.

See also: [`GET
/-/org/:scope/user`](https://github.com/npm/registry/blob/master/docs/orgs/memberships.md#org-roster)

##### Example

```javascript
for await (let [user, role] of org.ls.stream('myorg', {token: 'deadbeef'})) {
  console.log(`user: ${user} (${role})`)
}
=>
user: zkat (developer)
user: iarna (admin)
user: isaacs (owner)
```
PK~\/&
npm-user-validate/package.jsonnu[{
  "_id": "npm-user-validate@2.0.1",
  "_inBundle": true,
  "_location": "/npm/npm-user-validate",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm"
  ],
  "author": {
    "name": "GitHub Inc."
  },
  "bugs": {
    "url": "https://github.com/npm/npm-user-validate/issues"
  },
  "description": "User validations for npm",
  "devDependencies": {
    "@npmcli/eslint-config": "^4.0.1",
    "@npmcli/template-oss": "4.22.0",
    "tap": "^16.3.2"
  },
  "engines": {
    "node": "^14.17.0 || ^16.13.0 || >=18.0.0"
  },
  "files": [
    "bin/",
    "lib/"
  ],
  "homepage": "https://github.com/npm/npm-user-validate#readme",
  "keywords": [
    "npm",
    "validation",
    "registry"
  ],
  "license": "BSD-2-Clause",
  "main": "lib/index.js",
  "name": "npm-user-validate",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/npm-user-validate.git"
  },
  "scripts": {
    "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"",
    "lintfix": "npm run lint -- --fix",
    "postlint": "template-oss-check",
    "posttest": "npm run lint",
    "snap": "tap",
    "template-oss-apply": "template-oss-apply --force",
    "test": "tap"
  },
  "tap": {
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.22.0",
    "publish": true
  },
  "version": "2.0.1"
}
PK~\K߁{{npm-user-validate/lib/index.jsnu[exports.email = email
exports.pw = pw
exports.username = username
var requirements = exports.requirements = {
  username: {
    length: 'Name length must be less than or equal to 214 characters long',
    lowerCase: 'Name must be lowercase',
    urlSafe: 'Name may not contain non-url-safe chars',
    dot: 'Name may not start with "."',
    illegal: 'Name may not contain illegal character',
  },
  password: {},
  email: {
    length: 'Email length must be less then or equal to 254 characters long',
    valid: 'Email must be an email address',
  },
}

var illegalCharacterRe = new RegExp('([' + [
  "'",
].join() + '])')

function username (un) {
  if (un !== un.toLowerCase()) {
    return new Error(requirements.username.lowerCase)
  }

  if (un !== encodeURIComponent(un)) {
    return new Error(requirements.username.urlSafe)
  }

  if (un.charAt(0) === '.') {
    return new Error(requirements.username.dot)
  }

  if (un.length > 214) {
    return new Error(requirements.username.length)
  }

  var illegal = un.match(illegalCharacterRe)
  if (illegal) {
    return new Error(requirements.username.illegal + ' "' + illegal[0] + '"')
  }

  return null
}

function email (em) {
  if (em.length > 254) {
    return new Error(requirements.email.length)
  }
  if (!em.match(/^[^@]+@.+\..+$/)) {
    return new Error(requirements.email.valid)
  }

  return null
}

function pw () {
  return null
}
PK~\r^npm-user-validate/LICENSEnu[Copyright (c) Robert Kowalski
All rights reserved.

The BSD License

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.PK~\`**balanced-match/package.jsonnu[{
  "_id": "balanced-match@1.0.2",
  "_inBundle": true,
  "_location": "/npm/balanced-match",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm/brace-expansion"
  ],
  "author": {
    "name": "Julian Gruber",
    "email": "mail@juliangruber.com",
    "url": "http://juliangruber.com"
  },
  "bugs": {
    "url": "https://github.com/juliangruber/balanced-match/issues"
  },
  "description": "Match balanced character pairs, like \"{\" and \"}\"",
  "devDependencies": {
    "matcha": "^0.7.0",
    "tape": "^4.6.0"
  },
  "homepage": "https://github.com/juliangruber/balanced-match",
  "keywords": [
    "match",
    "regexp",
    "test",
    "balanced",
    "parse"
  ],
  "license": "MIT",
  "main": "index.js",
  "name": "balanced-match",
  "repository": {
    "type": "git",
    "url": "git://github.com/juliangruber/balanced-match.git"
  },
  "scripts": {
    "bench": "matcha test/bench.js",
    "test": "tape test/test.js"
  },
  "testling": {
    "files": "test/*.js",
    "browsers": [
      "ie/8..latest",
      "firefox/20..latest",
      "firefox/nightly",
      "chrome/25..latest",
      "chrome/canary",
      "opera/12..latest",
      "opera/next",
      "safari/5.1..latest",
      "ipad/6.0..latest",
      "iphone/6.0..latest",
      "android-browser/4.2..latest"
    ]
  },
  "version": "1.0.2"
}
PK~\3balanced-match/index.jsnu['use strict';
module.exports = balanced;
function balanced(a, b, str) {
  if (a instanceof RegExp) a = maybeMatch(a, str);
  if (b instanceof RegExp) b = maybeMatch(b, str);

  var r = range(a, b, str);

  return r && {
    start: r[0],
    end: r[1],
    pre: str.slice(0, r[0]),
    body: str.slice(r[0] + a.length, r[1]),
    post: str.slice(r[1] + b.length)
  };
}

function maybeMatch(reg, str) {
  var m = str.match(reg);
  return m ? m[0] : null;
}

balanced.range = range;
function range(a, b, str) {
  var begs, beg, left, right, result;
  var ai = str.indexOf(a);
  var bi = str.indexOf(b, ai + 1);
  var i = ai;

  if (ai >= 0 && bi > 0) {
    if(a===b) {
      return [ai, bi];
    }
    begs = [];
    left = str.length;

    while (i >= 0 && !result) {
      if (i == ai) {
        begs.push(i);
        ai = str.indexOf(a, i + 1);
      } else if (begs.length == 1) {
        result = [ begs.pop(), bi ];
      } else {
        beg = begs.pop();
        if (beg < left) {
          left = beg;
          right = bi;
        }

        bi = str.indexOf(b, i + 1);
      }

      i = ai < bi && ai >= 0 ? ai : bi;
    }

    if (begs.length) {
      result = [ left, right ];
    }
  }

  return result;
}
PK~\HHbalanced-match/LICENSE.mdnu[(MIT)

Copyright (c) 2013 Julian Gruber <julian@juliangruber.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
PK~\l(ѷarchy/package.jsonnu[{
  "_id": "archy@1.0.0",
  "_inBundle": true,
  "_location": "/npm/archy",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm"
  ],
  "author": {
    "name": "James Halliday",
    "email": "mail@substack.net",
    "url": "http://substack.net"
  },
  "bugs": {
    "url": "https://github.com/substack/node-archy/issues"
  },
  "description": "render nested hierarchies `npm ls` style with unicode pipes",
  "devDependencies": {
    "tap": "~0.3.3",
    "tape": "~0.1.1"
  },
  "homepage": "https://github.com/substack/node-archy#readme",
  "keywords": [
    "hierarchy",
    "npm ls",
    "unicode",
    "pretty",
    "print"
  ],
  "license": "MIT",
  "main": "index.js",
  "name": "archy",
  "repository": {
    "type": "git",
    "url": "git+ssh://git@github.com/substack/node-archy.git"
  },
  "scripts": {
    "test": "tap test"
  },
  "testling": {
    "files": "test/*.js",
    "browsers": {
      "iexplore": [
        "6.0",
        "7.0",
        "8.0",
        "9.0"
      ],
      "chrome": [
        "20.0"
      ],
      "firefox": [
        "10.0",
        "15.0"
      ],
      "safari": [
        "5.1"
      ],
      "opera": [
        "12.0"
      ]
    }
  },
  "version": "1.0.0"
}
PK~\]}archy/test/multi_line.jsnu[var test = require('tape');
var archy = require('../');

test('multi-line', function (t) {
    var s = archy({
      label : 'beep\none\ntwo',
      nodes : [
        'ity',
        {
          label : 'boop',
          nodes : [
            {
              label : 'o_O\nwheee',
              nodes : [
                {
                  label : 'oh',
                  nodes : [ 'hello', 'puny\nmeat' ]
                },
                'creature'
              ]
            },
            'party\ntime!'
          ]
        }
      ]
    });
    t.equal(s, [
        'beep',
        '│ one',
        '│ two',
        '├── ity',
        '└─┬ boop',
        '  ├─┬ o_O',
        '  │ │ wheee',
        '  │ ├─┬ oh',
        '  │ │ ├── hello',
        '  │ │ └── puny',
        '  │ │     meat',
        '  │ └── creature',
        '  └── party',
        '      time!',
        ''
    ].join('\n'));
    t.end();
});
PK~\aarchy/test/non_unicode.jsnu[var test = require('tape');
var archy = require('../');

test('beep', function (t) {
    var s = archy({
      label : 'beep',
      nodes : [
        'ity',
        {
          label : 'boop',
          nodes : [
            {
              label : 'o_O',
              nodes : [
                {
                  label : 'oh',
                  nodes : [ 'hello', 'puny' ]
                },
                'human'
              ]
            },
            'party!'
          ]
        }
      ]
    }, '', { unicode : false });
    t.equal(s, [
        'beep',
        '+-- ity',
        '`-- boop',
        '  +-- o_O',
        '  | +-- oh',
        '  | | +-- hello',
        '  | | `-- puny',
        '  | `-- human',
        '  `-- party!',
        ''
    ].join('\n'));
    t.end();
});
PK~\BBarchy/test/beep.jsnu[var test = require('tape');
var archy = require('../');

test('beep', function (t) {
    var s = archy({
      label : 'beep',
      nodes : [
        'ity',
        {
          label : 'boop',
          nodes : [
            {
              label : 'o_O',
              nodes : [
                {
                  label : 'oh',
                  nodes : [ 'hello', 'puny' ]
                },
                'human'
              ]
            },
            'party!'
          ]
        }
      ]
    });
    t.equal(s, [
        'beep',
        '├── ity',
        '└─┬ boop',
        '  ├─┬ o_O',
        '  │ ├─┬ oh',
        '  │ │ ├── hello',
        '  │ │ └── puny',
        '  │ └── human',
        '  └── party!',
        ''
    ].join('\n'));
    t.end();
});
PK~\Gl11
archy/LICENSEnu[This software is released under the MIT license:

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
PK~\
Dttarchy/index.jsnu[module.exports = function archy (obj, prefix, opts) {
    if (prefix === undefined) prefix = '';
    if (!opts) opts = {};
    var chr = function (s) {
        var chars = {
            '│' : '|',
            '└' : '`',
            '├' : '+',
            '─' : '-',
            '┬' : '-'
        };
        return opts.unicode === false ? chars[s] : s;
    };
    
    if (typeof obj === 'string') obj = { label : obj };
    
    var nodes = obj.nodes || [];
    var lines = (obj.label || '').split('\n');
    var splitter = '\n' + prefix + (nodes.length ? chr('│') : ' ') + ' ';
    
    return prefix
        + lines.join(splitter) + '\n'
        + nodes.map(function (node, ix) {
            var last = ix === nodes.length - 1;
            var more = node.nodes && node.nodes.length;
            var prefix_ = prefix + (last ? ' ' : chr('│')) + ' ';
            
            return prefix
                + (last ? chr('└') : chr('├')) + chr('─')
                + (more ? chr('┬') : chr('─')) + ' '
                + archy(node, prefix_, opts).slice(prefix.length + 2)
            ;
        }).join('')
    ;
};
PK~\ʁՁarchy/examples/multi_line.jsnu[var archy = require('../');

var s = archy({
  label : 'beep\none\ntwo',
  nodes : [
    'ity',
    {
      label : 'boop',
      nodes : [
        {
          label : 'o_O\nwheee',
          nodes : [
            {
              label : 'oh',
              nodes : [ 'hello', 'puny\nmeat' ]
            },
            'creature'
          ]
        },
        'party\ntime!'
      ]
    }
  ]
});
console.log(s);
PK~\?鋃archy/examples/beep.jsnu[var archy = require('../');
var s = archy({
  label : 'beep',
  nodes : [
    'ity',
    {
      label : 'boop',
      nodes : [
        {
          label : 'o_O',
          nodes : [
            {
              label : 'oh',
              nodes : [ 'hello', 'puny' ]
            },
            'human'
          ]
        },
        'party\ntime!'
      ]
    }
  ]
});
console.log(s);
PK~\	OBlibnpmpublish/package.jsonnu[{
  "_id": "libnpmpublish@9.0.9",
  "_inBundle": true,
  "_location": "/npm/libnpmpublish",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm"
  ],
  "author": {
    "name": "GitHub Inc."
  },
  "bugs": {
    "url": "https://github.com/npm/cli/issues"
  },
  "contributors": [
    {
      "name": "Kat Marchán",
      "email": "kzm@zkat.tech"
    },
    {
      "name": "Claudia Hernández",
      "email": "claudia@npmjs.com"
    }
  ],
  "dependencies": {
    "ci-info": "^4.0.0",
    "normalize-package-data": "^6.0.1",
    "npm-package-arg": "^11.0.2",
    "npm-registry-fetch": "^17.0.1",
    "proc-log": "^4.2.0",
    "semver": "^7.3.7",
    "sigstore": "^2.2.0",
    "ssri": "^10.0.6"
  },
  "description": "Programmatic API for the bits behind npm publish and unpublish",
  "devDependencies": {
    "@npmcli/eslint-config": "^4.0.0",
    "@npmcli/mock-globals": "^1.0.0",
    "@npmcli/mock-registry": "^1.0.0",
    "@npmcli/template-oss": "4.22.0",
    "nock": "^13.3.3",
    "tap": "^16.3.8"
  },
  "engines": {
    "node": "^16.14.0 || >=18.0.0"
  },
  "files": [
    "bin/",
    "lib/"
  ],
  "homepage": "https://npmjs.com/package/libnpmpublish",
  "license": "ISC",
  "main": "lib/index.js",
  "name": "libnpmpublish",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/cli.git",
    "directory": "workspaces/libnpmpublish"
  },
  "scripts": {
    "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"",
    "lintfix": "npm run lint -- --fix",
    "postlint": "template-oss-check",
    "posttest": "npm run lint",
    "snap": "tap",
    "template-oss-apply": "template-oss-apply --force",
    "test": "tap"
  },
  "tap": {
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.22.0",
    "content": "../../scripts/template-oss/index.js"
  },
  "version": "9.0.9"
}
PK~\9(aalibnpmpublish/lib/index.jsnu[module.exports = {
  publish: require('./publish.js'),
  unpublish: require('./unpublish.js'),
}
PK~\ -libnpmpublish/lib/unpublish.jsnu['use strict'

const { URL } = require('node:url')
const npa = require('npm-package-arg')
const npmFetch = require('npm-registry-fetch')
const semver = require('semver')

// given a tarball url and a registry url, returns just the
// relevant pathname portion of it, so that it can be handled
// elegantly by npm-registry-fetch which only expects pathnames
// and handles the registry hostname via opts
const getPathname = (tarball, registry) => {
  const registryUrl = new URL(registry).pathname.slice(1)
  let tarballUrl = new URL(tarball).pathname.slice(1)

  // test the tarball url to see if it starts with a possible
  // pathname from the registry url, in that case strips that portion
  // of it so that we only return the post-registry-url pathname
  if (registryUrl) {
    tarballUrl = tarballUrl.slice(registryUrl.length)
  }
  return tarballUrl
}

const unpublish = async (spec, opts) => {
  spec = npa(spec)
  // spec is used to pick the appropriate registry/auth combo.
  opts = {
    force: false,
    ...opts,
    spec,
  }

  try {
    const pkgUri = spec.escapedName
    const pkg = await npmFetch.json(pkgUri, {
      ...opts,
      query: { write: true },
    })

    const version = spec.rawSpec
    const allVersions = pkg.versions || {}
    const versionData = allVersions[version]

    const rawSpecs = (!spec.rawSpec || spec.rawSpec === '*')
    const onlyVersion = Object.keys(allVersions).length === 1
    const noVersions = !Object.keys(allVersions).length

    // if missing specific version,
    // assumed unpublished
    if (!versionData && !rawSpecs && !noVersions) {
      return true
    }

    // unpublish all versions of a package:
    // - no specs supplied "npm unpublish foo"
    // - all specs ("*") "npm unpublish foo@*"
    // - there was only one version
    // - has no versions field on packument
    if (rawSpecs || onlyVersion || noVersions) {
      await npmFetch(`${pkgUri}/-rev/${pkg._rev}`, {
        ...opts,
        method: 'DELETE',
        ignoreBody: true,
      })
      return true
    } else {
      const dist = allVersions[version].dist
      delete allVersions[version]

      const latestVer = pkg['dist-tags'].latest

      // deleting dist tags associated to version
      Object.keys(pkg['dist-tags']).forEach(tag => {
        if (pkg['dist-tags'][tag] === version) {
          delete pkg['dist-tags'][tag]
        }
      })

      if (latestVer === version) {
        pkg['dist-tags'].latest = Object.keys(
          allVersions
        ).sort(semver.compareLoose).pop()
      }

      delete pkg._revisions
      delete pkg._attachments

      // Update packument with removed versions
      await npmFetch(`${pkgUri}/-rev/${pkg._rev}`, {
        ...opts,
        method: 'PUT',
        body: pkg,
        ignoreBody: true,
      })

      // Remove the tarball itself
      const { _rev } = await npmFetch.json(pkgUri, {
        ...opts,
        query: { write: true },
      })
      const tarballUrl = getPathname(dist.tarball, opts.registry)
      await npmFetch(`${tarballUrl}/-rev/${_rev}`, {
        ...opts,
        method: 'DELETE',
        ignoreBody: true,
      })
      return true
    }
  } catch (err) {
    if (err.code !== 'E404') {
      throw err
    }

    return true
  }
}

module.exports = unpublish
PK~\e)

libnpmpublish/lib/publish.jsnu[const { fixer } = require('normalize-package-data')
const npmFetch = require('npm-registry-fetch')
const npa = require('npm-package-arg')
const { log } = require('proc-log')
const semver = require('semver')
const { URL } = require('node:url')
const ssri = require('ssri')
const ciInfo = require('ci-info')

const { generateProvenance, verifyProvenance } = require('./provenance')

const TLOG_BASE_URL = 'https://search.sigstore.dev/'

const publish = async (manifest, tarballData, opts) => {
  if (manifest.private) {
    throw Object.assign(
      new Error(`This package has been marked as private
Remove the 'private' field from the package.json to publish it.`),
      { code: 'EPRIVATE' }
    )
  }

  // spec is used to pick the appropriate registry/auth combo
  const spec = npa.resolve(manifest.name, manifest.version)
  opts = {
    access: 'public',
    algorithms: ['sha512'],
    defaultTag: 'latest',
    ...opts,
    spec,
  }

  const reg = npmFetch.pickRegistry(spec, opts)
  const pubManifest = patchManifest(manifest, opts)

  // registry-frontdoor cares about the access level,
  // which is only configurable for scoped packages
  if (!spec.scope && opts.access === 'restricted') {
    throw Object.assign(
      new Error("Can't restrict access to unscoped packages."),
      { code: 'EUNSCOPED' }
    )
  }

  const { metadata, transparencyLogUrl } = await buildMetadata(
    reg,
    pubManifest,
    tarballData,
    spec,
    opts
  )

  const res = await npmFetch(spec.escapedName, {
    ...opts,
    method: 'PUT',
    body: metadata,
    ignoreBody: true,
  })
  if (transparencyLogUrl) {
    res.transparencyLogUrl = transparencyLogUrl
  }
  return res
}

const patchManifest = (_manifest, opts) => {
  const { npmVersion } = opts
  // we only update top-level fields, so a shallow clone is fine
  const manifest = { ..._manifest }

  manifest._nodeVersion = process.versions.node
  if (npmVersion) {
    manifest._npmVersion = npmVersion
  }

  fixer.fixNameField(manifest, { strict: true, allowLegacyCase: true })
  const version = semver.clean(manifest.version)
  if (!version) {
    throw Object.assign(
      new Error('invalid semver: ' + manifest.version),
      { code: 'EBADSEMVER' }
    )
  }
  manifest.version = version
  return manifest
}

const buildMetadata = async (registry, manifest, tarballData, spec, opts) => {
  const { access, defaultTag, algorithms, provenance, provenanceFile } = opts
  const root = {
    _id: manifest.name,
    name: manifest.name,
    description: manifest.description,
    'dist-tags': {},
    versions: {},
    access,
  }

  root.versions[manifest.version] = manifest
  const tag = manifest.tag || defaultTag
  root['dist-tags'][tag] = manifest.version

  const tarballName = `${manifest.name}-${manifest.version}.tgz`
  const provenanceBundleName = `${manifest.name}-${manifest.version}.sigstore`
  const tarballURI = `${manifest.name}/-/${tarballName}`
  const integrity = ssri.fromData(tarballData, {
    algorithms: [...new Set(['sha1'].concat(algorithms))],
  })

  manifest._id = `${manifest.name}@${manifest.version}`
  manifest.dist = { ...manifest.dist }
  // Don't bother having sha1 in the actual integrity field
  manifest.dist.integrity = integrity.sha512[0].toString()
  // Legacy shasum support
  manifest.dist.shasum = integrity.sha1[0].hexDigest()

  // NB: the CLI always fetches via HTTPS if the registry is HTTPS,
  // regardless of what's here.  This makes it so that installing
  // from an HTTP-only mirror doesn't cause problems, though.
  manifest.dist.tarball = new URL(tarballURI, registry).href
    .replace(/^https:\/\//, 'http://')

  root._attachments = {}
  root._attachments[tarballName] = {
    content_type: 'application/octet-stream',
    data: tarballData.toString('base64'),
    length: tarballData.length,
  }

  // Handle case where --provenance flag was set to true
  let transparencyLogUrl
  if (provenance === true || provenanceFile) {
    let provenanceBundle
    const subject = {
      name: npa.toPurl(spec),
      digest: { sha512: integrity.sha512[0].hexDigest() },
    }

    if (provenance === true) {
      await ensureProvenanceGeneration(registry, spec, opts)
      provenanceBundle = await generateProvenance([subject], opts)

      /* eslint-disable-next-line max-len */
      log.notice('publish', `Signed provenance statement with source and build information from ${ciInfo.name}`)

      const tlogEntry = provenanceBundle?.verificationMaterial?.tlogEntries[0]
      /* istanbul ignore else */
      if (tlogEntry) {
        transparencyLogUrl = `${TLOG_BASE_URL}?logIndex=${tlogEntry.logIndex}`
        log.notice(
          'publish',
          `Provenance statement published to transparency log: ${transparencyLogUrl}`
        )
      }
    } else {
      provenanceBundle = await verifyProvenance(subject, provenanceFile)
    }

    const serializedBundle = JSON.stringify(provenanceBundle)
    root._attachments[provenanceBundleName] = {
      content_type: provenanceBundle.mediaType,
      data: serializedBundle,
      length: serializedBundle.length,
    }
  }

  return {
    metadata: root,
    transparencyLogUrl,
  }
}

// Check that all the prereqs are met for provenance generation
const ensureProvenanceGeneration = async (registry, spec, opts) => {
  if (ciInfo.GITHUB_ACTIONS) {
    // Ensure that the GHA OIDC token is available
    if (!process.env.ACTIONS_ID_TOKEN_REQUEST_URL) {
      throw Object.assign(
        /* eslint-disable-next-line max-len */
        new Error('Provenance generation in GitHub Actions requires "write" access to the "id-token" permission'),
        { code: 'EUSAGE' }
      )
    }
  } else if (ciInfo.GITLAB) {
    // Ensure that the Sigstore OIDC token is available
    if (!process.env.SIGSTORE_ID_TOKEN) {
      throw Object.assign(
        /* eslint-disable-next-line max-len */
        new Error('Provenance generation in GitLab CI requires "SIGSTORE_ID_TOKEN" with "sigstore" audience to be present in "id_tokens". For more info see:\nhttps://docs.gitlab.com/ee/ci/secrets/id_token_authentication.html'),
        { code: 'EUSAGE' }
      )
    }
  } else {
    throw Object.assign(
      new Error('Automatic provenance generation not supported for provider: ' + ciInfo.name),
      { code: 'EUSAGE' }
    )
  }

  // Some registries (e.g. GH packages) require auth to check visibility,
  // and always return 404 when no auth is supplied. In this case we assume
  // the package is always private and require `--access public` to publish
  // with provenance.
  let visibility = { public: false }
  if (opts.access !== 'public') {
    try {
      const res = await npmFetch
        .json(`${registry}/-/package/${spec.escapedName}/visibility`, opts)
      visibility = res
    } catch (err) {
      if (err.code !== 'E404') {
        throw err
      }
    }
  }

  if (!visibility.public && opts.provenance === true && opts.access !== 'public') {
    throw Object.assign(
      /* eslint-disable-next-line max-len */
      new Error("Can't generate provenance for new or private package, you must set `access` to public."),
      { code: 'EUSAGE' }
    )
  }
}

module.exports = publish
PK~\Օ%%libnpmpublish/lib/provenance.jsnu[const sigstore = require('sigstore')
const { readFile } = require('node:fs/promises')
const ci = require('ci-info')
const { env } = process

const INTOTO_PAYLOAD_TYPE = 'application/vnd.in-toto+json'
const INTOTO_STATEMENT_V01_TYPE = 'https://in-toto.io/Statement/v0.1'
const INTOTO_STATEMENT_V1_TYPE = 'https://in-toto.io/Statement/v1'
const SLSA_PREDICATE_V02_TYPE = 'https://slsa.dev/provenance/v0.2'
const SLSA_PREDICATE_V1_TYPE = 'https://slsa.dev/provenance/v1'

const GITHUB_BUILDER_ID_PREFIX = 'https://github.com/actions/runner'
const GITHUB_BUILD_TYPE = 'https://slsa-framework.github.io/github-actions-buildtypes/workflow/v1'

const GITLAB_BUILD_TYPE_PREFIX = 'https://github.com/npm/cli/gitlab'
const GITLAB_BUILD_TYPE_VERSION = 'v0alpha1'

const generateProvenance = async (subject, opts) => {
  let payload
  if (ci.GITHUB_ACTIONS) {
    /* istanbul ignore next - not covering missing env var case */
    const relativeRef = (env.GITHUB_WORKFLOW_REF || '').replace(env.GITHUB_REPOSITORY + '/', '')
    const delimiterIndex = relativeRef.indexOf('@')
    const workflowPath = relativeRef.slice(0, delimiterIndex)
    const workflowRef = relativeRef.slice(delimiterIndex + 1)

    payload = {
      _type: INTOTO_STATEMENT_V1_TYPE,
      subject,
      predicateType: SLSA_PREDICATE_V1_TYPE,
      predicate: {
        buildDefinition: {
          buildType: GITHUB_BUILD_TYPE,
          externalParameters: {
            workflow: {
              ref: workflowRef,
              repository: `${env.GITHUB_SERVER_URL}/${env.GITHUB_REPOSITORY}`,
              path: workflowPath,
            },
          },
          internalParameters: {
            github: {
              event_name: env.GITHUB_EVENT_NAME,
              repository_id: env.GITHUB_REPOSITORY_ID,
              repository_owner_id: env.GITHUB_REPOSITORY_OWNER_ID,
            },
          },
          resolvedDependencies: [
            {
              uri: `git+${env.GITHUB_SERVER_URL}/${env.GITHUB_REPOSITORY}@${env.GITHUB_REF}`,
              digest: {
                gitCommit: env.GITHUB_SHA,
              },
            },
          ],
        },
        runDetails: {
          builder: { id: `${GITHUB_BUILDER_ID_PREFIX}/${env.RUNNER_ENVIRONMENT}` },
          metadata: {
            /* eslint-disable-next-line max-len */
            invocationId: `${env.GITHUB_SERVER_URL}/${env.GITHUB_REPOSITORY}/actions/runs/${env.GITHUB_RUN_ID}/attempts/${env.GITHUB_RUN_ATTEMPT}`,
          },
        },
      },
    }
  }
  if (ci.GITLAB) {
    payload = {
      _type: INTOTO_STATEMENT_V01_TYPE,
      subject,
      predicateType: SLSA_PREDICATE_V02_TYPE,
      predicate: {
        buildType: `${GITLAB_BUILD_TYPE_PREFIX}/${GITLAB_BUILD_TYPE_VERSION}`,
        builder: { id: `${env.CI_PROJECT_URL}/-/runners/${env.CI_RUNNER_ID}` },
        invocation: {
          configSource: {
            uri: `git+${env.CI_PROJECT_URL}`,
            digest: {
              sha1: env.CI_COMMIT_SHA,
            },
            entryPoint: env.CI_JOB_NAME,
          },
          parameters: {
            CI: env.CI,
            CI_API_GRAPHQL_URL: env.CI_API_GRAPHQL_URL,
            CI_API_V4_URL: env.CI_API_V4_URL,
            CI_BUILD_BEFORE_SHA: env.CI_BUILD_BEFORE_SHA,
            CI_BUILD_ID: env.CI_BUILD_ID,
            CI_BUILD_NAME: env.CI_BUILD_NAME,
            CI_BUILD_REF: env.CI_BUILD_REF,
            CI_BUILD_REF_NAME: env.CI_BUILD_REF_NAME,
            CI_BUILD_REF_SLUG: env.CI_BUILD_REF_SLUG,
            CI_BUILD_STAGE: env.CI_BUILD_STAGE,
            CI_COMMIT_BEFORE_SHA: env.CI_COMMIT_BEFORE_SHA,
            CI_COMMIT_BRANCH: env.CI_COMMIT_BRANCH,
            CI_COMMIT_REF_NAME: env.CI_COMMIT_REF_NAME,
            CI_COMMIT_REF_PROTECTED: env.CI_COMMIT_REF_PROTECTED,
            CI_COMMIT_REF_SLUG: env.CI_COMMIT_REF_SLUG,
            CI_COMMIT_SHA: env.CI_COMMIT_SHA,
            CI_COMMIT_SHORT_SHA: env.CI_COMMIT_SHORT_SHA,
            CI_COMMIT_TIMESTAMP: env.CI_COMMIT_TIMESTAMP,
            CI_COMMIT_TITLE: env.CI_COMMIT_TITLE,
            CI_CONFIG_PATH: env.CI_CONFIG_PATH,
            CI_DEFAULT_BRANCH: env.CI_DEFAULT_BRANCH,
            CI_DEPENDENCY_PROXY_DIRECT_GROUP_IMAGE_PREFIX:
              env.CI_DEPENDENCY_PROXY_DIRECT_GROUP_IMAGE_PREFIX,
            CI_DEPENDENCY_PROXY_GROUP_IMAGE_PREFIX: env.CI_DEPENDENCY_PROXY_GROUP_IMAGE_PREFIX,
            CI_DEPENDENCY_PROXY_SERVER: env.CI_DEPENDENCY_PROXY_SERVER,
            CI_DEPENDENCY_PROXY_USER: env.CI_DEPENDENCY_PROXY_USER,
            CI_JOB_ID: env.CI_JOB_ID,
            CI_JOB_NAME: env.CI_JOB_NAME,
            CI_JOB_NAME_SLUG: env.CI_JOB_NAME_SLUG,
            CI_JOB_STAGE: env.CI_JOB_STAGE,
            CI_JOB_STARTED_AT: env.CI_JOB_STARTED_AT,
            CI_JOB_URL: env.CI_JOB_URL,
            CI_NODE_TOTAL: env.CI_NODE_TOTAL,
            CI_PAGES_DOMAIN: env.CI_PAGES_DOMAIN,
            CI_PAGES_URL: env.CI_PAGES_URL,
            CI_PIPELINE_CREATED_AT: env.CI_PIPELINE_CREATED_AT,
            CI_PIPELINE_ID: env.CI_PIPELINE_ID,
            CI_PIPELINE_IID: env.CI_PIPELINE_IID,
            CI_PIPELINE_SOURCE: env.CI_PIPELINE_SOURCE,
            CI_PIPELINE_URL: env.CI_PIPELINE_URL,
            CI_PROJECT_CLASSIFICATION_LABEL: env.CI_PROJECT_CLASSIFICATION_LABEL,
            CI_PROJECT_DESCRIPTION: env.CI_PROJECT_DESCRIPTION,
            CI_PROJECT_ID: env.CI_PROJECT_ID,
            CI_PROJECT_NAME: env.CI_PROJECT_NAME,
            CI_PROJECT_NAMESPACE: env.CI_PROJECT_NAMESPACE,
            CI_PROJECT_NAMESPACE_ID: env.CI_PROJECT_NAMESPACE_ID,
            CI_PROJECT_PATH: env.CI_PROJECT_PATH,
            CI_PROJECT_PATH_SLUG: env.CI_PROJECT_PATH_SLUG,
            CI_PROJECT_REPOSITORY_LANGUAGES: env.CI_PROJECT_REPOSITORY_LANGUAGES,
            CI_PROJECT_ROOT_NAMESPACE: env.CI_PROJECT_ROOT_NAMESPACE,
            CI_PROJECT_TITLE: env.CI_PROJECT_TITLE,
            CI_PROJECT_URL: env.CI_PROJECT_URL,
            CI_PROJECT_VISIBILITY: env.CI_PROJECT_VISIBILITY,
            CI_REGISTRY: env.CI_REGISTRY,
            CI_REGISTRY_IMAGE: env.CI_REGISTRY_IMAGE,
            CI_REGISTRY_USER: env.CI_REGISTRY_USER,
            CI_RUNNER_DESCRIPTION: env.CI_RUNNER_DESCRIPTION,
            CI_RUNNER_ID: env.CI_RUNNER_ID,
            CI_RUNNER_TAGS: env.CI_RUNNER_TAGS,
            CI_SERVER_HOST: env.CI_SERVER_HOST,
            CI_SERVER_NAME: env.CI_SERVER_NAME,
            CI_SERVER_PORT: env.CI_SERVER_PORT,
            CI_SERVER_PROTOCOL: env.CI_SERVER_PROTOCOL,
            CI_SERVER_REVISION: env.CI_SERVER_REVISION,
            CI_SERVER_SHELL_SSH_HOST: env.CI_SERVER_SHELL_SSH_HOST,
            CI_SERVER_SHELL_SSH_PORT: env.CI_SERVER_SHELL_SSH_PORT,
            CI_SERVER_URL: env.CI_SERVER_URL,
            CI_SERVER_VERSION: env.CI_SERVER_VERSION,
            CI_SERVER_VERSION_MAJOR: env.CI_SERVER_VERSION_MAJOR,
            CI_SERVER_VERSION_MINOR: env.CI_SERVER_VERSION_MINOR,
            CI_SERVER_VERSION_PATCH: env.CI_SERVER_VERSION_PATCH,
            CI_TEMPLATE_REGISTRY_HOST: env.CI_TEMPLATE_REGISTRY_HOST,
            GITLAB_CI: env.GITLAB_CI,
            GITLAB_FEATURES: env.GITLAB_FEATURES,
            GITLAB_USER_ID: env.GITLAB_USER_ID,
            GITLAB_USER_LOGIN: env.GITLAB_USER_LOGIN,
            RUNNER_GENERATE_ARTIFACTS_METADATA: env.RUNNER_GENERATE_ARTIFACTS_METADATA,
          },
          environment: {
            name: env.CI_RUNNER_DESCRIPTION,
            architecture: env.CI_RUNNER_EXECUTABLE_ARCH,
            server: env.CI_SERVER_URL,
            project: env.CI_PROJECT_PATH,
            job: {
              id: env.CI_JOB_ID,
            },
            pipeline: {
              id: env.CI_PIPELINE_ID,
              ref: env.CI_CONFIG_PATH,
            },
          },
        },
        metadata: {
          buildInvocationId: `${env.CI_JOB_URL}`,
          completeness: {
            parameters: true,
            environment: true,
            materials: false,
          },
          reproducible: false,
        },
        materials: [
          {
            uri: `git+${env.CI_PROJECT_URL}`,
            digest: {
              sha1: env.CI_COMMIT_SHA,
            },
          },
        ],
      },
    }
  }
  return sigstore.attest(Buffer.from(JSON.stringify(payload)), INTOTO_PAYLOAD_TYPE, opts)
}

const verifyProvenance = async (subject, provenancePath) => {
  let provenanceBundle
  try {
    provenanceBundle = JSON.parse(await readFile(provenancePath))
  } catch (err) {
    err.message = `Invalid provenance provided: ${err.message}`
    throw err
  }

  const payload = extractProvenance(provenanceBundle)
  if (!payload.subject || !payload.subject.length) {
    throw new Error('No subject found in sigstore bundle payload')
  }
  if (payload.subject.length > 1) {
    throw new Error('Found more than one subject in the sigstore bundle payload')
  }

  const bundleSubject = payload.subject[0]
  if (subject.name !== bundleSubject.name) {
    throw new Error(
      `Provenance subject ${bundleSubject.name} does not match the package: ${subject.name}`
    )
  }
  if (subject.digest.sha512 !== bundleSubject.digest.sha512) {
    throw new Error('Provenance subject digest does not match the package')
  }

  await sigstore.verify(provenanceBundle)
  return provenanceBundle
}

const extractProvenance = (bundle) => {
  if (!bundle?.dsseEnvelope?.payload) {
    throw new Error('No dsseEnvelope with payload found in sigstore bundle')
  }
  try {
    return JSON.parse(Buffer.from(bundle.dsseEnvelope.payload, 'base64').toString('utf8'))
  } catch (err) {
    err.message = `Failed to parse payload from dsseEnvelope: ${err.message}`
    throw err
  }
}

module.exports = {
  generateProvenance,
  verifyProvenance,
}
PK~\gXlibnpmpublish/LICENSEnu[Copyright npm, Inc

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
PK~\u3dlibnpmpublish/README.mdnu[# libnpmpublish

[![npm version](https://img.shields.io/npm/v/libnpmpublish.svg)](https://npm.im/libnpmpublish)
[![license](https://img.shields.io/npm/l/libnpmpublish.svg)](https://npm.im/libnpmpublish)
[![CI - libnpmpublish](https://github.com/npm/cli/actions/workflows/ci-libnpmpublish.yml/badge.svg)](https://github.com/npm/cli/actions/workflows/ci-libnpmpublish.yml)

[`libnpmpublish`](https://github.com/npm/libnpmpublish) is a Node.js
library for programmatically publishing and unpublishing npm packages. Give
it a manifest as an object and a tarball as a Buffer, and it'll put them on
the registry for you.

## Table of Contents

* [Example](#example)
* [Install](#install)
* [API](#api)
  * [publish/unpublish opts](#opts)
  * [`publish()`](#publish)
  * [`unpublish()`](#unpublish)

## Example

```js
const { publish, unpublish } = require('libnpmpublish')
```

## Install

`$ npm install libnpmpublish`

### API

####  `opts` for `libnpmpublish` commands

`libnpmpublish` uses
[`npm-registry-fetch`](https://npm.im/npm-registry-fetch).  Most options
are passed through directly to that library, so please refer to [its own
`opts` documentation](http://npm.im/npm-registry-fetch#fetch-options) for
options that can be passed in.

A couple of options of note:

* `opts.defaultTag` - registers the published package with the given tag,
  defaults to `latest`.

* `opts.access` - tells the registry whether this package should be
  published as `public` or `restricted`. Only applies to scoped
  packages.  Defaults to `public`.

* `opts.token` - can be passed in and will be used as the authentication
  token for the registry. For other ways to pass in auth details, see the
  n-r-f docs.

* `opts.provenance` - when running in a supported CI environment, will trigger
  the generation of a signed provenance statement to be published alongside
  the package. Mutually exclusive with the `provenanceFile` option.

* `opts.provenanceFile` - specifies the path to an externally-generated
  provenance statement to be published alongside the package. Mutually
  exclusive with the `provenance` option. The specified file should be a
  [Sigstore Bundle](https://github.com/sigstore/protobuf-specs/blob/main/protos/sigstore_bundle.proto)
  containing a [DSSE](https://github.com/secure-systems-lab/dsse)-packaged
  provenance statement.

####  `> libpub.publish(manifest, tarData, [opts]) -> Promise`

Sends the package represented by the `manifest` and `tarData` to the
configured registry.

`manifest` should be the parsed `package.json` for the package being
published (which can also be the manifest pulled from a packument, a git
repo, tarball, etc.)

`tarData` is a `Buffer` of the tarball being published.

If `opts.npmVersion` is passed in, it will be used as the `_npmVersion`
field in the outgoing packument.  You may put your own user-agent string in
there to identify your publishes.

If `opts.algorithms` is passed in, it should be an array of hashing
algorithms to generate `integrity` hashes for. The default is `['sha512']`,
which means you end up with `dist.integrity = 'sha512-deadbeefbadc0ffee'`.
Any algorithm supported by your current node version is allowed -- npm
clients that do not support those algorithms will simply ignore the
unsupported hashes.

##### Example

```js
// note that pacote.manifest() and pacote.tarball() can also take
// any spec that npm can install.  a folder shown here, since that's
// far and away the most common use case.
const path = '/a/path/to/your/source/code'
const pacote = require('pacote') // see: http://npm.im/pacote
const manifest = await pacote.manifest(path)
const tarData = await pacote.tarball(path)
await libpub.publish(manifest, tarData, {
  npmVersion: 'my-pub-script@1.0.2',
  token: 'my-auth-token-here'
}, opts)
// Package has been published to the npm registry.
```

####  `> libpub.unpublish(spec, [opts]) -> Promise`

Unpublishes `spec` from the appropriate registry. The registry in question may
have its own limitations on unpublishing.

`spec` should be either a string, or a valid
[`npm-package-arg`](https://npm.im/npm-package-arg) parsed spec object. For
legacy compatibility reasons, only `tag` and `version` specs will work as
expected. `range` specs will fail silently in most cases.

##### Example

```js
await libpub.unpublish('lodash', { token: 'i-am-the-worst'})
//
// `lodash` has now been unpublished, along with all its versions
```
PK~\V&&eastasianwidth/package.jsonnu[{
  "_id": "eastasianwidth@0.2.0",
  "_inBundle": true,
  "_location": "/npm/eastasianwidth",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm/@isaacs/cliui/string-width",
    "/npm/wrap-ansi/string-width"
  ],
  "author": {
    "name": "Masaki Komagata"
  },
  "bugs": {
    "url": "https://github.com/komagata/eastasianwidth/issues"
  },
  "description": "Get East Asian Width from a character.",
  "devDependencies": {
    "mocha": "~1.9.0"
  },
  "files": [
    "eastasianwidth.js"
  ],
  "homepage": "https://github.com/komagata/eastasianwidth#readme",
  "license": "MIT",
  "main": "eastasianwidth.js",
  "name": "eastasianwidth",
  "repository": {
    "type": "git",
    "url": "git://github.com/komagata/eastasianwidth.git"
  },
  "scripts": {
    "test": "mocha"
  },
  "version": "0.2.0"
}
PK~\!3A#/#/ eastasianwidth/eastasianwidth.jsnu[var eaw = {};

if ('undefined' == typeof module) {
  window.eastasianwidth = eaw;
} else {
  module.exports = eaw;
}

eaw.eastAsianWidth = function(character) {
  var x = character.charCodeAt(0);
  var y = (character.length == 2) ? character.charCodeAt(1) : 0;
  var codePoint = x;
  if ((0xD800 <= x && x <= 0xDBFF) && (0xDC00 <= y && y <= 0xDFFF)) {
    x &= 0x3FF;
    y &= 0x3FF;
    codePoint = (x << 10) | y;
    codePoint += 0x10000;
  }

  if ((0x3000 == codePoint) ||
      (0xFF01 <= codePoint && codePoint <= 0xFF60) ||
      (0xFFE0 <= codePoint && codePoint <= 0xFFE6)) {
    return 'F';
  }
  if ((0x20A9 == codePoint) ||
      (0xFF61 <= codePoint && codePoint <= 0xFFBE) ||
      (0xFFC2 <= codePoint && codePoint <= 0xFFC7) ||
      (0xFFCA <= codePoint && codePoint <= 0xFFCF) ||
      (0xFFD2 <= codePoint && codePoint <= 0xFFD7) ||
      (0xFFDA <= codePoint && codePoint <= 0xFFDC) ||
      (0xFFE8 <= codePoint && codePoint <= 0xFFEE)) {
    return 'H';
  }
  if ((0x1100 <= codePoint && codePoint <= 0x115F) ||
      (0x11A3 <= codePoint && codePoint <= 0x11A7) ||
      (0x11FA <= codePoint && codePoint <= 0x11FF) ||
      (0x2329 <= codePoint && codePoint <= 0x232A) ||
      (0x2E80 <= codePoint && codePoint <= 0x2E99) ||
      (0x2E9B <= codePoint && codePoint <= 0x2EF3) ||
      (0x2F00 <= codePoint && codePoint <= 0x2FD5) ||
      (0x2FF0 <= codePoint && codePoint <= 0x2FFB) ||
      (0x3001 <= codePoint && codePoint <= 0x303E) ||
      (0x3041 <= codePoint && codePoint <= 0x3096) ||
      (0x3099 <= codePoint && codePoint <= 0x30FF) ||
      (0x3105 <= codePoint && codePoint <= 0x312D) ||
      (0x3131 <= codePoint && codePoint <= 0x318E) ||
      (0x3190 <= codePoint && codePoint <= 0x31BA) ||
      (0x31C0 <= codePoint && codePoint <= 0x31E3) ||
      (0x31F0 <= codePoint && codePoint <= 0x321E) ||
      (0x3220 <= codePoint && codePoint <= 0x3247) ||
      (0x3250 <= codePoint && codePoint <= 0x32FE) ||
      (0x3300 <= codePoint && codePoint <= 0x4DBF) ||
      (0x4E00 <= codePoint && codePoint <= 0xA48C) ||
      (0xA490 <= codePoint && codePoint <= 0xA4C6) ||
      (0xA960 <= codePoint && codePoint <= 0xA97C) ||
      (0xAC00 <= codePoint && codePoint <= 0xD7A3) ||
      (0xD7B0 <= codePoint && codePoint <= 0xD7C6) ||
      (0xD7CB <= codePoint && codePoint <= 0xD7FB) ||
      (0xF900 <= codePoint && codePoint <= 0xFAFF) ||
      (0xFE10 <= codePoint && codePoint <= 0xFE19) ||
      (0xFE30 <= codePoint && codePoint <= 0xFE52) ||
      (0xFE54 <= codePoint && codePoint <= 0xFE66) ||
      (0xFE68 <= codePoint && codePoint <= 0xFE6B) ||
      (0x1B000 <= codePoint && codePoint <= 0x1B001) ||
      (0x1F200 <= codePoint && codePoint <= 0x1F202) ||
      (0x1F210 <= codePoint && codePoint <= 0x1F23A) ||
      (0x1F240 <= codePoint && codePoint <= 0x1F248) ||
      (0x1F250 <= codePoint && codePoint <= 0x1F251) ||
      (0x20000 <= codePoint && codePoint <= 0x2F73F) ||
      (0x2B740 <= codePoint && codePoint <= 0x2FFFD) ||
      (0x30000 <= codePoint && codePoint <= 0x3FFFD)) {
    return 'W';
  }
  if ((0x0020 <= codePoint && codePoint <= 0x007E) ||
      (0x00A2 <= codePoint && codePoint <= 0x00A3) ||
      (0x00A5 <= codePoint && codePoint <= 0x00A6) ||
      (0x00AC == codePoint) ||
      (0x00AF == codePoint) ||
      (0x27E6 <= codePoint && codePoint <= 0x27ED) ||
      (0x2985 <= codePoint && codePoint <= 0x2986)) {
    return 'Na';
  }
  if ((0x00A1 == codePoint) ||
      (0x00A4 == codePoint) ||
      (0x00A7 <= codePoint && codePoint <= 0x00A8) ||
      (0x00AA == codePoint) ||
      (0x00AD <= codePoint && codePoint <= 0x00AE) ||
      (0x00B0 <= codePoint && codePoint <= 0x00B4) ||
      (0x00B6 <= codePoint && codePoint <= 0x00BA) ||
      (0x00BC <= codePoint && codePoint <= 0x00BF) ||
      (0x00C6 == codePoint) ||
      (0x00D0 == codePoint) ||
      (0x00D7 <= codePoint && codePoint <= 0x00D8) ||
      (0x00DE <= codePoint && codePoint <= 0x00E1) ||
      (0x00E6 == codePoint) ||
      (0x00E8 <= codePoint && codePoint <= 0x00EA) ||
      (0x00EC <= codePoint && codePoint <= 0x00ED) ||
      (0x00F0 == codePoint) ||
      (0x00F2 <= codePoint && codePoint <= 0x00F3) ||
      (0x00F7 <= codePoint && codePoint <= 0x00FA) ||
      (0x00FC == codePoint) ||
      (0x00FE == codePoint) ||
      (0x0101 == codePoint) ||
      (0x0111 == codePoint) ||
      (0x0113 == codePoint) ||
      (0x011B == codePoint) ||
      (0x0126 <= codePoint && codePoint <= 0x0127) ||
      (0x012B == codePoint) ||
      (0x0131 <= codePoint && codePoint <= 0x0133) ||
      (0x0138 == codePoint) ||
      (0x013F <= codePoint && codePoint <= 0x0142) ||
      (0x0144 == codePoint) ||
      (0x0148 <= codePoint && codePoint <= 0x014B) ||
      (0x014D == codePoint) ||
      (0x0152 <= codePoint && codePoint <= 0x0153) ||
      (0x0166 <= codePoint && codePoint <= 0x0167) ||
      (0x016B == codePoint) ||
      (0x01CE == codePoint) ||
      (0x01D0 == codePoint) ||
      (0x01D2 == codePoint) ||
      (0x01D4 == codePoint) ||
      (0x01D6 == codePoint) ||
      (0x01D8 == codePoint) ||
      (0x01DA == codePoint) ||
      (0x01DC == codePoint) ||
      (0x0251 == codePoint) ||
      (0x0261 == codePoint) ||
      (0x02C4 == codePoint) ||
      (0x02C7 == codePoint) ||
      (0x02C9 <= codePoint && codePoint <= 0x02CB) ||
      (0x02CD == codePoint) ||
      (0x02D0 == codePoint) ||
      (0x02D8 <= codePoint && codePoint <= 0x02DB) ||
      (0x02DD == codePoint) ||
      (0x02DF == codePoint) ||
      (0x0300 <= codePoint && codePoint <= 0x036F) ||
      (0x0391 <= codePoint && codePoint <= 0x03A1) ||
      (0x03A3 <= codePoint && codePoint <= 0x03A9) ||
      (0x03B1 <= codePoint && codePoint <= 0x03C1) ||
      (0x03C3 <= codePoint && codePoint <= 0x03C9) ||
      (0x0401 == codePoint) ||
      (0x0410 <= codePoint && codePoint <= 0x044F) ||
      (0x0451 == codePoint) ||
      (0x2010 == codePoint) ||
      (0x2013 <= codePoint && codePoint <= 0x2016) ||
      (0x2018 <= codePoint && codePoint <= 0x2019) ||
      (0x201C <= codePoint && codePoint <= 0x201D) ||
      (0x2020 <= codePoint && codePoint <= 0x2022) ||
      (0x2024 <= codePoint && codePoint <= 0x2027) ||
      (0x2030 == codePoint) ||
      (0x2032 <= codePoint && codePoint <= 0x2033) ||
      (0x2035 == codePoint) ||
      (0x203B == codePoint) ||
      (0x203E == codePoint) ||
      (0x2074 == codePoint) ||
      (0x207F == codePoint) ||
      (0x2081 <= codePoint && codePoint <= 0x2084) ||
      (0x20AC == codePoint) ||
      (0x2103 == codePoint) ||
      (0x2105 == codePoint) ||
      (0x2109 == codePoint) ||
      (0x2113 == codePoint) ||
      (0x2116 == codePoint) ||
      (0x2121 <= codePoint && codePoint <= 0x2122) ||
      (0x2126 == codePoint) ||
      (0x212B == codePoint) ||
      (0x2153 <= codePoint && codePoint <= 0x2154) ||
      (0x215B <= codePoint && codePoint <= 0x215E) ||
      (0x2160 <= codePoint && codePoint <= 0x216B) ||
      (0x2170 <= codePoint && codePoint <= 0x2179) ||
      (0x2189 == codePoint) ||
      (0x2190 <= codePoint && codePoint <= 0x2199) ||
      (0x21B8 <= codePoint && codePoint <= 0x21B9) ||
      (0x21D2 == codePoint) ||
      (0x21D4 == codePoint) ||
      (0x21E7 == codePoint) ||
      (0x2200 == codePoint) ||
      (0x2202 <= codePoint && codePoint <= 0x2203) ||
      (0x2207 <= codePoint && codePoint <= 0x2208) ||
      (0x220B == codePoint) ||
      (0x220F == codePoint) ||
      (0x2211 == codePoint) ||
      (0x2215 == codePoint) ||
      (0x221A == codePoint) ||
      (0x221D <= codePoint && codePoint <= 0x2220) ||
      (0x2223 == codePoint) ||
      (0x2225 == codePoint) ||
      (0x2227 <= codePoint && codePoint <= 0x222C) ||
      (0x222E == codePoint) ||
      (0x2234 <= codePoint && codePoint <= 0x2237) ||
      (0x223C <= codePoint && codePoint <= 0x223D) ||
      (0x2248 == codePoint) ||
      (0x224C == codePoint) ||
      (0x2252 == codePoint) ||
      (0x2260 <= codePoint && codePoint <= 0x2261) ||
      (0x2264 <= codePoint && codePoint <= 0x2267) ||
      (0x226A <= codePoint && codePoint <= 0x226B) ||
      (0x226E <= codePoint && codePoint <= 0x226F) ||
      (0x2282 <= codePoint && codePoint <= 0x2283) ||
      (0x2286 <= codePoint && codePoint <= 0x2287) ||
      (0x2295 == codePoint) ||
      (0x2299 == codePoint) ||
      (0x22A5 == codePoint) ||
      (0x22BF == codePoint) ||
      (0x2312 == codePoint) ||
      (0x2460 <= codePoint && codePoint <= 0x24E9) ||
      (0x24EB <= codePoint && codePoint <= 0x254B) ||
      (0x2550 <= codePoint && codePoint <= 0x2573) ||
      (0x2580 <= codePoint && codePoint <= 0x258F) ||
      (0x2592 <= codePoint && codePoint <= 0x2595) ||
      (0x25A0 <= codePoint && codePoint <= 0x25A1) ||
      (0x25A3 <= codePoint && codePoint <= 0x25A9) ||
      (0x25B2 <= codePoint && codePoint <= 0x25B3) ||
      (0x25B6 <= codePoint && codePoint <= 0x25B7) ||
      (0x25BC <= codePoint && codePoint <= 0x25BD) ||
      (0x25C0 <= codePoint && codePoint <= 0x25C1) ||
      (0x25C6 <= codePoint && codePoint <= 0x25C8) ||
      (0x25CB == codePoint) ||
      (0x25CE <= codePoint && codePoint <= 0x25D1) ||
      (0x25E2 <= codePoint && codePoint <= 0x25E5) ||
      (0x25EF == codePoint) ||
      (0x2605 <= codePoint && codePoint <= 0x2606) ||
      (0x2609 == codePoint) ||
      (0x260E <= codePoint && codePoint <= 0x260F) ||
      (0x2614 <= codePoint && codePoint <= 0x2615) ||
      (0x261C == codePoint) ||
      (0x261E == codePoint) ||
      (0x2640 == codePoint) ||
      (0x2642 == codePoint) ||
      (0x2660 <= codePoint && codePoint <= 0x2661) ||
      (0x2663 <= codePoint && codePoint <= 0x2665) ||
      (0x2667 <= codePoint && codePoint <= 0x266A) ||
      (0x266C <= codePoint && codePoint <= 0x266D) ||
      (0x266F == codePoint) ||
      (0x269E <= codePoint && codePoint <= 0x269F) ||
      (0x26BE <= codePoint && codePoint <= 0x26BF) ||
      (0x26C4 <= codePoint && codePoint <= 0x26CD) ||
      (0x26CF <= codePoint && codePoint <= 0x26E1) ||
      (0x26E3 == codePoint) ||
      (0x26E8 <= codePoint && codePoint <= 0x26FF) ||
      (0x273D == codePoint) ||
      (0x2757 == codePoint) ||
      (0x2776 <= codePoint && codePoint <= 0x277F) ||
      (0x2B55 <= codePoint && codePoint <= 0x2B59) ||
      (0x3248 <= codePoint && codePoint <= 0x324F) ||
      (0xE000 <= codePoint && codePoint <= 0xF8FF) ||
      (0xFE00 <= codePoint && codePoint <= 0xFE0F) ||
      (0xFFFD == codePoint) ||
      (0x1F100 <= codePoint && codePoint <= 0x1F10A) ||
      (0x1F110 <= codePoint && codePoint <= 0x1F12D) ||
      (0x1F130 <= codePoint && codePoint <= 0x1F169) ||
      (0x1F170 <= codePoint && codePoint <= 0x1F19A) ||
      (0xE0100 <= codePoint && codePoint <= 0xE01EF) ||
      (0xF0000 <= codePoint && codePoint <= 0xFFFFD) ||
      (0x100000 <= codePoint && codePoint <= 0x10FFFD)) {
    return 'A';
  }

  return 'N';
};

eaw.characterLength = function(character) {
  var code = this.eastAsianWidth(character);
  if (code == 'F' || code == 'W' || code == 'A') {
    return 2;
  } else {
    return 1;
  }
};

// Split a string considering surrogate-pairs.
function stringToArray(string) {
  return string.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g) || [];
}

eaw.length = function(string) {
  var characters = stringToArray(string);
  var len = 0;
  for (var i = 0; i < characters.length; i++) {
    len = len + this.characterLength(characters[i]);
  }
  return len;
};

eaw.slice = function(text, start, end) {
  textLen = eaw.length(text)
  start = start ? start : 0;
  end = end ? end : 1;
  if (start < 0) {
      start = textLen + start;
  }
  if (end < 0) {
      end = textLen + end;
  }
  var result = '';
  var eawLen = 0;
  var chars = stringToArray(text);
  for (var i = 0; i < chars.length; i++) {
    var char = chars[i];
    var charLen = eaw.length(char);
    if (eawLen >= start - (charLen == 2 ? 1 : 0)) {
        if (eawLen + charLen <= end) {
            result += char;
        } else {
            break;
        }
    }
    eawLen += charLen;
  }
  return result;
};
PK~\retry/package.jsonnu[{
  "_id": "retry@0.12.0",
  "_inBundle": true,
  "_location": "/npm/retry",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm/promise-retry"
  ],
  "author": {
    "name": "Tim Koschützki",
    "email": "tim@debuggable.com",
    "url": "http://debuggable.com/"
  },
  "bugs": {
    "url": "https://github.com/tim-kos/node-retry/issues"
  },
  "dependencies": {},
  "description": "Abstraction for exponential and custom retry strategies for failed operations.",
  "devDependencies": {
    "fake": "0.2.0",
    "istanbul": "^0.4.5",
    "tape": "^4.8.0"
  },
  "directories": {
    "lib": "./lib"
  },
  "engines": {
    "node": ">= 4"
  },
  "homepage": "https://github.com/tim-kos/node-retry",
  "license": "MIT",
  "main": "index",
  "name": "retry",
  "repository": {
    "type": "git",
    "url": "git://github.com/tim-kos/node-retry.git"
  },
  "scripts": {
    "release": "npm version ${SEMANTIC:-patch} -m \"Release %s\" && git push && git push --tags && npm publish",
    "release:major": "env SEMANTIC=major npm run release",
    "release:minor": "env SEMANTIC=minor npm run release",
    "release:patch": "env SEMANTIC=patch npm run release",
    "test": "istanbul cover ./node_modules/tape/bin/tape ./test/integration/*.js"
  },
  "version": "0.12.0"
}
PK~\9IIretry/lib/retry_operation.jsnu[function RetryOperation(timeouts, options) {
  // Compatibility for the old (timeouts, retryForever) signature
  if (typeof options === 'boolean') {
    options = { forever: options };
  }

  this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
  this._timeouts = timeouts;
  this._options = options || {};
  this._maxRetryTime = options && options.maxRetryTime || Infinity;
  this._fn = null;
  this._errors = [];
  this._attempts = 1;
  this._operationTimeout = null;
  this._operationTimeoutCb = null;
  this._timeout = null;
  this._operationStart = null;

  if (this._options.forever) {
    this._cachedTimeouts = this._timeouts.slice(0);
  }
}
module.exports = RetryOperation;

RetryOperation.prototype.reset = function() {
  this._attempts = 1;
  this._timeouts = this._originalTimeouts;
}

RetryOperation.prototype.stop = function() {
  if (this._timeout) {
    clearTimeout(this._timeout);
  }

  this._timeouts       = [];
  this._cachedTimeouts = null;
};

RetryOperation.prototype.retry = function(err) {
  if (this._timeout) {
    clearTimeout(this._timeout);
  }

  if (!err) {
    return false;
  }
  var currentTime = new Date().getTime();
  if (err && currentTime - this._operationStart >= this._maxRetryTime) {
    this._errors.unshift(new Error('RetryOperation timeout occurred'));
    return false;
  }

  this._errors.push(err);

  var timeout = this._timeouts.shift();
  if (timeout === undefined) {
    if (this._cachedTimeouts) {
      // retry forever, only keep last error
      this._errors.splice(this._errors.length - 1, this._errors.length);
      this._timeouts = this._cachedTimeouts.slice(0);
      timeout = this._timeouts.shift();
    } else {
      return false;
    }
  }

  var self = this;
  var timer = setTimeout(function() {
    self._attempts++;

    if (self._operationTimeoutCb) {
      self._timeout = setTimeout(function() {
        self._operationTimeoutCb(self._attempts);
      }, self._operationTimeout);

      if (self._options.unref) {
          self._timeout.unref();
      }
    }

    self._fn(self._attempts);
  }, timeout);

  if (this._options.unref) {
      timer.unref();
  }

  return true;
};

RetryOperation.prototype.attempt = function(fn, timeoutOps) {
  this._fn = fn;

  if (timeoutOps) {
    if (timeoutOps.timeout) {
      this._operationTimeout = timeoutOps.timeout;
    }
    if (timeoutOps.cb) {
      this._operationTimeoutCb = timeoutOps.cb;
    }
  }

  var self = this;
  if (this._operationTimeoutCb) {
    this._timeout = setTimeout(function() {
      self._operationTimeoutCb();
    }, self._operationTimeout);
  }

  this._operationStart = new Date().getTime();

  this._fn(this._attempts);
};

RetryOperation.prototype.try = function(fn) {
  console.log('Using RetryOperation.try() is deprecated');
  this.attempt(fn);
};

RetryOperation.prototype.start = function(fn) {
  console.log('Using RetryOperation.start() is deprecated');
  this.attempt(fn);
};

RetryOperation.prototype.start = RetryOperation.prototype.try;

RetryOperation.prototype.errors = function() {
  return this._errors;
};

RetryOperation.prototype.attempts = function() {
  return this._attempts;
};

RetryOperation.prototype.mainError = function() {
  if (this._errors.length === 0) {
    return null;
  }

  var counts = {};
  var mainError = null;
  var mainErrorCount = 0;

  for (var i = 0; i < this._errors.length; i++) {
    var error = this._errors[i];
    var message = error.message;
    var count = (counts[message] || 0) + 1;

    counts[message] = count;

    if (count >= mainErrorCount) {
      mainError = error;
      mainErrorCount = count;
    }
  }

  return mainError;
};
PK~\oqretry/lib/retry.jsnu[var RetryOperation = require('./retry_operation');

exports.operation = function(options) {
  var timeouts = exports.timeouts(options);
  return new RetryOperation(timeouts, {
      forever: options && options.forever,
      unref: options && options.unref,
      maxRetryTime: options && options.maxRetryTime
  });
};

exports.timeouts = function(options) {
  if (options instanceof Array) {
    return [].concat(options);
  }

  var opts = {
    retries: 10,
    factor: 2,
    minTimeout: 1 * 1000,
    maxTimeout: Infinity,
    randomize: false
  };
  for (var key in options) {
    opts[key] = options[key];
  }

  if (opts.minTimeout > opts.maxTimeout) {
    throw new Error('minTimeout is greater than maxTimeout');
  }

  var timeouts = [];
  for (var i = 0; i < opts.retries; i++) {
    timeouts.push(this.createTimeout(i, opts));
  }

  if (options && options.forever && !timeouts.length) {
    timeouts.push(this.createTimeout(i, opts));
  }

  // sort the array numerically ascending
  timeouts.sort(function(a,b) {
    return a - b;
  });

  return timeouts;
};

exports.createTimeout = function(attempt, opts) {
  var random = (opts.randomize)
    ? (Math.random() + 1)
    : 1;

  var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
  timeout = Math.min(timeout, opts.maxTimeout);

  return timeout;
};

exports.wrap = function(obj, options, methods) {
  if (options instanceof Array) {
    methods = options;
    options = null;
  }

  if (!methods) {
    methods = [];
    for (var key in obj) {
      if (typeof obj[key] === 'function') {
        methods.push(key);
      }
    }
  }

  for (var i = 0; i < methods.length; i++) {
    var method   = methods[i];
    var original = obj[method];

    obj[method] = function retryWrapper(original) {
      var op       = exports.operation(options);
      var args     = Array.prototype.slice.call(arguments, 1);
      var callback = args.pop();

      args.push(function(err) {
        if (op.retry(err)) {
          return;
        }
        if (err) {
          arguments[0] = op.mainError();
        }
        callback.apply(this, arguments);
      });

      op.attempt(function() {
        original.apply(obj, args);
      });
    }.bind(obj, original);
    obj[method].options = options;
  }
};
PK~\'retry/test/integration/test-timeouts.jsnu[var common = require('../common');
var assert = common.assert;
var retry = require(common.dir.lib + '/retry');

(function testDefaultValues() {
  var timeouts = retry.timeouts();

  assert.equal(timeouts.length, 10);
  assert.equal(timeouts[0], 1000);
  assert.equal(timeouts[1], 2000);
  assert.equal(timeouts[2], 4000);
})();

(function testDefaultValuesWithRandomize() {
  var minTimeout = 5000;
  var timeouts = retry.timeouts({
    minTimeout: minTimeout,
    randomize: true
  });

  assert.equal(timeouts.length, 10);
  assert.ok(timeouts[0] > minTimeout);
  assert.ok(timeouts[1] > timeouts[0]);
  assert.ok(timeouts[2] > timeouts[1]);
})();

(function testPassedTimeoutsAreUsed() {
  var timeoutsArray = [1000, 2000, 3000];
  var timeouts = retry.timeouts(timeoutsArray);
  assert.deepEqual(timeouts, timeoutsArray);
  assert.notStrictEqual(timeouts, timeoutsArray);
})();

(function testTimeoutsAreWithinBoundaries() {
  var minTimeout = 1000;
  var maxTimeout = 10000;
  var timeouts = retry.timeouts({
    minTimeout: minTimeout,
    maxTimeout: maxTimeout
  });
  for (var i = 0; i < timeouts; i++) {
    assert.ok(timeouts[i] >= minTimeout);
    assert.ok(timeouts[i] <= maxTimeout);
  }
})();

(function testTimeoutsAreIncremental() {
  var timeouts = retry.timeouts();
  var lastTimeout = timeouts[0];
  for (var i = 0; i < timeouts; i++) {
    assert.ok(timeouts[i] > lastTimeout);
    lastTimeout = timeouts[i];
  }
})();

(function testTimeoutsAreIncrementalForFactorsLessThanOne() {
  var timeouts = retry.timeouts({
    retries: 3,
    factor: 0.5
  });

  var expected = [250, 500, 1000];
  assert.deepEqual(expected, timeouts);
})();

(function testRetries() {
  var timeouts = retry.timeouts({retries: 2});
  assert.strictEqual(timeouts.length, 2);
})();
PK~\oF@"".retry/test/integration/test-retry-operation.jsnu[var common = require('../common');
var assert = common.assert;
var fake = common.fake.create();
var retry = require(common.dir.lib + '/retry');

(function testReset() {
  var error = new Error('some error');
  var operation = retry.operation([1, 2, 3]);
  var attempts = 0;

  var finalCallback = fake.callback('finalCallback');
  fake.expectAnytime(finalCallback);

  var expectedFinishes = 1;
  var finishes         = 0;

  var fn = function() {
    operation.attempt(function(currentAttempt) {
      attempts++;
      assert.equal(currentAttempt, attempts);
      if (operation.retry(error)) {
        return;
      }

      finishes++
      assert.equal(expectedFinishes, finishes);
      assert.strictEqual(attempts, 4);
      assert.strictEqual(operation.attempts(), attempts);
      assert.strictEqual(operation.mainError(), error);

      if (finishes < 2) {
        attempts = 0;
        expectedFinishes++;
        operation.reset();
        fn()
      } else {
        finalCallback();
      }
    });
  };

  fn();
})();

(function testErrors() {
  var operation = retry.operation();

  var error = new Error('some error');
  var error2 = new Error('some other error');
  operation._errors.push(error);
  operation._errors.push(error2);

  assert.deepEqual(operation.errors(), [error, error2]);
})();

(function testMainErrorReturnsMostFrequentError() {
  var operation = retry.operation();
  var error = new Error('some error');
  var error2 = new Error('some other error');

  operation._errors.push(error);
  operation._errors.push(error2);
  operation._errors.push(error);

  assert.strictEqual(operation.mainError(), error);
})();

(function testMainErrorReturnsLastErrorOnEqualCount() {
  var operation = retry.operation();
  var error = new Error('some error');
  var error2 = new Error('some other error');

  operation._errors.push(error);
  operation._errors.push(error2);

  assert.strictEqual(operation.mainError(), error2);
})();

(function testAttempt() {
  var operation = retry.operation();
  var fn = new Function();

  var timeoutOpts = {
    timeout: 1,
    cb: function() {}
  };
  operation.attempt(fn, timeoutOpts);

  assert.strictEqual(fn, operation._fn);
  assert.strictEqual(timeoutOpts.timeout, operation._operationTimeout);
  assert.strictEqual(timeoutOpts.cb, operation._operationTimeoutCb);
})();

(function testRetry() {
  var error = new Error('some error');
  var operation = retry.operation([1, 2, 3]);
  var attempts = 0;

  var finalCallback = fake.callback('finalCallback');
  fake.expectAnytime(finalCallback);

  var fn = function() {
    operation.attempt(function(currentAttempt) {
      attempts++;
      assert.equal(currentAttempt, attempts);
      if (operation.retry(error)) {
        return;
      }

      assert.strictEqual(attempts, 4);
      assert.strictEqual(operation.attempts(), attempts);
      assert.strictEqual(operation.mainError(), error);
      finalCallback();
    });
  };

  fn();
})();

(function testRetryForever() {
  var error = new Error('some error');
  var operation = retry.operation({ retries: 3, forever: true });
  var attempts = 0;

  var finalCallback = fake.callback('finalCallback');
  fake.expectAnytime(finalCallback);

  var fn = function() {
    operation.attempt(function(currentAttempt) {
      attempts++;
      assert.equal(currentAttempt, attempts);
      if (attempts !== 6 && operation.retry(error)) {
        return;
      }

      assert.strictEqual(attempts, 6);
      assert.strictEqual(operation.attempts(), attempts);
      assert.strictEqual(operation.mainError(), error);
      finalCallback();
    });
  };

  fn();
})();

(function testRetryForeverNoRetries() {
  var error = new Error('some error');
  var delay = 50
  var operation = retry.operation({
    retries: null,
    forever: true,
    minTimeout: delay,
    maxTimeout: delay
  });

  var attempts = 0;
  var startTime = new Date().getTime();

  var finalCallback = fake.callback('finalCallback');
  fake.expectAnytime(finalCallback);

  var fn = function() {
    operation.attempt(function(currentAttempt) {
      attempts++;
      assert.equal(currentAttempt, attempts);
      if (attempts !== 4 && operation.retry(error)) {
        return;
      }

      var endTime = new Date().getTime();
      var minTime = startTime + (delay * 3);
      var maxTime = minTime + 20 // add a little headroom for code execution time
      assert(endTime >= minTime)
      assert(endTime < maxTime)
      assert.strictEqual(attempts, 4);
      assert.strictEqual(operation.attempts(), attempts);
      assert.strictEqual(operation.mainError(), error);
      finalCallback();
    });
  };

  fn();
})();

(function testStop() {
  var error = new Error('some error');
  var operation = retry.operation([1, 2, 3]);
  var attempts = 0;

  var finalCallback = fake.callback('finalCallback');
  fake.expectAnytime(finalCallback);

  var fn = function() {
    operation.attempt(function(currentAttempt) {
      attempts++;
      assert.equal(currentAttempt, attempts);

      if (attempts === 2) {
        operation.stop();

        assert.strictEqual(attempts, 2);
        assert.strictEqual(operation.attempts(), attempts);
        assert.strictEqual(operation.mainError(), error);
        finalCallback();
      }

      if (operation.retry(error)) {
        return;
      }
    });
  };

  fn();
})();

(function testMaxRetryTime() {
  var error = new Error('some error');
  var maxRetryTime = 30;
  var operation = retry.operation({
      minTimeout: 1,
      maxRetryTime: maxRetryTime
  });
  var attempts = 0;

  var finalCallback = fake.callback('finalCallback');
  fake.expectAnytime(finalCallback);

  var longAsyncFunction = function (wait, callback){
    setTimeout(callback, wait);
  };

  var fn = function() {
    var startTime = new Date().getTime();
    operation.attempt(function(currentAttempt) {
      attempts++;
      assert.equal(currentAttempt, attempts);

      if (attempts !== 2) {
        if (operation.retry(error)) {
            return;
        }
      } else {
        var curTime = new Date().getTime();
        longAsyncFunction(maxRetryTime - (curTime - startTime - 1), function(){
          if (operation.retry(error)) {
            assert.fail('timeout should be occurred');
            return;
          }

          assert.strictEqual(operation.mainError(), error);
          finalCallback();
        });
      }
    });
  };

  fn();
})();
PK~\P+&retry/test/integration/test-forever.jsnu[var common = require('../common');
var assert = common.assert;
var retry = require(common.dir.lib + '/retry');

(function testForeverUsesFirstTimeout() {
  var operation = retry.operation({
    retries: 0,
    minTimeout: 100,
    maxTimeout: 100,
    forever: true
  });

  operation.attempt(function(numAttempt) {
    console.log('>numAttempt', numAttempt);
    var err = new Error("foo");
    if (numAttempt == 10) {
      operation.stop();
    }

    if (operation.retry(err)) {
      return;
    }
  });
})();
PK~\xz
z
)retry/test/integration/test-retry-wrap.jsnu[var common = require('../common');
var assert = common.assert;
var fake = common.fake.create();
var retry = require(common.dir.lib + '/retry');

function getLib() {
  return {
    fn1: function() {},
    fn2: function() {},
    fn3: function() {}
  };
}

(function wrapAll() {
  var lib = getLib();
  retry.wrap(lib);
  assert.equal(lib.fn1.name, 'bound retryWrapper');
  assert.equal(lib.fn2.name, 'bound retryWrapper');
  assert.equal(lib.fn3.name, 'bound retryWrapper');
}());

(function wrapAllPassOptions() {
  var lib = getLib();
  retry.wrap(lib, {retries: 2});
  assert.equal(lib.fn1.name, 'bound retryWrapper');
  assert.equal(lib.fn2.name, 'bound retryWrapper');
  assert.equal(lib.fn3.name, 'bound retryWrapper');
  assert.equal(lib.fn1.options.retries, 2);
  assert.equal(lib.fn2.options.retries, 2);
  assert.equal(lib.fn3.options.retries, 2);
}());

(function wrapDefined() {
  var lib = getLib();
  retry.wrap(lib, ['fn2', 'fn3']);
  assert.notEqual(lib.fn1.name, 'bound retryWrapper');
  assert.equal(lib.fn2.name, 'bound retryWrapper');
  assert.equal(lib.fn3.name, 'bound retryWrapper');
}());

(function wrapDefinedAndPassOptions() {
  var lib = getLib();
  retry.wrap(lib, {retries: 2}, ['fn2', 'fn3']);
  assert.notEqual(lib.fn1.name, 'bound retryWrapper');
  assert.equal(lib.fn2.name, 'bound retryWrapper');
  assert.equal(lib.fn3.name, 'bound retryWrapper');
  assert.equal(lib.fn2.options.retries, 2);
  assert.equal(lib.fn3.options.retries, 2);
}());

(function runWrappedWithoutError() {
  var callbackCalled;
  var lib = {method: function(a, b, callback) {
    assert.equal(a, 1);
    assert.equal(b, 2);
    assert.equal(typeof callback, 'function');
    callback();
  }};
  retry.wrap(lib);
  lib.method(1, 2, function() {
    callbackCalled = true;
  });
  assert.ok(callbackCalled);
}());

(function runWrappedSeveralWithoutError() {
  var callbacksCalled = 0;
  var lib = {
    fn1: function (a, callback) {
      assert.equal(a, 1);
      assert.equal(typeof callback, 'function');
      callback();
    },
    fn2: function (a, callback) {
      assert.equal(a, 2);
      assert.equal(typeof callback, 'function');
      callback();
    }
  };
  retry.wrap(lib, {}, ['fn1', 'fn2']);
  lib.fn1(1, function() {
    callbacksCalled++;
  });
  lib.fn2(2, function() {
    callbacksCalled++;
  });
  assert.equal(callbacksCalled, 2);
}());

(function runWrappedWithError() {
  var callbackCalled;
  var lib = {method: function(callback) {
    callback(new Error('Some error'));
  }};
  retry.wrap(lib, {retries: 1});
  lib.method(function(err) {
    callbackCalled = true;
    assert.ok(err instanceof Error);
  });
  assert.ok(!callbackCalled);
}());
PK~\$Lretry/test/common.jsnu[var common = module.exports;
var path = require('path');

var rootDir = path.join(__dirname, '..');
common.dir = {
  lib: rootDir + '/lib'
};

common.assert = require('assert');
common.fake = require('fake');PK~\-'T((retry/index.jsnu[module.exports = require('./lib/retry');PK~\^88retry/Makefilenu[SHELL := /bin/bash

release-major: test
	npm version major -m "Release %s"
	git push
	npm publish

release-minor: test
	npm version minor -m "Release %s"
	git push
	npm publish

release-patch: test
	npm version patch -m "Release %s"
	git push
	npm publish

.PHONY: test release-major release-minor release-patch
PK~\שuxxretry/example/stop.jsnu[var retry = require('../lib/retry');

function attemptAsyncOperation(someInput, cb) {
  var opts = {
    retries: 2,
    factor: 2,
    minTimeout: 1 * 1000,
    maxTimeout: 2 * 1000,
    randomize: true
  };
  var operation = retry.operation(opts);

  operation.attempt(function(currentAttempt) {
    failingAsyncOperation(someInput, function(err, result) {

      if (err && err.message === 'A fatal error') {
        operation.stop();
        return cb(err);
      }

      if (operation.retry(err)) {
        return;
      }

      cb(operation.mainError(), operation.errors(), result);
    });
  });
}

attemptAsyncOperation('test input', function(err, errors, result) {
  console.warn('err:');
  console.log(err);

  console.warn('result:');
  console.log(result);
});

function failingAsyncOperation(input, cb) {
  return setImmediate(cb.bind(null, new Error('A fatal error')));
}
PK~\>ySretry/example/dns.jsnu[var dns = require('dns');
var retry = require('../lib/retry');

function faultTolerantResolve(address, cb) {
  var opts = {
    retries: 2,
    factor: 2,
    minTimeout: 1 * 1000,
    maxTimeout: 2 * 1000,
    randomize: true
  };
  var operation = retry.operation(opts);

  operation.attempt(function(currentAttempt) {
    dns.resolve(address, function(err, addresses) {
      if (operation.retry(err)) {
        return;
      }

      cb(operation.mainError(), operation.errors(), addresses);
    });
  });
}

faultTolerantResolve('nodejs.org', function(err, errors, addresses) {
  console.warn('err:');
  console.log(err);

  console.warn('addresses:');
  console.log(addresses);
});PK~\AWUss
retry/Licensenu[Copyright (c) 2011:
Tim Koschützki (tim@debuggable.com)
Felix Geisendörfer (felix@debuggable.com)

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
PK~\
retry/equation.gifnu[GIF89a1    $ )()),)1011419899<9A@AADAJHJJLJRPRRURZYZZ]Zbabbebjijjmjsqssus{y{{}{,1pH,Ȥrl:ШtJZجxˀ(xL.gan<51zD/w<
5[:,R6C3o&H>1-
%>8I7v24J
š!Hڄ=18.0.0"
  },
  "files": [
    "dist"
  ],
  "homepage": "https://github.com/theupdateframework/tuf-js/tree/main/packages/models#readme",
  "keywords": [
    "tuf",
    "security",
    "update"
  ],
  "license": "MIT",
  "main": "dist/index.js",
  "name": "@tufjs/models",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/theupdateframework/tuf-js.git"
  },
  "scripts": {
    "build": "tsc --build",
    "clean": "rm -rf dist && rm tsconfig.tsbuildinfo",
    "test": "jest"
  },
  "types": "dist/index.d.ts",
  "version": "2.0.1"
}
PK~\М@@@tufjs/models/LICENSEnu[MIT License

Copyright (c) 2022 GitHub and the TUF Contributors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
PK~\BDQQ@tufjs/models/dist/key.jsnu["use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Key = void 0;
const util_1 = __importDefault(require("util"));
const error_1 = require("./error");
const utils_1 = require("./utils");
const key_1 = require("./utils/key");
// A container class representing the public portion of a Key.
class Key {
    constructor(options) {
        const { keyID, keyType, scheme, keyVal, unrecognizedFields } = options;
        this.keyID = keyID;
        this.keyType = keyType;
        this.scheme = scheme;
        this.keyVal = keyVal;
        this.unrecognizedFields = unrecognizedFields || {};
    }
    // Verifies the that the metadata.signatures contains a signature made with
    // this key and is correctly signed.
    verifySignature(metadata) {
        const signature = metadata.signatures[this.keyID];
        if (!signature)
            throw new error_1.UnsignedMetadataError('no signature for key found in metadata');
        if (!this.keyVal.public)
            throw new error_1.UnsignedMetadataError('no public key found');
        const publicKey = (0, key_1.getPublicKey)({
            keyType: this.keyType,
            scheme: this.scheme,
            keyVal: this.keyVal.public,
        });
        const signedData = metadata.signed.toJSON();
        try {
            if (!utils_1.crypto.verifySignature(signedData, publicKey, signature.sig)) {
                throw new error_1.UnsignedMetadataError(`failed to verify ${this.keyID} signature`);
            }
        }
        catch (error) {
            if (error instanceof error_1.UnsignedMetadataError) {
                throw error;
            }
            throw new error_1.UnsignedMetadataError(`failed to verify ${this.keyID} signature`);
        }
    }
    equals(other) {
        if (!(other instanceof Key)) {
            return false;
        }
        return (this.keyID === other.keyID &&
            this.keyType === other.keyType &&
            this.scheme === other.scheme &&
            util_1.default.isDeepStrictEqual(this.keyVal, other.keyVal) &&
            util_1.default.isDeepStrictEqual(this.unrecognizedFields, other.unrecognizedFields));
    }
    toJSON() {
        return {
            keytype: this.keyType,
            scheme: this.scheme,
            keyval: this.keyVal,
            ...this.unrecognizedFields,
        };
    }
    static fromJSON(keyID, data) {
        const { keytype, scheme, keyval, ...rest } = data;
        if (typeof keytype !== 'string') {
            throw new TypeError('keytype must be a string');
        }
        if (typeof scheme !== 'string') {
            throw new TypeError('scheme must be a string');
        }
        if (!utils_1.guard.isStringRecord(keyval)) {
            throw new TypeError('keyval must be a string record');
        }
        return new Key({
            keyID,
            keyType: keytype,
            scheme,
            keyVal: keyval,
            unrecognizedFields: rest,
        });
    }
}
exports.Key = Key;
PK~\N@tufjs/models/dist/targets.jsnu["use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Targets = void 0;
const util_1 = __importDefault(require("util"));
const base_1 = require("./base");
const delegations_1 = require("./delegations");
const file_1 = require("./file");
const utils_1 = require("./utils");
// Container for the signed part of targets metadata.
//
// Targets contains verifying information about target files and also delegates
// responsible to other Targets roles.
class Targets extends base_1.Signed {
    constructor(options) {
        super(options);
        this.type = base_1.MetadataKind.Targets;
        this.targets = options.targets || {};
        this.delegations = options.delegations;
    }
    addTarget(target) {
        this.targets[target.path] = target;
    }
    equals(other) {
        if (!(other instanceof Targets)) {
            return false;
        }
        return (super.equals(other) &&
            util_1.default.isDeepStrictEqual(this.targets, other.targets) &&
            util_1.default.isDeepStrictEqual(this.delegations, other.delegations));
    }
    toJSON() {
        const json = {
            _type: this.type,
            spec_version: this.specVersion,
            version: this.version,
            expires: this.expires,
            targets: targetsToJSON(this.targets),
            ...this.unrecognizedFields,
        };
        if (this.delegations) {
            json.delegations = this.delegations.toJSON();
        }
        return json;
    }
    static fromJSON(data) {
        const { unrecognizedFields, ...commonFields } = base_1.Signed.commonFieldsFromJSON(data);
        const { targets, delegations, ...rest } = unrecognizedFields;
        return new Targets({
            ...commonFields,
            targets: targetsFromJSON(targets),
            delegations: delegationsFromJSON(delegations),
            unrecognizedFields: rest,
        });
    }
}
exports.Targets = Targets;
function targetsToJSON(targets) {
    return Object.entries(targets).reduce((acc, [path, target]) => ({
        ...acc,
        [path]: target.toJSON(),
    }), {});
}
function targetsFromJSON(data) {
    let targets;
    if (utils_1.guard.isDefined(data)) {
        if (!utils_1.guard.isObjectRecord(data)) {
            throw new TypeError('targets must be an object');
        }
        else {
            targets = Object.entries(data).reduce((acc, [path, target]) => ({
                ...acc,
                [path]: file_1.TargetFile.fromJSON(path, target),
            }), {});
        }
    }
    return targets;
}
function delegationsFromJSON(data) {
    let delegations;
    if (utils_1.guard.isDefined(data)) {
        if (!utils_1.guard.isObject(data)) {
            throw new TypeError('delegations must be an object');
        }
        else {
            delegations = delegations_1.Delegations.fromJSON(data);
        }
    }
    return delegations;
}
PK~\_@tufjs/models/dist/timestamp.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Timestamp = void 0;
const base_1 = require("./base");
const file_1 = require("./file");
const utils_1 = require("./utils");
/**
 * A container for the signed part of timestamp metadata.
 *
 * A top-level that specifies the latest version of the snapshot role metadata file,
 * and hence the latest versions of all metadata and targets on the repository.
 */
class Timestamp extends base_1.Signed {
    constructor(options) {
        super(options);
        this.type = base_1.MetadataKind.Timestamp;
        this.snapshotMeta = options.snapshotMeta || new file_1.MetaFile({ version: 1 });
    }
    equals(other) {
        if (!(other instanceof Timestamp)) {
            return false;
        }
        return super.equals(other) && this.snapshotMeta.equals(other.snapshotMeta);
    }
    toJSON() {
        return {
            _type: this.type,
            spec_version: this.specVersion,
            version: this.version,
            expires: this.expires,
            meta: { 'snapshot.json': this.snapshotMeta.toJSON() },
            ...this.unrecognizedFields,
        };
    }
    static fromJSON(data) {
        const { unrecognizedFields, ...commonFields } = base_1.Signed.commonFieldsFromJSON(data);
        const { meta, ...rest } = unrecognizedFields;
        return new Timestamp({
            ...commonFields,
            snapshotMeta: snapshotMetaFromJSON(meta),
            unrecognizedFields: rest,
        });
    }
}
exports.Timestamp = Timestamp;
function snapshotMetaFromJSON(data) {
    let snapshotMeta;
    if (utils_1.guard.isDefined(data)) {
        const snapshotData = data['snapshot.json'];
        if (!utils_1.guard.isDefined(snapshotData) || !utils_1.guard.isObject(snapshotData)) {
            throw new TypeError('missing snapshot.json in meta');
        }
        else {
            snapshotMeta = file_1.MetaFile.fromJSON(snapshotData);
        }
    }
    return snapshotMeta;
}
PK~\F(@tufjs/models/dist/base.jsnu["use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Signed = exports.isMetadataKind = exports.MetadataKind = void 0;
const util_1 = __importDefault(require("util"));
const error_1 = require("./error");
const utils_1 = require("./utils");
const SPECIFICATION_VERSION = ['1', '0', '31'];
var MetadataKind;
(function (MetadataKind) {
    MetadataKind["Root"] = "root";
    MetadataKind["Timestamp"] = "timestamp";
    MetadataKind["Snapshot"] = "snapshot";
    MetadataKind["Targets"] = "targets";
})(MetadataKind || (exports.MetadataKind = MetadataKind = {}));
function isMetadataKind(value) {
    return (typeof value === 'string' &&
        Object.values(MetadataKind).includes(value));
}
exports.isMetadataKind = isMetadataKind;
/***
 * A base class for the signed part of TUF metadata.
 *
 * Objects with base class Signed are usually included in a ``Metadata`` object
 * on the signed attribute. This class provides attributes and methods that
 * are common for all TUF metadata types (roles).
 */
class Signed {
    constructor(options) {
        this.specVersion = options.specVersion || SPECIFICATION_VERSION.join('.');
        const specList = this.specVersion.split('.');
        if (!(specList.length === 2 || specList.length === 3) ||
            !specList.every((item) => isNumeric(item))) {
            throw new error_1.ValueError('Failed to parse specVersion');
        }
        // major version must match
        if (specList[0] != SPECIFICATION_VERSION[0]) {
            throw new error_1.ValueError('Unsupported specVersion');
        }
        this.expires = options.expires || new Date().toISOString();
        this.version = options.version || 1;
        this.unrecognizedFields = options.unrecognizedFields || {};
    }
    equals(other) {
        if (!(other instanceof Signed)) {
            return false;
        }
        return (this.specVersion === other.specVersion &&
            this.expires === other.expires &&
            this.version === other.version &&
            util_1.default.isDeepStrictEqual(this.unrecognizedFields, other.unrecognizedFields));
    }
    isExpired(referenceTime) {
        if (!referenceTime) {
            referenceTime = new Date();
        }
        return referenceTime >= new Date(this.expires);
    }
    static commonFieldsFromJSON(data) {
        const { spec_version, expires, version, ...rest } = data;
        if (utils_1.guard.isDefined(spec_version) && !(typeof spec_version === 'string')) {
            throw new TypeError('spec_version must be a string');
        }
        if (utils_1.guard.isDefined(expires) && !(typeof expires === 'string')) {
            throw new TypeError('expires must be a string');
        }
        if (utils_1.guard.isDefined(version) && !(typeof version === 'number')) {
            throw new TypeError('version must be a number');
        }
        return {
            specVersion: spec_version,
            expires,
            version,
            unrecognizedFields: rest,
        };
    }
}
exports.Signed = Signed;
function isNumeric(str) {
    return !isNaN(Number(str));
}
PK~\8Rn!@tufjs/models/dist/delegations.jsnu["use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Delegations = void 0;
const util_1 = __importDefault(require("util"));
const error_1 = require("./error");
const key_1 = require("./key");
const role_1 = require("./role");
const utils_1 = require("./utils");
/**
 * A container object storing information about all delegations.
 *
 * Targets roles that are trusted to provide signed metadata files
 * describing targets with designated pathnames and/or further delegations.
 */
class Delegations {
    constructor(options) {
        this.keys = options.keys;
        this.unrecognizedFields = options.unrecognizedFields || {};
        if (options.roles) {
            if (Object.keys(options.roles).some((roleName) => role_1.TOP_LEVEL_ROLE_NAMES.includes(roleName))) {
                throw new error_1.ValueError('Delegated role name conflicts with top-level role name');
            }
        }
        this.succinctRoles = options.succinctRoles;
        this.roles = options.roles;
    }
    equals(other) {
        if (!(other instanceof Delegations)) {
            return false;
        }
        return (util_1.default.isDeepStrictEqual(this.keys, other.keys) &&
            util_1.default.isDeepStrictEqual(this.roles, other.roles) &&
            util_1.default.isDeepStrictEqual(this.unrecognizedFields, other.unrecognizedFields) &&
            util_1.default.isDeepStrictEqual(this.succinctRoles, other.succinctRoles));
    }
    *rolesForTarget(targetPath) {
        if (this.roles) {
            for (const role of Object.values(this.roles)) {
                if (role.isDelegatedPath(targetPath)) {
                    yield { role: role.name, terminating: role.terminating };
                }
            }
        }
        else if (this.succinctRoles) {
            yield {
                role: this.succinctRoles.getRoleForTarget(targetPath),
                terminating: true,
            };
        }
    }
    toJSON() {
        const json = {
            keys: keysToJSON(this.keys),
            ...this.unrecognizedFields,
        };
        if (this.roles) {
            json.roles = rolesToJSON(this.roles);
        }
        else if (this.succinctRoles) {
            json.succinct_roles = this.succinctRoles.toJSON();
        }
        return json;
    }
    static fromJSON(data) {
        const { keys, roles, succinct_roles, ...unrecognizedFields } = data;
        let succinctRoles;
        if (utils_1.guard.isObject(succinct_roles)) {
            succinctRoles = role_1.SuccinctRoles.fromJSON(succinct_roles);
        }
        return new Delegations({
            keys: keysFromJSON(keys),
            roles: rolesFromJSON(roles),
            unrecognizedFields,
            succinctRoles,
        });
    }
}
exports.Delegations = Delegations;
function keysToJSON(keys) {
    return Object.entries(keys).reduce((acc, [keyId, key]) => ({
        ...acc,
        [keyId]: key.toJSON(),
    }), {});
}
function rolesToJSON(roles) {
    return Object.values(roles).map((role) => role.toJSON());
}
function keysFromJSON(data) {
    if (!utils_1.guard.isObjectRecord(data)) {
        throw new TypeError('keys is malformed');
    }
    return Object.entries(data).reduce((acc, [keyID, keyData]) => ({
        ...acc,
        [keyID]: key_1.Key.fromJSON(keyID, keyData),
    }), {});
}
function rolesFromJSON(data) {
    let roleMap;
    if (utils_1.guard.isDefined(data)) {
        if (!utils_1.guard.isObjectArray(data)) {
            throw new TypeError('roles is malformed');
        }
        roleMap = data.reduce((acc, role) => {
            const delegatedRole = role_1.DelegatedRole.fromJSON(role);
            return {
                ...acc,
                [delegatedRole.name]: delegatedRole,
            };
        }, {});
    }
    return roleMap;
}
PK~\{v[	[	@tufjs/models/dist/snapshot.jsnu["use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Snapshot = void 0;
const util_1 = __importDefault(require("util"));
const base_1 = require("./base");
const file_1 = require("./file");
const utils_1 = require("./utils");
/**
 * A container for the signed part of snapshot metadata.
 *
 * Snapshot contains information about all target Metadata files.
 * A top-level role that specifies the latest versions of all targets metadata files,
 * and hence the latest versions of all targets (including any dependencies between them) on the repository.
 */
class Snapshot extends base_1.Signed {
    constructor(opts) {
        super(opts);
        this.type = base_1.MetadataKind.Snapshot;
        this.meta = opts.meta || { 'targets.json': new file_1.MetaFile({ version: 1 }) };
    }
    equals(other) {
        if (!(other instanceof Snapshot)) {
            return false;
        }
        return super.equals(other) && util_1.default.isDeepStrictEqual(this.meta, other.meta);
    }
    toJSON() {
        return {
            _type: this.type,
            meta: metaToJSON(this.meta),
            spec_version: this.specVersion,
            version: this.version,
            expires: this.expires,
            ...this.unrecognizedFields,
        };
    }
    static fromJSON(data) {
        const { unrecognizedFields, ...commonFields } = base_1.Signed.commonFieldsFromJSON(data);
        const { meta, ...rest } = unrecognizedFields;
        return new Snapshot({
            ...commonFields,
            meta: metaFromJSON(meta),
            unrecognizedFields: rest,
        });
    }
}
exports.Snapshot = Snapshot;
function metaToJSON(meta) {
    return Object.entries(meta).reduce((acc, [path, metadata]) => ({
        ...acc,
        [path]: metadata.toJSON(),
    }), {});
}
function metaFromJSON(data) {
    let meta;
    if (utils_1.guard.isDefined(data)) {
        if (!utils_1.guard.isObjectRecord(data)) {
            throw new TypeError('meta field is malformed');
        }
        else {
            meta = Object.entries(data).reduce((acc, [path, metadata]) => ({
                ...acc,
                [path]: file_1.MetaFile.fromJSON(metadata),
            }), {});
        }
    }
    return meta;
}
PK~\S@tufjs/models/dist/utils/key.jsnu["use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getPublicKey = void 0;
const crypto_1 = __importDefault(require("crypto"));
const error_1 = require("../error");
const oid_1 = require("./oid");
const ASN1_TAG_SEQUENCE = 0x30;
const ANS1_TAG_BIT_STRING = 0x03;
const NULL_BYTE = 0x00;
const OID_EDDSA = '1.3.101.112';
const OID_EC_PUBLIC_KEY = '1.2.840.10045.2.1';
const OID_EC_CURVE_P256V1 = '1.2.840.10045.3.1.7';
const PEM_HEADER = '-----BEGIN PUBLIC KEY-----';
function getPublicKey(keyInfo) {
    switch (keyInfo.keyType) {
        case 'rsa':
            return getRSAPublicKey(keyInfo);
        case 'ed25519':
            return getED25519PublicKey(keyInfo);
        case 'ecdsa':
        case 'ecdsa-sha2-nistp256':
        case 'ecdsa-sha2-nistp384':
            return getECDCSAPublicKey(keyInfo);
        default:
            throw new error_1.UnsupportedAlgorithmError(`Unsupported key type: ${keyInfo.keyType}`);
    }
}
exports.getPublicKey = getPublicKey;
function getRSAPublicKey(keyInfo) {
    // Only support PEM-encoded RSA keys
    if (!keyInfo.keyVal.startsWith(PEM_HEADER)) {
        throw new error_1.CryptoError('Invalid key format');
    }
    const key = crypto_1.default.createPublicKey(keyInfo.keyVal);
    switch (keyInfo.scheme) {
        case 'rsassa-pss-sha256':
            return {
                key: key,
                padding: crypto_1.default.constants.RSA_PKCS1_PSS_PADDING,
            };
        default:
            throw new error_1.UnsupportedAlgorithmError(`Unsupported RSA scheme: ${keyInfo.scheme}`);
    }
}
function getED25519PublicKey(keyInfo) {
    let key;
    // If key is already PEM-encoded we can just parse it
    if (keyInfo.keyVal.startsWith(PEM_HEADER)) {
        key = crypto_1.default.createPublicKey(keyInfo.keyVal);
    }
    else {
        // If key is not PEM-encoded it had better be hex
        if (!isHex(keyInfo.keyVal)) {
            throw new error_1.CryptoError('Invalid key format');
        }
        key = crypto_1.default.createPublicKey({
            key: ed25519.hexToDER(keyInfo.keyVal),
            format: 'der',
            type: 'spki',
        });
    }
    return { key };
}
function getECDCSAPublicKey(keyInfo) {
    let key;
    // If key is already PEM-encoded we can just parse it
    if (keyInfo.keyVal.startsWith(PEM_HEADER)) {
        key = crypto_1.default.createPublicKey(keyInfo.keyVal);
    }
    else {
        // If key is not PEM-encoded it had better be hex
        if (!isHex(keyInfo.keyVal)) {
            throw new error_1.CryptoError('Invalid key format');
        }
        key = crypto_1.default.createPublicKey({
            key: ecdsa.hexToDER(keyInfo.keyVal),
            format: 'der',
            type: 'spki',
        });
    }
    return { key };
}
const ed25519 = {
    // Translates a hex key into a crypto KeyObject
    // https://keygen.sh/blog/how-to-use-hexadecimal-ed25519-keys-in-node/
    hexToDER: (hex) => {
        const key = Buffer.from(hex, 'hex');
        const oid = (0, oid_1.encodeOIDString)(OID_EDDSA);
        // Create a byte sequence containing the OID and key
        const elements = Buffer.concat([
            Buffer.concat([
                Buffer.from([ASN1_TAG_SEQUENCE]),
                Buffer.from([oid.length]),
                oid,
            ]),
            Buffer.concat([
                Buffer.from([ANS1_TAG_BIT_STRING]),
                Buffer.from([key.length + 1]),
                Buffer.from([NULL_BYTE]),
                key,
            ]),
        ]);
        // Wrap up by creating a sequence of elements
        const der = Buffer.concat([
            Buffer.from([ASN1_TAG_SEQUENCE]),
            Buffer.from([elements.length]),
            elements,
        ]);
        return der;
    },
};
const ecdsa = {
    hexToDER: (hex) => {
        const key = Buffer.from(hex, 'hex');
        const bitString = Buffer.concat([
            Buffer.from([ANS1_TAG_BIT_STRING]),
            Buffer.from([key.length + 1]),
            Buffer.from([NULL_BYTE]),
            key,
        ]);
        const oids = Buffer.concat([
            (0, oid_1.encodeOIDString)(OID_EC_PUBLIC_KEY),
            (0, oid_1.encodeOIDString)(OID_EC_CURVE_P256V1),
        ]);
        const oidSequence = Buffer.concat([
            Buffer.from([ASN1_TAG_SEQUENCE]),
            Buffer.from([oids.length]),
            oids,
        ]);
        // Wrap up by creating a sequence of elements
        const der = Buffer.concat([
            Buffer.from([ASN1_TAG_SEQUENCE]),
            Buffer.from([oidSequence.length + bitString.length]),
            oidSequence,
            bitString,
        ]);
        return der;
    },
};
const isHex = (key) => /^[0-9a-fA-F]+$/.test(key);
PK~\w#!@tufjs/models/dist/utils/guard.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isObjectRecord = exports.isStringRecord = exports.isObjectArray = exports.isStringArray = exports.isObject = exports.isDefined = void 0;
function isDefined(val) {
    return val !== undefined;
}
exports.isDefined = isDefined;
function isObject(value) {
    return typeof value === 'object' && value !== null;
}
exports.isObject = isObject;
function isStringArray(value) {
    return Array.isArray(value) && value.every((v) => typeof v === 'string');
}
exports.isStringArray = isStringArray;
function isObjectArray(value) {
    return Array.isArray(value) && value.every(isObject);
}
exports.isObjectArray = isObjectArray;
function isStringRecord(value) {
    return (typeof value === 'object' &&
        value !== null &&
        Object.keys(value).every((k) => typeof k === 'string') &&
        Object.values(value).every((v) => typeof v === 'string'));
}
exports.isStringRecord = isStringRecord;
function isObjectRecord(value) {
    return (typeof value === 'object' &&
        value !== null &&
        Object.keys(value).every((k) => typeof k === 'string') &&
        Object.values(value).every((v) => typeof v === 'object' && v !== null));
}
exports.isObjectRecord = isObjectRecord;
PK~\-TMM!@tufjs/models/dist/utils/types.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
PK~\ܪ!@tufjs/models/dist/utils/index.jsnu["use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.crypto = exports.guard = void 0;
exports.guard = __importStar(require("./guard"));
exports.crypto = __importStar(require("./verify"));
PK~\WD{{@tufjs/models/dist/utils/oid.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.encodeOIDString = void 0;
const ANS1_TAG_OID = 0x06;
function encodeOIDString(oid) {
    const parts = oid.split('.');
    // The first two subidentifiers are encoded into the first byte
    const first = parseInt(parts[0], 10) * 40 + parseInt(parts[1], 10);
    const rest = [];
    parts.slice(2).forEach((part) => {
        const bytes = encodeVariableLengthInteger(parseInt(part, 10));
        rest.push(...bytes);
    });
    const der = Buffer.from([first, ...rest]);
    return Buffer.from([ANS1_TAG_OID, der.length, ...der]);
}
exports.encodeOIDString = encodeOIDString;
function encodeVariableLengthInteger(value) {
    const bytes = [];
    let mask = 0x00;
    while (value > 0) {
        bytes.unshift((value & 0x7f) | mask);
        value >>= 7;
        mask = 0x80;
    }
    return bytes;
}
PK~\>ޛ"@tufjs/models/dist/utils/verify.jsnu["use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.verifySignature = void 0;
const canonical_json_1 = require("@tufjs/canonical-json");
const crypto_1 = __importDefault(require("crypto"));
const verifySignature = (metaDataSignedData, key, signature) => {
    const canonicalData = Buffer.from((0, canonical_json_1.canonicalize)(metaDataSignedData));
    return crypto_1.default.verify(undefined, canonicalData, key, Buffer.from(signature, 'hex'));
};
exports.verifySignature = verifySignature;
PK~\t[kk@tufjs/models/dist/root.jsnu["use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Root = void 0;
const util_1 = __importDefault(require("util"));
const base_1 = require("./base");
const error_1 = require("./error");
const key_1 = require("./key");
const role_1 = require("./role");
const utils_1 = require("./utils");
/**
 * A container for the signed part of root metadata.
 *
 * The top-level role and metadata file signed by the root keys.
 * This role specifies trusted keys for all other top-level roles, which may further delegate trust.
 */
class Root extends base_1.Signed {
    constructor(options) {
        super(options);
        this.type = base_1.MetadataKind.Root;
        this.keys = options.keys || {};
        this.consistentSnapshot = options.consistentSnapshot ?? true;
        if (!options.roles) {
            this.roles = role_1.TOP_LEVEL_ROLE_NAMES.reduce((acc, role) => ({
                ...acc,
                [role]: new role_1.Role({ keyIDs: [], threshold: 1 }),
            }), {});
        }
        else {
            const roleNames = new Set(Object.keys(options.roles));
            if (!role_1.TOP_LEVEL_ROLE_NAMES.every((role) => roleNames.has(role))) {
                throw new error_1.ValueError('missing top-level role');
            }
            this.roles = options.roles;
        }
    }
    addKey(key, role) {
        if (!this.roles[role]) {
            throw new error_1.ValueError(`role ${role} does not exist`);
        }
        if (!this.roles[role].keyIDs.includes(key.keyID)) {
            this.roles[role].keyIDs.push(key.keyID);
        }
        this.keys[key.keyID] = key;
    }
    equals(other) {
        if (!(other instanceof Root)) {
            return false;
        }
        return (super.equals(other) &&
            this.consistentSnapshot === other.consistentSnapshot &&
            util_1.default.isDeepStrictEqual(this.keys, other.keys) &&
            util_1.default.isDeepStrictEqual(this.roles, other.roles));
    }
    toJSON() {
        return {
            _type: this.type,
            spec_version: this.specVersion,
            version: this.version,
            expires: this.expires,
            keys: keysToJSON(this.keys),
            roles: rolesToJSON(this.roles),
            consistent_snapshot: this.consistentSnapshot,
            ...this.unrecognizedFields,
        };
    }
    static fromJSON(data) {
        const { unrecognizedFields, ...commonFields } = base_1.Signed.commonFieldsFromJSON(data);
        const { keys, roles, consistent_snapshot, ...rest } = unrecognizedFields;
        if (typeof consistent_snapshot !== 'boolean') {
            throw new TypeError('consistent_snapshot must be a boolean');
        }
        return new Root({
            ...commonFields,
            keys: keysFromJSON(keys),
            roles: rolesFromJSON(roles),
            consistentSnapshot: consistent_snapshot,
            unrecognizedFields: rest,
        });
    }
}
exports.Root = Root;
function keysToJSON(keys) {
    return Object.entries(keys).reduce((acc, [keyID, key]) => ({ ...acc, [keyID]: key.toJSON() }), {});
}
function rolesToJSON(roles) {
    return Object.entries(roles).reduce((acc, [roleName, role]) => ({ ...acc, [roleName]: role.toJSON() }), {});
}
function keysFromJSON(data) {
    let keys;
    if (utils_1.guard.isDefined(data)) {
        if (!utils_1.guard.isObjectRecord(data)) {
            throw new TypeError('keys must be an object');
        }
        keys = Object.entries(data).reduce((acc, [keyID, keyData]) => ({
            ...acc,
            [keyID]: key_1.Key.fromJSON(keyID, keyData),
        }), {});
    }
    return keys;
}
function rolesFromJSON(data) {
    let roles;
    if (utils_1.guard.isDefined(data)) {
        if (!utils_1.guard.isObjectRecord(data)) {
            throw new TypeError('roles must be an object');
        }
        roles = Object.entries(data).reduce((acc, [roleName, roleData]) => ({
            ...acc,
            [roleName]: role_1.Role.fromJSON(roleData),
        }), {});
    }
    return roles;
}
PK~\vruu@tufjs/models/dist/index.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Timestamp = exports.Targets = exports.Snapshot = exports.Signature = exports.Root = exports.Metadata = exports.Key = exports.TargetFile = exports.MetaFile = exports.ValueError = exports.MetadataKind = void 0;
var base_1 = require("./base");
Object.defineProperty(exports, "MetadataKind", { enumerable: true, get: function () { return base_1.MetadataKind; } });
var error_1 = require("./error");
Object.defineProperty(exports, "ValueError", { enumerable: true, get: function () { return error_1.ValueError; } });
var file_1 = require("./file");
Object.defineProperty(exports, "MetaFile", { enumerable: true, get: function () { return file_1.MetaFile; } });
Object.defineProperty(exports, "TargetFile", { enumerable: true, get: function () { return file_1.TargetFile; } });
var key_1 = require("./key");
Object.defineProperty(exports, "Key", { enumerable: true, get: function () { return key_1.Key; } });
var metadata_1 = require("./metadata");
Object.defineProperty(exports, "Metadata", { enumerable: true, get: function () { return metadata_1.Metadata; } });
var root_1 = require("./root");
Object.defineProperty(exports, "Root", { enumerable: true, get: function () { return root_1.Root; } });
var signature_1 = require("./signature");
Object.defineProperty(exports, "Signature", { enumerable: true, get: function () { return signature_1.Signature; } });
var snapshot_1 = require("./snapshot");
Object.defineProperty(exports, "Snapshot", { enumerable: true, get: function () { return snapshot_1.Snapshot; } });
var targets_1 = require("./targets");
Object.defineProperty(exports, "Targets", { enumerable: true, get: function () { return targets_1.Targets; } });
var timestamp_1 = require("./timestamp");
Object.defineProperty(exports, "Timestamp", { enumerable: true, get: function () { return timestamp_1.Timestamp; } });
PK~\1gg@tufjs/models/dist/metadata.jsnu["use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Metadata = void 0;
const canonical_json_1 = require("@tufjs/canonical-json");
const util_1 = __importDefault(require("util"));
const base_1 = require("./base");
const error_1 = require("./error");
const root_1 = require("./root");
const signature_1 = require("./signature");
const snapshot_1 = require("./snapshot");
const targets_1 = require("./targets");
const timestamp_1 = require("./timestamp");
const utils_1 = require("./utils");
/***
 * A container for signed TUF metadata.
 *
 * Provides methods to convert to and from json, read and write to and
 * from JSON and to create and verify metadata signatures.
 *
 * ``Metadata[T]`` is a generic container type where T can be any one type of
 * [``Root``, ``Timestamp``, ``Snapshot``, ``Targets``]. The purpose of this
 * is to allow static type checking of the signed attribute in code using
 * Metadata::
 *
 * root_md = Metadata[Root].fromJSON("root.json")
 * # root_md type is now Metadata[Root]. This means signed and its
 * # attributes like consistent_snapshot are now statically typed and the
 * # types can be verified by static type checkers and shown by IDEs
 *
 * Using a type constraint is not required but not doing so means T is not a
 * specific type so static typing cannot happen. Note that the type constraint
 * ``[Root]`` is not validated at runtime (as pure annotations are not available
 * then).
 *
 * Apart from ``expires`` all of the arguments to the inner constructors have
 * reasonable default values for new metadata.
 */
class Metadata {
    constructor(signed, signatures, unrecognizedFields) {
        this.signed = signed;
        this.signatures = signatures || {};
        this.unrecognizedFields = unrecognizedFields || {};
    }
    sign(signer, append = true) {
        const bytes = Buffer.from((0, canonical_json_1.canonicalize)(this.signed.toJSON()));
        const signature = signer(bytes);
        if (!append) {
            this.signatures = {};
        }
        this.signatures[signature.keyID] = signature;
    }
    verifyDelegate(delegatedRole, delegatedMetadata) {
        let role;
        let keys = {};
        switch (this.signed.type) {
            case base_1.MetadataKind.Root:
                keys = this.signed.keys;
                role = this.signed.roles[delegatedRole];
                break;
            case base_1.MetadataKind.Targets:
                if (!this.signed.delegations) {
                    throw new error_1.ValueError(`No delegations found for ${delegatedRole}`);
                }
                keys = this.signed.delegations.keys;
                if (this.signed.delegations.roles) {
                    role = this.signed.delegations.roles[delegatedRole];
                }
                else if (this.signed.delegations.succinctRoles) {
                    if (this.signed.delegations.succinctRoles.isDelegatedRole(delegatedRole)) {
                        role = this.signed.delegations.succinctRoles;
                    }
                }
                break;
            default:
                throw new TypeError('invalid metadata type');
        }
        if (!role) {
            throw new error_1.ValueError(`no delegation found for ${delegatedRole}`);
        }
        const signingKeys = new Set();
        role.keyIDs.forEach((keyID) => {
            const key = keys[keyID];
            // If we dont' have the key, continue checking other keys
            if (!key) {
                return;
            }
            try {
                key.verifySignature(delegatedMetadata);
                signingKeys.add(key.keyID);
            }
            catch (error) {
                // continue
            }
        });
        if (signingKeys.size < role.threshold) {
            throw new error_1.UnsignedMetadataError(`${delegatedRole} was signed by ${signingKeys.size}/${role.threshold} keys`);
        }
    }
    equals(other) {
        if (!(other instanceof Metadata)) {
            return false;
        }
        return (this.signed.equals(other.signed) &&
            util_1.default.isDeepStrictEqual(this.signatures, other.signatures) &&
            util_1.default.isDeepStrictEqual(this.unrecognizedFields, other.unrecognizedFields));
    }
    toJSON() {
        const signatures = Object.values(this.signatures).map((signature) => {
            return signature.toJSON();
        });
        return {
            signatures,
            signed: this.signed.toJSON(),
            ...this.unrecognizedFields,
        };
    }
    static fromJSON(type, data) {
        const { signed, signatures, ...rest } = data;
        if (!utils_1.guard.isDefined(signed) || !utils_1.guard.isObject(signed)) {
            throw new TypeError('signed is not defined');
        }
        if (type !== signed._type) {
            throw new error_1.ValueError(`expected '${type}', got ${signed['_type']}`);
        }
        let signedObj;
        switch (type) {
            case base_1.MetadataKind.Root:
                signedObj = root_1.Root.fromJSON(signed);
                break;
            case base_1.MetadataKind.Timestamp:
                signedObj = timestamp_1.Timestamp.fromJSON(signed);
                break;
            case base_1.MetadataKind.Snapshot:
                signedObj = snapshot_1.Snapshot.fromJSON(signed);
                break;
            case base_1.MetadataKind.Targets:
                signedObj = targets_1.Targets.fromJSON(signed);
                break;
            default:
                throw new TypeError('invalid metadata type');
        }
        const sigMap = signaturesFromJSON(signatures);
        return new Metadata(signedObj, sigMap, rest);
    }
}
exports.Metadata = Metadata;
function signaturesFromJSON(data) {
    if (!utils_1.guard.isObjectArray(data)) {
        throw new TypeError('signatures is not an array');
    }
    return data.reduce((acc, sigData) => {
        const signature = signature_1.Signature.fromJSON(sigData);
        return { ...acc, [signature.keyID]: signature };
    }, {});
}
PK~\PTP@tufjs/models/dist/error.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.UnsupportedAlgorithmError = exports.CryptoError = exports.LengthOrHashMismatchError = exports.UnsignedMetadataError = exports.RepositoryError = exports.ValueError = void 0;
// An error about insufficient values
class ValueError extends Error {
}
exports.ValueError = ValueError;
// An error with a repository's state, such as a missing file.
// It covers all exceptions that come from the repository side when
// looking from the perspective of users of metadata API or ngclient.
class RepositoryError extends Error {
}
exports.RepositoryError = RepositoryError;
// An error about metadata object with insufficient threshold of signatures.
class UnsignedMetadataError extends RepositoryError {
}
exports.UnsignedMetadataError = UnsignedMetadataError;
// An error while checking the length and hash values of an object.
class LengthOrHashMismatchError extends RepositoryError {
}
exports.LengthOrHashMismatchError = LengthOrHashMismatchError;
class CryptoError extends Error {
}
exports.CryptoError = CryptoError;
class UnsupportedAlgorithmError extends CryptoError {
}
exports.UnsupportedAlgorithmError = UnsupportedAlgorithmError;
PK~\"
@tufjs/models/dist/signature.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Signature = void 0;
/**
 * A container class containing information about a signature.
 *
 * Contains a signature and the keyid uniquely identifying the key used
 * to generate the signature.
 *
 * Provide a `fromJSON` method to create a Signature from a JSON object.
 */
class Signature {
    constructor(options) {
        const { keyID, sig } = options;
        this.keyID = keyID;
        this.sig = sig;
    }
    toJSON() {
        return {
            keyid: this.keyID,
            sig: this.sig,
        };
    }
    static fromJSON(data) {
        const { keyid, sig } = data;
        if (typeof keyid !== 'string') {
            throw new TypeError('keyid must be a string');
        }
        if (typeof sig !== 'string') {
            throw new TypeError('sig must be a string');
        }
        return new Signature({
            keyID: keyid,
            sig: sig,
        });
    }
}
exports.Signature = Signature;
PK~\vR@tufjs/models/dist/file.jsnu["use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TargetFile = exports.MetaFile = void 0;
const crypto_1 = __importDefault(require("crypto"));
const util_1 = __importDefault(require("util"));
const error_1 = require("./error");
const utils_1 = require("./utils");
// A container with information about a particular metadata file.
//
// This class is used for Timestamp and Snapshot metadata.
class MetaFile {
    constructor(opts) {
        if (opts.version <= 0) {
            throw new error_1.ValueError('Metafile version must be at least 1');
        }
        if (opts.length !== undefined) {
            validateLength(opts.length);
        }
        this.version = opts.version;
        this.length = opts.length;
        this.hashes = opts.hashes;
        this.unrecognizedFields = opts.unrecognizedFields || {};
    }
    equals(other) {
        if (!(other instanceof MetaFile)) {
            return false;
        }
        return (this.version === other.version &&
            this.length === other.length &&
            util_1.default.isDeepStrictEqual(this.hashes, other.hashes) &&
            util_1.default.isDeepStrictEqual(this.unrecognizedFields, other.unrecognizedFields));
    }
    verify(data) {
        // Verifies that the given data matches the expected length.
        if (this.length !== undefined) {
            if (data.length !== this.length) {
                throw new error_1.LengthOrHashMismatchError(`Expected length ${this.length} but got ${data.length}`);
            }
        }
        // Verifies that the given data matches the supplied hashes.
        if (this.hashes) {
            Object.entries(this.hashes).forEach(([key, value]) => {
                let hash;
                try {
                    hash = crypto_1.default.createHash(key);
                }
                catch (e) {
                    throw new error_1.LengthOrHashMismatchError(`Hash algorithm ${key} not supported`);
                }
                const observedHash = hash.update(data).digest('hex');
                if (observedHash !== value) {
                    throw new error_1.LengthOrHashMismatchError(`Expected hash ${value} but got ${observedHash}`);
                }
            });
        }
    }
    toJSON() {
        const json = {
            version: this.version,
            ...this.unrecognizedFields,
        };
        if (this.length !== undefined) {
            json.length = this.length;
        }
        if (this.hashes) {
            json.hashes = this.hashes;
        }
        return json;
    }
    static fromJSON(data) {
        const { version, length, hashes, ...rest } = data;
        if (typeof version !== 'number') {
            throw new TypeError('version must be a number');
        }
        if (utils_1.guard.isDefined(length) && typeof length !== 'number') {
            throw new TypeError('length must be a number');
        }
        if (utils_1.guard.isDefined(hashes) && !utils_1.guard.isStringRecord(hashes)) {
            throw new TypeError('hashes must be string keys and values');
        }
        return new MetaFile({
            version,
            length,
            hashes,
            unrecognizedFields: rest,
        });
    }
}
exports.MetaFile = MetaFile;
// Container for info about a particular target file.
//
// This class is used for Target metadata.
class TargetFile {
    constructor(opts) {
        validateLength(opts.length);
        this.length = opts.length;
        this.path = opts.path;
        this.hashes = opts.hashes;
        this.unrecognizedFields = opts.unrecognizedFields || {};
    }
    get custom() {
        const custom = this.unrecognizedFields['custom'];
        if (!custom || Array.isArray(custom) || !(typeof custom === 'object')) {
            return {};
        }
        return custom;
    }
    equals(other) {
        if (!(other instanceof TargetFile)) {
            return false;
        }
        return (this.length === other.length &&
            this.path === other.path &&
            util_1.default.isDeepStrictEqual(this.hashes, other.hashes) &&
            util_1.default.isDeepStrictEqual(this.unrecognizedFields, other.unrecognizedFields));
    }
    async verify(stream) {
        let observedLength = 0;
        // Create a digest for each hash algorithm
        const digests = Object.keys(this.hashes).reduce((acc, key) => {
            try {
                acc[key] = crypto_1.default.createHash(key);
            }
            catch (e) {
                throw new error_1.LengthOrHashMismatchError(`Hash algorithm ${key} not supported`);
            }
            return acc;
        }, {});
        // Read stream chunk by chunk
        for await (const chunk of stream) {
            // Keep running tally of stream length
            observedLength += chunk.length;
            // Append chunk to each digest
            Object.values(digests).forEach((digest) => {
                digest.update(chunk);
            });
        }
        // Verify length matches expected value
        if (observedLength !== this.length) {
            throw new error_1.LengthOrHashMismatchError(`Expected length ${this.length} but got ${observedLength}`);
        }
        // Verify each digest matches expected value
        Object.entries(digests).forEach(([key, value]) => {
            const expected = this.hashes[key];
            const actual = value.digest('hex');
            if (actual !== expected) {
                throw new error_1.LengthOrHashMismatchError(`Expected hash ${expected} but got ${actual}`);
            }
        });
    }
    toJSON() {
        return {
            length: this.length,
            hashes: this.hashes,
            ...this.unrecognizedFields,
        };
    }
    static fromJSON(path, data) {
        const { length, hashes, ...rest } = data;
        if (typeof length !== 'number') {
            throw new TypeError('length must be a number');
        }
        if (!utils_1.guard.isStringRecord(hashes)) {
            throw new TypeError('hashes must have string keys and values');
        }
        return new TargetFile({
            length,
            path,
            hashes,
            unrecognizedFields: rest,
        });
    }
}
exports.TargetFile = TargetFile;
// Check that supplied length if valid
function validateLength(length) {
    if (length < 0) {
        throw new error_1.ValueError('Length must be at least 0');
    }
}
PK~\v&A1,,@tufjs/models/dist/role.jsnu["use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SuccinctRoles = exports.DelegatedRole = exports.Role = exports.TOP_LEVEL_ROLE_NAMES = void 0;
const crypto_1 = __importDefault(require("crypto"));
const minimatch_1 = require("minimatch");
const util_1 = __importDefault(require("util"));
const error_1 = require("./error");
const utils_1 = require("./utils");
exports.TOP_LEVEL_ROLE_NAMES = [
    'root',
    'targets',
    'snapshot',
    'timestamp',
];
/**
 * Container that defines which keys are required to sign roles metadata.
 *
 * Role defines how many keys are required to successfully sign the roles
 * metadata, and which keys are accepted.
 */
class Role {
    constructor(options) {
        const { keyIDs, threshold, unrecognizedFields } = options;
        if (hasDuplicates(keyIDs)) {
            throw new error_1.ValueError('duplicate key IDs found');
        }
        if (threshold < 1) {
            throw new error_1.ValueError('threshold must be at least 1');
        }
        this.keyIDs = keyIDs;
        this.threshold = threshold;
        this.unrecognizedFields = unrecognizedFields || {};
    }
    equals(other) {
        if (!(other instanceof Role)) {
            return false;
        }
        return (this.threshold === other.threshold &&
            util_1.default.isDeepStrictEqual(this.keyIDs, other.keyIDs) &&
            util_1.default.isDeepStrictEqual(this.unrecognizedFields, other.unrecognizedFields));
    }
    toJSON() {
        return {
            keyids: this.keyIDs,
            threshold: this.threshold,
            ...this.unrecognizedFields,
        };
    }
    static fromJSON(data) {
        const { keyids, threshold, ...rest } = data;
        if (!utils_1.guard.isStringArray(keyids)) {
            throw new TypeError('keyids must be an array');
        }
        if (typeof threshold !== 'number') {
            throw new TypeError('threshold must be a number');
        }
        return new Role({
            keyIDs: keyids,
            threshold,
            unrecognizedFields: rest,
        });
    }
}
exports.Role = Role;
function hasDuplicates(array) {
    return new Set(array).size !== array.length;
}
/**
 * A container with information about a delegated role.
 *
 * A delegation can happen in two ways:
 *   - ``paths`` is set: delegates targets matching any path pattern in ``paths``
 *   - ``pathHashPrefixes`` is set: delegates targets whose target path hash
 *      starts with any of the prefixes in ``pathHashPrefixes``
 *
 *   ``paths`` and ``pathHashPrefixes`` are mutually exclusive: both cannot be
 *   set, at least one of them must be set.
 */
class DelegatedRole extends Role {
    constructor(opts) {
        super(opts);
        const { name, terminating, paths, pathHashPrefixes } = opts;
        this.name = name;
        this.terminating = terminating;
        if (opts.paths && opts.pathHashPrefixes) {
            throw new error_1.ValueError('paths and pathHashPrefixes are mutually exclusive');
        }
        this.paths = paths;
        this.pathHashPrefixes = pathHashPrefixes;
    }
    equals(other) {
        if (!(other instanceof DelegatedRole)) {
            return false;
        }
        return (super.equals(other) &&
            this.name === other.name &&
            this.terminating === other.terminating &&
            util_1.default.isDeepStrictEqual(this.paths, other.paths) &&
            util_1.default.isDeepStrictEqual(this.pathHashPrefixes, other.pathHashPrefixes));
    }
    isDelegatedPath(targetFilepath) {
        if (this.paths) {
            return this.paths.some((pathPattern) => isTargetInPathPattern(targetFilepath, pathPattern));
        }
        if (this.pathHashPrefixes) {
            const hasher = crypto_1.default.createHash('sha256');
            const pathHash = hasher.update(targetFilepath).digest('hex');
            return this.pathHashPrefixes.some((pathHashPrefix) => pathHash.startsWith(pathHashPrefix));
        }
        return false;
    }
    toJSON() {
        const json = {
            ...super.toJSON(),
            name: this.name,
            terminating: this.terminating,
        };
        if (this.paths) {
            json.paths = this.paths;
        }
        if (this.pathHashPrefixes) {
            json.path_hash_prefixes = this.pathHashPrefixes;
        }
        return json;
    }
    static fromJSON(data) {
        const { keyids, threshold, name, terminating, paths, path_hash_prefixes, ...rest } = data;
        if (!utils_1.guard.isStringArray(keyids)) {
            throw new TypeError('keyids must be an array of strings');
        }
        if (typeof threshold !== 'number') {
            throw new TypeError('threshold must be a number');
        }
        if (typeof name !== 'string') {
            throw new TypeError('name must be a string');
        }
        if (typeof terminating !== 'boolean') {
            throw new TypeError('terminating must be a boolean');
        }
        if (utils_1.guard.isDefined(paths) && !utils_1.guard.isStringArray(paths)) {
            throw new TypeError('paths must be an array of strings');
        }
        if (utils_1.guard.isDefined(path_hash_prefixes) &&
            !utils_1.guard.isStringArray(path_hash_prefixes)) {
            throw new TypeError('path_hash_prefixes must be an array of strings');
        }
        return new DelegatedRole({
            keyIDs: keyids,
            threshold,
            name,
            terminating,
            paths,
            pathHashPrefixes: path_hash_prefixes,
            unrecognizedFields: rest,
        });
    }
}
exports.DelegatedRole = DelegatedRole;
// JS version of Ruby's Array#zip
const zip = (a, b) => a.map((k, i) => [k, b[i]]);
function isTargetInPathPattern(target, pattern) {
    const targetParts = target.split('/');
    const patternParts = pattern.split('/');
    if (patternParts.length != targetParts.length) {
        return false;
    }
    return zip(targetParts, patternParts).every(([targetPart, patternPart]) => (0, minimatch_1.minimatch)(targetPart, patternPart));
}
/**
 * Succinctly defines a hash bin delegation graph.
 *
 * A ``SuccinctRoles`` object describes a delegation graph that covers all
 * targets, distributing them uniformly over the delegated roles (i.e. bins)
 * in the graph.
 *
 * The total number of bins is 2 to the power of the passed ``bit_length``.
 *
 * Bin names are the concatenation of the passed ``name_prefix`` and a
 * zero-padded hex representation of the bin index separated by a hyphen.
 *
 * The passed ``keyids`` and ``threshold`` is used for each bin, and each bin
 * is 'terminating'.
 *
 * For details: https://github.com/theupdateframework/taps/blob/master/tap15.md
 */
class SuccinctRoles extends Role {
    constructor(opts) {
        super(opts);
        const { bitLength, namePrefix } = opts;
        if (bitLength <= 0 || bitLength > 32) {
            throw new error_1.ValueError('bitLength must be between 1 and 32');
        }
        this.bitLength = bitLength;
        this.namePrefix = namePrefix;
        // Calculate the suffix_len value based on the total number of bins in
        // hex. If bit_length = 10 then number_of_bins = 1024 or bin names will
        // have a suffix between "000" and "3ff" in hex and suffix_len will be 3
        // meaning the third bin will have a suffix of "003".
        this.numberOfBins = Math.pow(2, bitLength);
        // suffix_len is calculated based on "number_of_bins - 1" as the name
        // of the last bin contains the number "number_of_bins -1" as a suffix.
        this.suffixLen = (this.numberOfBins - 1).toString(16).length;
    }
    equals(other) {
        if (!(other instanceof SuccinctRoles)) {
            return false;
        }
        return (super.equals(other) &&
            this.bitLength === other.bitLength &&
            this.namePrefix === other.namePrefix);
    }
    /***
     * Calculates the name of the delegated role responsible for 'target_filepath'.
     *
     * The target at path ''target_filepath' is assigned to a bin by casting
     * the left-most 'bit_length' of bits of the file path hash digest to
     * int, using it as bin index between 0 and '2**bit_length - 1'.
     *
     * Args:
     *  target_filepath: URL path to a target file, relative to a base
     *  targets URL.
     */
    getRoleForTarget(targetFilepath) {
        const hasher = crypto_1.default.createHash('sha256');
        const hasherBuffer = hasher.update(targetFilepath).digest();
        // can't ever need more than 4 bytes (32 bits).
        const hashBytes = hasherBuffer.subarray(0, 4);
        // Right shift hash bytes, so that we only have the leftmost
        // bit_length bits that we care about.
        const shiftValue = 32 - this.bitLength;
        const binNumber = hashBytes.readUInt32BE() >>> shiftValue;
        // Add zero padding if necessary and cast to hex the suffix.
        const suffix = binNumber.toString(16).padStart(this.suffixLen, '0');
        return `${this.namePrefix}-${suffix}`;
    }
    *getRoles() {
        for (let i = 0; i < this.numberOfBins; i++) {
            const suffix = i.toString(16).padStart(this.suffixLen, '0');
            yield `${this.namePrefix}-${suffix}`;
        }
    }
    /***
     * Determines whether the given ``role_name`` is in one of
     * the delegated roles that ``SuccinctRoles`` represents.
     *
     * Args:
     *  role_name: The name of the role to check against.
     */
    isDelegatedRole(roleName) {
        const desiredPrefix = this.namePrefix + '-';
        if (!roleName.startsWith(desiredPrefix)) {
            return false;
        }
        const suffix = roleName.slice(desiredPrefix.length, roleName.length);
        if (suffix.length != this.suffixLen) {
            return false;
        }
        // make sure the suffix is a hex string
        if (!suffix.match(/^[0-9a-fA-F]+$/)) {
            return false;
        }
        const num = parseInt(suffix, 16);
        return 0 <= num && num < this.numberOfBins;
    }
    toJSON() {
        const json = {
            ...super.toJSON(),
            bit_length: this.bitLength,
            name_prefix: this.namePrefix,
        };
        return json;
    }
    static fromJSON(data) {
        const { keyids, threshold, bit_length, name_prefix, ...rest } = data;
        if (!utils_1.guard.isStringArray(keyids)) {
            throw new TypeError('keyids must be an array of strings');
        }
        if (typeof threshold !== 'number') {
            throw new TypeError('threshold must be a number');
        }
        if (typeof bit_length !== 'number') {
            throw new TypeError('bit_length must be a number');
        }
        if (typeof name_prefix !== 'string') {
            throw new TypeError('name_prefix must be a string');
        }
        return new SuccinctRoles({
            keyIDs: keyids,
            threshold,
            bitLength: bit_length,
            namePrefix: name_prefix,
            unrecognizedFields: rest,
        });
    }
}
exports.SuccinctRoles = SuccinctRoles;
PK~\2F"@tufjs/canonical-json/package.jsonnu[{
  "_id": "@tufjs/canonical-json@2.0.0",
  "_inBundle": true,
  "_location": "/npm/@tufjs/canonical-json",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm/@tufjs/models"
  ],
  "author": {
    "name": "bdehamer@github.com"
  },
  "bugs": {
    "url": "https://github.com/theupdateframework/tuf-js/issues"
  },
  "description": "OLPC JSON canonicalization",
  "engines": {
    "node": "^16.14.0 || >=18.0.0"
  },
  "files": [
    "lib/"
  ],
  "homepage": "https://github.com/theupdateframework/tuf-js/tree/main/packages/canonical-json#readme",
  "keywords": [
    "json",
    "canonical",
    "canonicalize",
    "canonicalization",
    "crypto",
    "signature",
    "olpc"
  ],
  "license": "MIT",
  "main": "lib/index.js",
  "name": "@tufjs/canonical-json",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/theupdateframework/tuf-js.git"
  },
  "scripts": {
    "test": "jest"
  },
  "typings": "lib/index.d.ts",
  "version": "2.0.0"
}
PK~\?E"@tufjs/canonical-json/lib/index.jsnu[const COMMA = ',';
const COLON = ':';
const LEFT_SQUARE_BRACKET = '[';
const RIGHT_SQUARE_BRACKET = ']';
const LEFT_CURLY_BRACKET = '{';
const RIGHT_CURLY_BRACKET = '}';

// Recursively encodes the supplied object according to the canonical JSON form
// as specified at http://wiki.laptop.org/go/Canonical_JSON. It's a restricted
// dialect of JSON in which keys are lexically sorted, floats are not allowed,
// and only double quotes and backslashes are escaped.
function canonicalize(object) {
  const buffer = [];
  if (typeof object === 'string') {
    buffer.push(canonicalizeString(object));
  } else if (typeof object === 'boolean') {
    buffer.push(JSON.stringify(object));
  } else if (Number.isInteger(object)) {
    buffer.push(JSON.stringify(object));
  } else if (object === null) {
    buffer.push(JSON.stringify(object));
  } else if (Array.isArray(object)) {
    buffer.push(LEFT_SQUARE_BRACKET);
    let first = true;
    object.forEach((element) => {
      if (!first) {
        buffer.push(COMMA);
      }
      first = false;
      buffer.push(canonicalize(element));
    });
    buffer.push(RIGHT_SQUARE_BRACKET);
  } else if (typeof object === 'object') {
    buffer.push(LEFT_CURLY_BRACKET);
    let first = true;
    Object.keys(object)
      .sort()
      .forEach((property) => {
        if (!first) {
          buffer.push(COMMA);
        }
        first = false;
        buffer.push(canonicalizeString(property));
        buffer.push(COLON);
        buffer.push(canonicalize(object[property]));
      });
    buffer.push(RIGHT_CURLY_BRACKET);
  } else {
    throw new TypeError('cannot encode ' + object.toString());
  }

  return buffer.join('');
}

// String canonicalization consists of escaping backslash (\) and double
// quote (") characters and wrapping the resulting string in double quotes.
function canonicalizeString(string) {
  const escapedString = string.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
  return '"' + escapedString + '"';
}

module.exports = {
  canonicalize,
};
PK~\М@@@tufjs/canonical-json/LICENSEnu[MIT License

Copyright (c) 2022 GitHub and the TUF Contributors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
PK~\2zzsignal-exit/package.jsonnu[{
  "_id": "signal-exit@4.1.0",
  "_inBundle": true,
  "_location": "/npm/signal-exit",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm/foreground-child",
    "/npm/write-file-atomic"
  ],
  "author": {
    "name": "Ben Coe",
    "email": "ben@npmjs.com"
  },
  "browser": "./dist/mjs/browser.js",
  "bugs": {
    "url": "https://github.com/tapjs/signal-exit/issues"
  },
  "description": "when you want to fire an event no matter how a process exits.",
  "devDependencies": {
    "@types/cross-spawn": "^6.0.2",
    "@types/node": "^18.15.11",
    "@types/signal-exit": "^3.0.1",
    "@types/tap": "^15.0.8",
    "c8": "^7.13.0",
    "prettier": "^2.8.6",
    "tap": "^16.3.4",
    "ts-node": "^10.9.1",
    "typedoc": "^0.23.28",
    "typescript": "^5.0.2"
  },
  "engines": {
    "node": ">=14"
  },
  "exports": {
    ".": {
      "import": {
        "types": "./dist/mjs/index.d.ts",
        "default": "./dist/mjs/index.js"
      },
      "require": {
        "types": "./dist/cjs/index.d.ts",
        "default": "./dist/cjs/index.js"
      }
    },
    "./signals": {
      "import": {
        "types": "./dist/mjs/signals.d.ts",
        "default": "./dist/mjs/signals.js"
      },
      "require": {
        "types": "./dist/cjs/signals.d.ts",
        "default": "./dist/cjs/signals.js"
      }
    },
    "./browser": {
      "import": {
        "types": "./dist/mjs/browser.d.ts",
        "default": "./dist/mjs/browser.js"
      },
      "require": {
        "types": "./dist/cjs/browser.d.ts",
        "default": "./dist/cjs/browser.js"
      }
    }
  },
  "files": [
    "dist"
  ],
  "funding": {
    "url": "https://github.com/sponsors/isaacs"
  },
  "homepage": "https://github.com/tapjs/signal-exit#readme",
  "keywords": [
    "signal",
    "exit"
  ],
  "license": "ISC",
  "main": "./dist/cjs/index.js",
  "module": "./dist/mjs/index.js",
  "name": "signal-exit",
  "prettier": {
    "semi": false,
    "printWidth": 75,
    "tabWidth": 2,
    "useTabs": false,
    "singleQuote": true,
    "jsxSingleQuote": false,
    "bracketSameLine": true,
    "arrowParens": "avoid",
    "endOfLine": "lf"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/tapjs/signal-exit.git"
  },
  "scripts": {
    "format": "prettier --write . --loglevel warn",
    "postversion": "npm publish",
    "prepare": "tsc -p tsconfig.json && tsc -p tsconfig-esm.json && bash ./scripts/fixup.sh",
    "preprepare": "rm -rf dist",
    "prepublishOnly": "git push origin --follow-tags",
    "presnap": "npm run prepare",
    "pretest": "npm run prepare",
    "preversion": "npm test",
    "snap": "c8 tap",
    "test": "c8 tap",
    "typedoc": "typedoc --tsconfig tsconfig-esm.json ./src/*.ts"
  },
  "tap": {
    "coverage": false,
    "jobs": 1,
    "node-arg": [
      "--no-warnings",
      "--loader",
      "ts-node/esm"
    ],
    "ts": false
  },
  "types": "./dist/mjs/index.d.ts",
  "version": "4.1.0"
}
PK~\x!signal-exit/dist/mjs/package.jsonnu[{
  "type": "module"
}
PK~\signal-exit/dist/mjs/signals.jsnu[/**
 * This is not the set of all possible signals.
 *
 * It IS, however, the set of all signals that trigger
 * an exit on either Linux or BSD systems.  Linux is a
 * superset of the signal names supported on BSD, and
 * the unknown signals just fail to register, so we can
 * catch that easily enough.
 *
 * Windows signals are a different set, since there are
 * signals that terminate Windows processes, but don't
 * terminate (or don't even exist) on Posix systems.
 *
 * Don't bother with SIGKILL.  It's uncatchable, which
 * means that we can't fire any callbacks anyway.
 *
 * If a user does happen to register a handler on a non-
 * fatal signal like SIGWINCH or something, and then
 * exit, it'll end up firing `process.emit('exit')`, so
 * the handler will be fired anyway.
 *
 * SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised
 * artificially, inherently leave the process in a
 * state from which it is not safe to try and enter JS
 * listeners.
 */
export const signals = [];
signals.push('SIGHUP', 'SIGINT', 'SIGTERM');
if (process.platform !== 'win32') {
    signals.push('SIGALRM', 'SIGABRT', 'SIGVTALRM', 'SIGXCPU', 'SIGXFSZ', 'SIGUSR2', 'SIGTRAP', 'SIGSYS', 'SIGQUIT', 'SIGIOT'
    // should detect profiler and enable/disable accordingly.
    // see #21
    // 'SIGPROF'
    );
}
if (process.platform === 'linux') {
    signals.push('SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT');
}
//# sourceMappingURL=signals.js.mapPK~\DZT##signal-exit/dist/mjs/index.jsnu[// Note: since nyc uses this module to output coverage, any lines
// that are in the direct sync flow of nyc's outputCoverage are
// ignored, since we can never get coverage for them.
// grab a reference to node's real process object right away
import { signals } from './signals.js';
export { signals };
const processOk = (process) => !!process &&
    typeof process === 'object' &&
    typeof process.removeListener === 'function' &&
    typeof process.emit === 'function' &&
    typeof process.reallyExit === 'function' &&
    typeof process.listeners === 'function' &&
    typeof process.kill === 'function' &&
    typeof process.pid === 'number' &&
    typeof process.on === 'function';
const kExitEmitter = Symbol.for('signal-exit emitter');
const global = globalThis;
const ObjectDefineProperty = Object.defineProperty.bind(Object);
// teeny special purpose ee
class Emitter {
    emitted = {
        afterExit: false,
        exit: false,
    };
    listeners = {
        afterExit: [],
        exit: [],
    };
    count = 0;
    id = Math.random();
    constructor() {
        if (global[kExitEmitter]) {
            return global[kExitEmitter];
        }
        ObjectDefineProperty(global, kExitEmitter, {
            value: this,
            writable: false,
            enumerable: false,
            configurable: false,
        });
    }
    on(ev, fn) {
        this.listeners[ev].push(fn);
    }
    removeListener(ev, fn) {
        const list = this.listeners[ev];
        const i = list.indexOf(fn);
        /* c8 ignore start */
        if (i === -1) {
            return;
        }
        /* c8 ignore stop */
        if (i === 0 && list.length === 1) {
            list.length = 0;
        }
        else {
            list.splice(i, 1);
        }
    }
    emit(ev, code, signal) {
        if (this.emitted[ev]) {
            return false;
        }
        this.emitted[ev] = true;
        let ret = false;
        for (const fn of this.listeners[ev]) {
            ret = fn(code, signal) === true || ret;
        }
        if (ev === 'exit') {
            ret = this.emit('afterExit', code, signal) || ret;
        }
        return ret;
    }
}
class SignalExitBase {
}
const signalExitWrap = (handler) => {
    return {
        onExit(cb, opts) {
            return handler.onExit(cb, opts);
        },
        load() {
            return handler.load();
        },
        unload() {
            return handler.unload();
        },
    };
};
class SignalExitFallback extends SignalExitBase {
    onExit() {
        return () => { };
    }
    load() { }
    unload() { }
}
class SignalExit extends SignalExitBase {
    // "SIGHUP" throws an `ENOSYS` error on Windows,
    // so use a supported signal instead
    /* c8 ignore start */
    #hupSig = process.platform === 'win32' ? 'SIGINT' : 'SIGHUP';
    /* c8 ignore stop */
    #emitter = new Emitter();
    #process;
    #originalProcessEmit;
    #originalProcessReallyExit;
    #sigListeners = {};
    #loaded = false;
    constructor(process) {
        super();
        this.#process = process;
        // { : , ... }
        this.#sigListeners = {};
        for (const sig of signals) {
            this.#sigListeners[sig] = () => {
                // If there are no other listeners, an exit is coming!
                // Simplest way: remove us and then re-send the signal.
                // We know that this will kill the process, so we can
                // safely emit now.
                const listeners = this.#process.listeners(sig);
                let { count } = this.#emitter;
                // This is a workaround for the fact that signal-exit v3 and signal
                // exit v4 are not aware of each other, and each will attempt to let
                // the other handle it, so neither of them do. To correct this, we
                // detect if we're the only handler *except* for previous versions
                // of signal-exit, and increment by the count of listeners it has
                // created.
                /* c8 ignore start */
                const p = process;
                if (typeof p.__signal_exit_emitter__ === 'object' &&
                    typeof p.__signal_exit_emitter__.count === 'number') {
                    count += p.__signal_exit_emitter__.count;
                }
                /* c8 ignore stop */
                if (listeners.length === count) {
                    this.unload();
                    const ret = this.#emitter.emit('exit', null, sig);
                    /* c8 ignore start */
                    const s = sig === 'SIGHUP' ? this.#hupSig : sig;
                    if (!ret)
                        process.kill(process.pid, s);
                    /* c8 ignore stop */
                }
            };
        }
        this.#originalProcessReallyExit = process.reallyExit;
        this.#originalProcessEmit = process.emit;
    }
    onExit(cb, opts) {
        /* c8 ignore start */
        if (!processOk(this.#process)) {
            return () => { };
        }
        /* c8 ignore stop */
        if (this.#loaded === false) {
            this.load();
        }
        const ev = opts?.alwaysLast ? 'afterExit' : 'exit';
        this.#emitter.on(ev, cb);
        return () => {
            this.#emitter.removeListener(ev, cb);
            if (this.#emitter.listeners['exit'].length === 0 &&
                this.#emitter.listeners['afterExit'].length === 0) {
                this.unload();
            }
        };
    }
    load() {
        if (this.#loaded) {
            return;
        }
        this.#loaded = true;
        // This is the number of onSignalExit's that are in play.
        // It's important so that we can count the correct number of
        // listeners on signals, and don't wait for the other one to
        // handle it instead of us.
        this.#emitter.count += 1;
        for (const sig of signals) {
            try {
                const fn = this.#sigListeners[sig];
                if (fn)
                    this.#process.on(sig, fn);
            }
            catch (_) { }
        }
        this.#process.emit = (ev, ...a) => {
            return this.#processEmit(ev, ...a);
        };
        this.#process.reallyExit = (code) => {
            return this.#processReallyExit(code);
        };
    }
    unload() {
        if (!this.#loaded) {
            return;
        }
        this.#loaded = false;
        signals.forEach(sig => {
            const listener = this.#sigListeners[sig];
            /* c8 ignore start */
            if (!listener) {
                throw new Error('Listener not defined for signal: ' + sig);
            }
            /* c8 ignore stop */
            try {
                this.#process.removeListener(sig, listener);
                /* c8 ignore start */
            }
            catch (_) { }
            /* c8 ignore stop */
        });
        this.#process.emit = this.#originalProcessEmit;
        this.#process.reallyExit = this.#originalProcessReallyExit;
        this.#emitter.count -= 1;
    }
    #processReallyExit(code) {
        /* c8 ignore start */
        if (!processOk(this.#process)) {
            return 0;
        }
        this.#process.exitCode = code || 0;
        /* c8 ignore stop */
        this.#emitter.emit('exit', this.#process.exitCode, null);
        return this.#originalProcessReallyExit.call(this.#process, this.#process.exitCode);
    }
    #processEmit(ev, ...args) {
        const og = this.#originalProcessEmit;
        if (ev === 'exit' && processOk(this.#process)) {
            if (typeof args[0] === 'number') {
                this.#process.exitCode = args[0];
                /* c8 ignore start */
            }
            /* c8 ignore start */
            const ret = og.call(this.#process, ev, ...args);
            /* c8 ignore start */
            this.#emitter.emit('exit', this.#process.exitCode, null);
            /* c8 ignore stop */
            return ret;
        }
        else {
            return og.call(this.#process, ev, ...args);
        }
    }
}
const process = globalThis.process;
// wrap so that we call the method on the actual handler, without
// exporting it directly.
export const { 
/**
 * Called when the process is exiting, whether via signal, explicit
 * exit, or running out of stuff to do.
 *
 * If the global process object is not suitable for instrumentation,
 * then this will be a no-op.
 *
 * Returns a function that may be used to unload signal-exit.
 */
onExit, 
/**
 * Load the listeners.  Likely you never need to call this, unless
 * doing a rather deep integration with signal-exit functionality.
 * Mostly exposed for the benefit of testing.
 *
 * @internal
 */
load, 
/**
 * Unload the listeners.  Likely you never need to call this, unless
 * doing a rather deep integration with signal-exit functionality.
 * Mostly exposed for the benefit of testing.
 *
 * @internal
 */
unload, } = signalExitWrap(processOk(process) ? new SignalExit(process) : new SignalExitFallback());
//# sourceMappingURL=index.js.mapPK~\픯signal-exit/dist/mjs/browser.jsnu[export const onExit = () => () => { };
export const load = () => { };
export const unload = () => { };
//# sourceMappingURL=browser.js.mapPK~\>!signal-exit/dist/cjs/package.jsonnu[{
  "type": "commonjs"
}
PK~\Hsignal-exit/dist/cjs/signals.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.signals = void 0;
/**
 * This is not the set of all possible signals.
 *
 * It IS, however, the set of all signals that trigger
 * an exit on either Linux or BSD systems.  Linux is a
 * superset of the signal names supported on BSD, and
 * the unknown signals just fail to register, so we can
 * catch that easily enough.
 *
 * Windows signals are a different set, since there are
 * signals that terminate Windows processes, but don't
 * terminate (or don't even exist) on Posix systems.
 *
 * Don't bother with SIGKILL.  It's uncatchable, which
 * means that we can't fire any callbacks anyway.
 *
 * If a user does happen to register a handler on a non-
 * fatal signal like SIGWINCH or something, and then
 * exit, it'll end up firing `process.emit('exit')`, so
 * the handler will be fired anyway.
 *
 * SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised
 * artificially, inherently leave the process in a
 * state from which it is not safe to try and enter JS
 * listeners.
 */
exports.signals = [];
exports.signals.push('SIGHUP', 'SIGINT', 'SIGTERM');
if (process.platform !== 'win32') {
    exports.signals.push('SIGALRM', 'SIGABRT', 'SIGVTALRM', 'SIGXCPU', 'SIGXFSZ', 'SIGUSR2', 'SIGTRAP', 'SIGSYS', 'SIGQUIT', 'SIGIOT'
    // should detect profiler and enable/disable accordingly.
    // see #21
    // 'SIGPROF'
    );
}
if (process.platform === 'linux') {
    exports.signals.push('SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT');
}
//# sourceMappingURL=signals.js.mapPK~\IS$$signal-exit/dist/cjs/index.jsnu["use strict";
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.unload = exports.load = exports.onExit = exports.signals = void 0;
// Note: since nyc uses this module to output coverage, any lines
// that are in the direct sync flow of nyc's outputCoverage are
// ignored, since we can never get coverage for them.
// grab a reference to node's real process object right away
const signals_js_1 = require("./signals.js");
Object.defineProperty(exports, "signals", { enumerable: true, get: function () { return signals_js_1.signals; } });
const processOk = (process) => !!process &&
    typeof process === 'object' &&
    typeof process.removeListener === 'function' &&
    typeof process.emit === 'function' &&
    typeof process.reallyExit === 'function' &&
    typeof process.listeners === 'function' &&
    typeof process.kill === 'function' &&
    typeof process.pid === 'number' &&
    typeof process.on === 'function';
const kExitEmitter = Symbol.for('signal-exit emitter');
const global = globalThis;
const ObjectDefineProperty = Object.defineProperty.bind(Object);
// teeny special purpose ee
class Emitter {
    emitted = {
        afterExit: false,
        exit: false,
    };
    listeners = {
        afterExit: [],
        exit: [],
    };
    count = 0;
    id = Math.random();
    constructor() {
        if (global[kExitEmitter]) {
            return global[kExitEmitter];
        }
        ObjectDefineProperty(global, kExitEmitter, {
            value: this,
            writable: false,
            enumerable: false,
            configurable: false,
        });
    }
    on(ev, fn) {
        this.listeners[ev].push(fn);
    }
    removeListener(ev, fn) {
        const list = this.listeners[ev];
        const i = list.indexOf(fn);
        /* c8 ignore start */
        if (i === -1) {
            return;
        }
        /* c8 ignore stop */
        if (i === 0 && list.length === 1) {
            list.length = 0;
        }
        else {
            list.splice(i, 1);
        }
    }
    emit(ev, code, signal) {
        if (this.emitted[ev]) {
            return false;
        }
        this.emitted[ev] = true;
        let ret = false;
        for (const fn of this.listeners[ev]) {
            ret = fn(code, signal) === true || ret;
        }
        if (ev === 'exit') {
            ret = this.emit('afterExit', code, signal) || ret;
        }
        return ret;
    }
}
class SignalExitBase {
}
const signalExitWrap = (handler) => {
    return {
        onExit(cb, opts) {
            return handler.onExit(cb, opts);
        },
        load() {
            return handler.load();
        },
        unload() {
            return handler.unload();
        },
    };
};
class SignalExitFallback extends SignalExitBase {
    onExit() {
        return () => { };
    }
    load() { }
    unload() { }
}
class SignalExit extends SignalExitBase {
    // "SIGHUP" throws an `ENOSYS` error on Windows,
    // so use a supported signal instead
    /* c8 ignore start */
    #hupSig = process.platform === 'win32' ? 'SIGINT' : 'SIGHUP';
    /* c8 ignore stop */
    #emitter = new Emitter();
    #process;
    #originalProcessEmit;
    #originalProcessReallyExit;
    #sigListeners = {};
    #loaded = false;
    constructor(process) {
        super();
        this.#process = process;
        // { : , ... }
        this.#sigListeners = {};
        for (const sig of signals_js_1.signals) {
            this.#sigListeners[sig] = () => {
                // If there are no other listeners, an exit is coming!
                // Simplest way: remove us and then re-send the signal.
                // We know that this will kill the process, so we can
                // safely emit now.
                const listeners = this.#process.listeners(sig);
                let { count } = this.#emitter;
                // This is a workaround for the fact that signal-exit v3 and signal
                // exit v4 are not aware of each other, and each will attempt to let
                // the other handle it, so neither of them do. To correct this, we
                // detect if we're the only handler *except* for previous versions
                // of signal-exit, and increment by the count of listeners it has
                // created.
                /* c8 ignore start */
                const p = process;
                if (typeof p.__signal_exit_emitter__ === 'object' &&
                    typeof p.__signal_exit_emitter__.count === 'number') {
                    count += p.__signal_exit_emitter__.count;
                }
                /* c8 ignore stop */
                if (listeners.length === count) {
                    this.unload();
                    const ret = this.#emitter.emit('exit', null, sig);
                    /* c8 ignore start */
                    const s = sig === 'SIGHUP' ? this.#hupSig : sig;
                    if (!ret)
                        process.kill(process.pid, s);
                    /* c8 ignore stop */
                }
            };
        }
        this.#originalProcessReallyExit = process.reallyExit;
        this.#originalProcessEmit = process.emit;
    }
    onExit(cb, opts) {
        /* c8 ignore start */
        if (!processOk(this.#process)) {
            return () => { };
        }
        /* c8 ignore stop */
        if (this.#loaded === false) {
            this.load();
        }
        const ev = opts?.alwaysLast ? 'afterExit' : 'exit';
        this.#emitter.on(ev, cb);
        return () => {
            this.#emitter.removeListener(ev, cb);
            if (this.#emitter.listeners['exit'].length === 0 &&
                this.#emitter.listeners['afterExit'].length === 0) {
                this.unload();
            }
        };
    }
    load() {
        if (this.#loaded) {
            return;
        }
        this.#loaded = true;
        // This is the number of onSignalExit's that are in play.
        // It's important so that we can count the correct number of
        // listeners on signals, and don't wait for the other one to
        // handle it instead of us.
        this.#emitter.count += 1;
        for (const sig of signals_js_1.signals) {
            try {
                const fn = this.#sigListeners[sig];
                if (fn)
                    this.#process.on(sig, fn);
            }
            catch (_) { }
        }
        this.#process.emit = (ev, ...a) => {
            return this.#processEmit(ev, ...a);
        };
        this.#process.reallyExit = (code) => {
            return this.#processReallyExit(code);
        };
    }
    unload() {
        if (!this.#loaded) {
            return;
        }
        this.#loaded = false;
        signals_js_1.signals.forEach(sig => {
            const listener = this.#sigListeners[sig];
            /* c8 ignore start */
            if (!listener) {
                throw new Error('Listener not defined for signal: ' + sig);
            }
            /* c8 ignore stop */
            try {
                this.#process.removeListener(sig, listener);
                /* c8 ignore start */
            }
            catch (_) { }
            /* c8 ignore stop */
        });
        this.#process.emit = this.#originalProcessEmit;
        this.#process.reallyExit = this.#originalProcessReallyExit;
        this.#emitter.count -= 1;
    }
    #processReallyExit(code) {
        /* c8 ignore start */
        if (!processOk(this.#process)) {
            return 0;
        }
        this.#process.exitCode = code || 0;
        /* c8 ignore stop */
        this.#emitter.emit('exit', this.#process.exitCode, null);
        return this.#originalProcessReallyExit.call(this.#process, this.#process.exitCode);
    }
    #processEmit(ev, ...args) {
        const og = this.#originalProcessEmit;
        if (ev === 'exit' && processOk(this.#process)) {
            if (typeof args[0] === 'number') {
                this.#process.exitCode = args[0];
                /* c8 ignore start */
            }
            /* c8 ignore start */
            const ret = og.call(this.#process, ev, ...args);
            /* c8 ignore start */
            this.#emitter.emit('exit', this.#process.exitCode, null);
            /* c8 ignore stop */
            return ret;
        }
        else {
            return og.call(this.#process, ev, ...args);
        }
    }
}
const process = globalThis.process;
// wrap so that we call the method on the actual handler, without
// exporting it directly.
_a = signalExitWrap(processOk(process) ? new SignalExit(process) : new SignalExitFallback()), 
/**
 * Called when the process is exiting, whether via signal, explicit
 * exit, or running out of stuff to do.
 *
 * If the global process object is not suitable for instrumentation,
 * then this will be a no-op.
 *
 * Returns a function that may be used to unload signal-exit.
 */
exports.onExit = _a.onExit, 
/**
 * Load the listeners.  Likely you never need to call this, unless
 * doing a rather deep integration with signal-exit functionality.
 * Mostly exposed for the benefit of testing.
 *
 * @internal
 */
exports.load = _a.load, 
/**
 * Unload the listeners.  Likely you never need to call this, unless
 * doing a rather deep integration with signal-exit functionality.
 * Mostly exposed for the benefit of testing.
 *
 * @internal
 */
exports.unload = _a.unload;
//# sourceMappingURL=index.js.mapPK~\N8I9BBsignal-exit/dist/cjs/browser.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.unload = exports.load = exports.onExit = void 0;
const onExit = () => () => { };
exports.onExit = onExit;
const load = () => { };
exports.load = load;
const unload = () => { };
exports.unload = unload;
//# sourceMappingURL=browser.js.mapPK~\{signal-exit/LICENSE.txtnu[The ISC License

Copyright (c) 2015-2023 Benjamin Coe, Isaac Z. Schlueter, and Contributors

Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice
appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE
LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
PK~\0Htuf-js/package.jsonnu[{
  "_id": "tuf-js@2.2.1",
  "_inBundle": true,
  "_location": "/npm/tuf-js",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm/@sigstore/tuf"
  ],
  "author": {
    "name": "bdehamer@github.com"
  },
  "bugs": {
    "url": "https://github.com/theupdateframework/tuf-js/issues"
  },
  "dependencies": {
    "@tufjs/models": "2.0.1",
    "debug": "^4.3.4",
    "make-fetch-happen": "^13.0.1"
  },
  "description": "JavaScript implementation of The Update Framework (TUF)",
  "devDependencies": {
    "@tufjs/repo-mock": "2.0.1",
    "@types/debug": "^4.1.12",
    "@types/make-fetch-happen": "^10.0.4"
  },
  "engines": {
    "node": "^16.14.0 || >=18.0.0"
  },
  "files": [
    "dist"
  ],
  "homepage": "https://github.com/theupdateframework/tuf-js/tree/main/packages/client#readme",
  "keywords": [
    "tuf",
    "security",
    "update"
  ],
  "license": "MIT",
  "main": "dist/index.js",
  "name": "tuf-js",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/theupdateframework/tuf-js.git"
  },
  "scripts": {
    "build": "tsc --build",
    "clean": "rm -rf dist",
    "test": "jest"
  },
  "types": "dist/index.d.ts",
  "version": "2.2.1"
}
PK~\М@@tuf-js/LICENSEnu[MIT License

Copyright (c) 2022 GitHub and the TUF Contributors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
PK~\7t;;tuf-js/dist/updater.jsnu["use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Updater = void 0;
const models_1 = require("@tufjs/models");
const debug_1 = __importDefault(require("debug"));
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const config_1 = require("./config");
const error_1 = require("./error");
const fetcher_1 = require("./fetcher");
const store_1 = require("./store");
const url = __importStar(require("./utils/url"));
const log = (0, debug_1.default)('tuf:cache');
class Updater {
    constructor(options) {
        const { metadataDir, metadataBaseUrl, targetDir, targetBaseUrl, fetcher, config, } = options;
        this.dir = metadataDir;
        this.metadataBaseUrl = metadataBaseUrl;
        this.targetDir = targetDir;
        this.targetBaseUrl = targetBaseUrl;
        this.forceCache = options.forceCache ?? false;
        const data = this.loadLocalMetadata(models_1.MetadataKind.Root);
        this.trustedSet = new store_1.TrustedMetadataStore(data);
        this.config = { ...config_1.defaultConfig, ...config };
        this.fetcher =
            fetcher ||
                new fetcher_1.DefaultFetcher({
                    timeout: this.config.fetchTimeout,
                    retry: this.config.fetchRetries ?? this.config.fetchRetry,
                });
    }
    // refresh and load the metadata before downloading the target
    // refresh should be called once after the client is initialized
    async refresh() {
        // If forceCache is true, try to load the timestamp from local storage
        // without fetching it from the remote. Otherwise, load the root and
        // timestamp from the remote per the TUF spec.
        if (this.forceCache) {
            // If anything fails, load the root and timestamp from the remote. This
            // should cover any situation where the local metadata is corrupted or
            // expired.
            try {
                await this.loadTimestamp({ checkRemote: false });
            }
            catch (error) {
                await this.loadRoot();
                await this.loadTimestamp();
            }
        }
        else {
            await this.loadRoot();
            await this.loadTimestamp();
        }
        await this.loadSnapshot();
        await this.loadTargets(models_1.MetadataKind.Targets, models_1.MetadataKind.Root);
    }
    // Returns the TargetFile instance with information for the given target path.
    //
    // Implicitly calls refresh if it hasn't already been called.
    async getTargetInfo(targetPath) {
        if (!this.trustedSet.targets) {
            await this.refresh();
        }
        return this.preorderDepthFirstWalk(targetPath);
    }
    async downloadTarget(targetInfo, filePath, targetBaseUrl) {
        const targetPath = filePath || this.generateTargetPath(targetInfo);
        if (!targetBaseUrl) {
            if (!this.targetBaseUrl) {
                throw new error_1.ValueError('Target base URL not set');
            }
            targetBaseUrl = this.targetBaseUrl;
        }
        let targetFilePath = targetInfo.path;
        const consistentSnapshot = this.trustedSet.root.signed.consistentSnapshot;
        if (consistentSnapshot && this.config.prefixTargetsWithHash) {
            const hashes = Object.values(targetInfo.hashes);
            const { dir, base } = path.parse(targetFilePath);
            const filename = `${hashes[0]}.${base}`;
            targetFilePath = dir ? `${dir}/${filename}` : filename;
        }
        const targetUrl = url.join(targetBaseUrl, targetFilePath);
        // Client workflow 5.7.3: download target file
        await this.fetcher.downloadFile(targetUrl, targetInfo.length, async (fileName) => {
            // Verify hashes and length of downloaded file
            await targetInfo.verify(fs.createReadStream(fileName));
            // Copy file to target path
            log('WRITE %s', targetPath);
            fs.copyFileSync(fileName, targetPath);
        });
        return targetPath;
    }
    async findCachedTarget(targetInfo, filePath) {
        if (!filePath) {
            filePath = this.generateTargetPath(targetInfo);
        }
        try {
            if (fs.existsSync(filePath)) {
                await targetInfo.verify(fs.createReadStream(filePath));
                return filePath;
            }
        }
        catch (error) {
            return; // File not found
        }
        return; // File not found
    }
    loadLocalMetadata(fileName) {
        const filePath = path.join(this.dir, `${fileName}.json`);
        log('READ %s', filePath);
        return fs.readFileSync(filePath);
    }
    // Sequentially load and persist on local disk every newer root metadata
    // version available on the remote.
    // Client workflow 5.3: update root role
    async loadRoot() {
        // Client workflow 5.3.2: version of trusted root metadata file
        const rootVersion = this.trustedSet.root.signed.version;
        const lowerBound = rootVersion + 1;
        const upperBound = lowerBound + this.config.maxRootRotations;
        for (let version = lowerBound; version <= upperBound; version++) {
            const rootUrl = url.join(this.metadataBaseUrl, `${version}.root.json`);
            try {
                // Client workflow 5.3.3: download new root metadata file
                const bytesData = await this.fetcher.downloadBytes(rootUrl, this.config.rootMaxLength);
                // Client workflow 5.3.4 - 5.4.7
                this.trustedSet.updateRoot(bytesData);
                // Client workflow 5.3.8: persist root metadata file
                this.persistMetadata(models_1.MetadataKind.Root, bytesData);
            }
            catch (error) {
                break;
            }
        }
    }
    // Load local and remote timestamp metadata.
    // Client workflow 5.4: update timestamp role
    async loadTimestamp({ checkRemote } = { checkRemote: true }) {
        // Load local and remote timestamp metadata
        try {
            const data = this.loadLocalMetadata(models_1.MetadataKind.Timestamp);
            this.trustedSet.updateTimestamp(data);
            // If checkRemote is disabled, return here to avoid fetching the remote
            // timestamp metadata.
            if (!checkRemote) {
                return;
            }
        }
        catch (error) {
            // continue
        }
        //Load from remote (whether local load succeeded or not)
        const timestampUrl = url.join(this.metadataBaseUrl, 'timestamp.json');
        // Client workflow 5.4.1: download timestamp metadata file
        const bytesData = await this.fetcher.downloadBytes(timestampUrl, this.config.timestampMaxLength);
        try {
            // Client workflow 5.4.2 - 5.4.4
            this.trustedSet.updateTimestamp(bytesData);
        }
        catch (error) {
            // If new timestamp version is same as current, discardd the new one.
            // This is normal and should NOT raise an error.
            if (error instanceof error_1.EqualVersionError) {
                return;
            }
            // Re-raise any other error
            throw error;
        }
        // Client workflow 5.4.5: persist timestamp metadata
        this.persistMetadata(models_1.MetadataKind.Timestamp, bytesData);
    }
    // Load local and remote snapshot metadata.
    // Client workflow 5.5: update snapshot role
    async loadSnapshot() {
        //Load local (and if needed remote) snapshot metadata
        try {
            const data = this.loadLocalMetadata(models_1.MetadataKind.Snapshot);
            this.trustedSet.updateSnapshot(data, true);
        }
        catch (error) {
            if (!this.trustedSet.timestamp) {
                throw new ReferenceError('No timestamp metadata');
            }
            const snapshotMeta = this.trustedSet.timestamp.signed.snapshotMeta;
            const maxLength = snapshotMeta.length || this.config.snapshotMaxLength;
            const version = this.trustedSet.root.signed.consistentSnapshot
                ? snapshotMeta.version
                : undefined;
            const snapshotUrl = url.join(this.metadataBaseUrl, version ? `${version}.snapshot.json` : 'snapshot.json');
            try {
                // Client workflow 5.5.1: download snapshot metadata file
                const bytesData = await this.fetcher.downloadBytes(snapshotUrl, maxLength);
                // Client workflow 5.5.2 - 5.5.6
                this.trustedSet.updateSnapshot(bytesData);
                // Client workflow 5.5.7: persist snapshot metadata file
                this.persistMetadata(models_1.MetadataKind.Snapshot, bytesData);
            }
            catch (error) {
                throw new error_1.RuntimeError(`Unable to load snapshot metadata error ${error}`);
            }
        }
    }
    // Load local and remote targets metadata.
    // Client workflow 5.6: update targets role
    async loadTargets(role, parentRole) {
        if (this.trustedSet.getRole(role)) {
            return this.trustedSet.getRole(role);
        }
        try {
            const buffer = this.loadLocalMetadata(role);
            this.trustedSet.updateDelegatedTargets(buffer, role, parentRole);
        }
        catch (error) {
            // Local 'role' does not exist or is invalid: update from remote
            if (!this.trustedSet.snapshot) {
                throw new ReferenceError('No snapshot metadata');
            }
            const metaInfo = this.trustedSet.snapshot.signed.meta[`${role}.json`];
            // TODO: use length for fetching
            const maxLength = metaInfo.length || this.config.targetsMaxLength;
            const version = this.trustedSet.root.signed.consistentSnapshot
                ? metaInfo.version
                : undefined;
            const metadataUrl = url.join(this.metadataBaseUrl, version ? `${version}.${role}.json` : `${role}.json`);
            try {
                // Client workflow 5.6.1: download targets metadata file
                const bytesData = await this.fetcher.downloadBytes(metadataUrl, maxLength);
                // Client workflow 5.6.2 - 5.6.6
                this.trustedSet.updateDelegatedTargets(bytesData, role, parentRole);
                // Client workflow 5.6.7: persist targets metadata file
                this.persistMetadata(role, bytesData);
            }
            catch (error) {
                throw new error_1.RuntimeError(`Unable to load targets error ${error}`);
            }
        }
        return this.trustedSet.getRole(role);
    }
    async preorderDepthFirstWalk(targetPath) {
        // Interrogates the tree of target delegations in order of appearance
        // (which implicitly order trustworthiness), and returns the matching
        // target found in the most trusted role.
        // List of delegations to be interrogated. A (role, parent role) pair
        // is needed to load and verify the delegated targets metadata.
        const delegationsToVisit = [
            {
                roleName: models_1.MetadataKind.Targets,
                parentRoleName: models_1.MetadataKind.Root,
            },
        ];
        const visitedRoleNames = new Set();
        // Client workflow 5.6.7: preorder depth-first traversal of the graph of
        // target delegations
        while (visitedRoleNames.size <= this.config.maxDelegations &&
            delegationsToVisit.length > 0) {
            //  Pop the role name from the top of the stack.
            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
            const { roleName, parentRoleName } = delegationsToVisit.pop();
            // Skip any visited current role to prevent cycles.
            // Client workflow 5.6.7.1: skip already-visited roles
            if (visitedRoleNames.has(roleName)) {
                continue;
            }
            // The metadata for 'role_name' must be downloaded/updated before
            // its targets, delegations, and child roles can be inspected.
            const targets = (await this.loadTargets(roleName, parentRoleName))
                ?.signed;
            if (!targets) {
                continue;
            }
            const target = targets.targets?.[targetPath];
            if (target) {
                return target;
            }
            // After preorder check, add current role to set of visited roles.
            visitedRoleNames.add(roleName);
            if (targets.delegations) {
                const childRolesToVisit = [];
                // NOTE: This may be a slow operation if there are many delegated roles.
                const rolesForTarget = targets.delegations.rolesForTarget(targetPath);
                for (const { role: childName, terminating } of rolesForTarget) {
                    childRolesToVisit.push({
                        roleName: childName,
                        parentRoleName: roleName,
                    });
                    // Client workflow 5.6.7.2.1
                    if (terminating) {
                        delegationsToVisit.splice(0); // empty the array
                        break;
                    }
                }
                childRolesToVisit.reverse();
                delegationsToVisit.push(...childRolesToVisit);
            }
        }
        return; // no matching target found
    }
    generateTargetPath(targetInfo) {
        if (!this.targetDir) {
            throw new error_1.ValueError('Target directory not set');
        }
        // URL encode target path
        const filePath = encodeURIComponent(targetInfo.path);
        return path.join(this.targetDir, filePath);
    }
    persistMetadata(metaDataName, bytesData) {
        try {
            const filePath = path.join(this.dir, `${metaDataName}.json`);
            log('WRITE %s', filePath);
            fs.writeFileSync(filePath, bytesData.toString('utf8'));
        }
        catch (error) {
            throw new error_1.PersistError(`Failed to persist metadata ${metaDataName} error: ${error}`);
        }
    }
}
exports.Updater = Updater;
PK~\Xtuf-js/dist/config.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.defaultConfig = void 0;
exports.defaultConfig = {
    maxRootRotations: 32,
    maxDelegations: 32,
    rootMaxLength: 512000, //bytes
    timestampMaxLength: 16384, // bytes
    snapshotMaxLength: 2000000, // bytes
    targetsMaxLength: 5000000, // bytes
    prefixTargetsWithHash: true,
    fetchTimeout: 100000, // milliseconds
    fetchRetries: undefined,
    fetchRetry: 2,
};
PK~\P#!tuf-js/dist/utils/url.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.join = void 0;
const url_1 = require("url");
function join(base, path) {
    return new url_1.URL(ensureTrailingSlash(base) + removeLeadingSlash(path)).toString();
}
exports.join = join;
function ensureTrailingSlash(path) {
    return path.endsWith('/') ? path : path + '/';
}
function removeLeadingSlash(path) {
    return path.startsWith('/') ? path.slice(1) : path;
}
PK~\Ouutuf-js/dist/utils/tmpfile.jsnu["use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.withTempFile = void 0;
const promises_1 = __importDefault(require("fs/promises"));
const os_1 = __importDefault(require("os"));
const path_1 = __importDefault(require("path"));
// Invokes the given handler with the path to a temporary file. The file
// is deleted after the handler returns.
const withTempFile = async (handler) => withTempDir(async (dir) => handler(path_1.default.join(dir, 'tempfile')));
exports.withTempFile = withTempFile;
// Invokes the given handler with a temporary directory. The directory is
// deleted after the handler returns.
const withTempDir = async (handler) => {
    const tmpDir = await promises_1.default.realpath(os_1.default.tmpdir());
    const dir = await promises_1.default.mkdtemp(tmpDir + path_1.default.sep);
    try {
        return await handler(dir);
    }
    finally {
        await promises_1.default.rm(dir, { force: true, recursive: true, maxRetries: 3 });
    }
};
PK~\Jv2ggtuf-js/dist/index.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Updater = exports.BaseFetcher = exports.TargetFile = void 0;
var models_1 = require("@tufjs/models");
Object.defineProperty(exports, "TargetFile", { enumerable: true, get: function () { return models_1.TargetFile; } });
var fetcher_1 = require("./fetcher");
Object.defineProperty(exports, "BaseFetcher", { enumerable: true, get: function () { return fetcher_1.BaseFetcher; } });
var updater_1 = require("./updater");
Object.defineProperty(exports, "Updater", { enumerable: true, get: function () { return updater_1.Updater; } });
PK~\en+tuf-js/dist/fetcher.jsnu["use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DefaultFetcher = exports.BaseFetcher = void 0;
const debug_1 = __importDefault(require("debug"));
const fs_1 = __importDefault(require("fs"));
const make_fetch_happen_1 = __importDefault(require("make-fetch-happen"));
const util_1 = __importDefault(require("util"));
const error_1 = require("./error");
const tmpfile_1 = require("./utils/tmpfile");
const log = (0, debug_1.default)('tuf:fetch');
class BaseFetcher {
    // Download file from given URL. The file is downloaded to a temporary
    // location and then passed to the given handler. The handler is responsible
    // for moving the file to its final location. The temporary file is deleted
    // after the handler returns.
    async downloadFile(url, maxLength, handler) {
        return (0, tmpfile_1.withTempFile)(async (tmpFile) => {
            const reader = await this.fetch(url);
            let numberOfBytesReceived = 0;
            const fileStream = fs_1.default.createWriteStream(tmpFile);
            // Read the stream a chunk at a time so that we can check
            // the length of the file as we go
            try {
                for await (const chunk of reader) {
                    const bufferChunk = Buffer.from(chunk);
                    numberOfBytesReceived += bufferChunk.length;
                    if (numberOfBytesReceived > maxLength) {
                        throw new error_1.DownloadLengthMismatchError('Max length reached');
                    }
                    await writeBufferToStream(fileStream, bufferChunk);
                }
            }
            finally {
                // Make sure we always close the stream
                await util_1.default.promisify(fileStream.close).bind(fileStream)();
            }
            return handler(tmpFile);
        });
    }
    // Download bytes from given URL.
    async downloadBytes(url, maxLength) {
        return this.downloadFile(url, maxLength, async (file) => {
            const stream = fs_1.default.createReadStream(file);
            const chunks = [];
            for await (const chunk of stream) {
                chunks.push(chunk);
            }
            return Buffer.concat(chunks);
        });
    }
}
exports.BaseFetcher = BaseFetcher;
class DefaultFetcher extends BaseFetcher {
    constructor(options = {}) {
        super();
        this.timeout = options.timeout;
        this.retry = options.retry;
    }
    async fetch(url) {
        log('GET %s', url);
        const response = await (0, make_fetch_happen_1.default)(url, {
            timeout: this.timeout,
            retry: this.retry,
        });
        if (!response.ok || !response?.body) {
            throw new error_1.DownloadHTTPError('Failed to download', response.status);
        }
        return response.body;
    }
}
exports.DefaultFetcher = DefaultFetcher;
const writeBufferToStream = async (stream, buffer) => {
    return new Promise((resolve, reject) => {
        stream.write(buffer, (err) => {
            if (err) {
                reject(err);
            }
            resolve(true);
        });
    });
};
PK~\q((tuf-js/dist/store.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TrustedMetadataStore = void 0;
const models_1 = require("@tufjs/models");
const error_1 = require("./error");
class TrustedMetadataStore {
    constructor(rootData) {
        this.trustedSet = {};
        // Client workflow 5.1: record fixed update start time
        this.referenceTime = new Date();
        // Client workflow 5.2: load trusted root metadata
        this.loadTrustedRoot(rootData);
    }
    get root() {
        if (!this.trustedSet.root) {
            throw new ReferenceError('No trusted root metadata');
        }
        return this.trustedSet.root;
    }
    get timestamp() {
        return this.trustedSet.timestamp;
    }
    get snapshot() {
        return this.trustedSet.snapshot;
    }
    get targets() {
        return this.trustedSet.targets;
    }
    getRole(name) {
        return this.trustedSet[name];
    }
    updateRoot(bytesBuffer) {
        const data = JSON.parse(bytesBuffer.toString('utf8'));
        const newRoot = models_1.Metadata.fromJSON(models_1.MetadataKind.Root, data);
        if (newRoot.signed.type != models_1.MetadataKind.Root) {
            throw new error_1.RepositoryError(`Expected 'root', got ${newRoot.signed.type}`);
        }
        // Client workflow 5.4: check for arbitrary software attack
        this.root.verifyDelegate(models_1.MetadataKind.Root, newRoot);
        // Client workflow 5.5: check for rollback attack
        if (newRoot.signed.version != this.root.signed.version + 1) {
            throw new error_1.BadVersionError(`Expected version ${this.root.signed.version + 1}, got ${newRoot.signed.version}`);
        }
        // Check that new root is signed by self
        newRoot.verifyDelegate(models_1.MetadataKind.Root, newRoot);
        // Client workflow 5.7: set new root as trusted root
        this.trustedSet.root = newRoot;
        return newRoot;
    }
    updateTimestamp(bytesBuffer) {
        if (this.snapshot) {
            throw new error_1.RuntimeError('Cannot update timestamp after snapshot');
        }
        if (this.root.signed.isExpired(this.referenceTime)) {
            throw new error_1.ExpiredMetadataError('Final root.json is expired');
        }
        const data = JSON.parse(bytesBuffer.toString('utf8'));
        const newTimestamp = models_1.Metadata.fromJSON(models_1.MetadataKind.Timestamp, data);
        if (newTimestamp.signed.type != models_1.MetadataKind.Timestamp) {
            throw new error_1.RepositoryError(`Expected 'timestamp', got ${newTimestamp.signed.type}`);
        }
        // Client workflow 5.4.2: check for arbitrary software attack
        this.root.verifyDelegate(models_1.MetadataKind.Timestamp, newTimestamp);
        if (this.timestamp) {
            // Prevent rolling back timestamp version
            // Client workflow 5.4.3.1: check for rollback attack
            if (newTimestamp.signed.version < this.timestamp.signed.version) {
                throw new error_1.BadVersionError(`New timestamp version ${newTimestamp.signed.version} is less than current version ${this.timestamp.signed.version}`);
            }
            //  Keep using old timestamp if versions are equal.
            if (newTimestamp.signed.version === this.timestamp.signed.version) {
                throw new error_1.EqualVersionError(`New timestamp version ${newTimestamp.signed.version} is equal to current version ${this.timestamp.signed.version}`);
            }
            // Prevent rolling back snapshot version
            // Client workflow 5.4.3.2: check for rollback attack
            const snapshotMeta = this.timestamp.signed.snapshotMeta;
            const newSnapshotMeta = newTimestamp.signed.snapshotMeta;
            if (newSnapshotMeta.version < snapshotMeta.version) {
                throw new error_1.BadVersionError(`New snapshot version ${newSnapshotMeta.version} is less than current version ${snapshotMeta.version}`);
            }
        }
        // expiry not checked to allow old timestamp to be used for rollback
        // protection of new timestamp: expiry is checked in update_snapshot
        this.trustedSet.timestamp = newTimestamp;
        // Client workflow 5.4.4: check for freeze attack
        this.checkFinalTimestamp();
        return newTimestamp;
    }
    updateSnapshot(bytesBuffer, trusted = false) {
        if (!this.timestamp) {
            throw new error_1.RuntimeError('Cannot update snapshot before timestamp');
        }
        if (this.targets) {
            throw new error_1.RuntimeError('Cannot update snapshot after targets');
        }
        // Snapshot cannot be loaded if final timestamp is expired
        this.checkFinalTimestamp();
        const snapshotMeta = this.timestamp.signed.snapshotMeta;
        // Verify non-trusted data against the hashes in timestamp, if any.
        // Trusted snapshot data has already been verified once.
        // Client workflow 5.5.2: check against timestamp role's snaphsot hash
        if (!trusted) {
            snapshotMeta.verify(bytesBuffer);
        }
        const data = JSON.parse(bytesBuffer.toString('utf8'));
        const newSnapshot = models_1.Metadata.fromJSON(models_1.MetadataKind.Snapshot, data);
        if (newSnapshot.signed.type != models_1.MetadataKind.Snapshot) {
            throw new error_1.RepositoryError(`Expected 'snapshot', got ${newSnapshot.signed.type}`);
        }
        // Client workflow 5.5.3: check for arbitrary software attack
        this.root.verifyDelegate(models_1.MetadataKind.Snapshot, newSnapshot);
        // version check against meta version (5.5.4) is deferred to allow old
        // snapshot to be used in rollback protection
        // Client workflow 5.5.5: check for rollback attack
        if (this.snapshot) {
            Object.entries(this.snapshot.signed.meta).forEach(([fileName, fileInfo]) => {
                const newFileInfo = newSnapshot.signed.meta[fileName];
                if (!newFileInfo) {
                    throw new error_1.RepositoryError(`Missing file ${fileName} in new snapshot`);
                }
                if (newFileInfo.version < fileInfo.version) {
                    throw new error_1.BadVersionError(`New version ${newFileInfo.version} of ${fileName} is less than current version ${fileInfo.version}`);
                }
            });
        }
        this.trustedSet.snapshot = newSnapshot;
        // snapshot is loaded, but we raise if it's not valid _final_ snapshot
        // Client workflow 5.5.4 & 5.5.6
        this.checkFinalSnapsnot();
        return newSnapshot;
    }
    updateDelegatedTargets(bytesBuffer, roleName, delegatorName) {
        if (!this.snapshot) {
            throw new error_1.RuntimeError('Cannot update delegated targets before snapshot');
        }
        // Targets cannot be loaded if final snapshot is expired or its version
        // does not match meta version in timestamp.
        this.checkFinalSnapsnot();
        const delegator = this.trustedSet[delegatorName];
        if (!delegator) {
            throw new error_1.RuntimeError(`No trusted ${delegatorName} metadata`);
        }
        // Extract metadata for the delegated role from snapshot
        const meta = this.snapshot.signed.meta?.[`${roleName}.json`];
        if (!meta) {
            throw new error_1.RepositoryError(`Missing ${roleName}.json in snapshot`);
        }
        // Client workflow 5.6.2: check against snapshot role's targets hash
        meta.verify(bytesBuffer);
        const data = JSON.parse(bytesBuffer.toString('utf8'));
        const newDelegate = models_1.Metadata.fromJSON(models_1.MetadataKind.Targets, data);
        if (newDelegate.signed.type != models_1.MetadataKind.Targets) {
            throw new error_1.RepositoryError(`Expected 'targets', got ${newDelegate.signed.type}`);
        }
        // Client workflow 5.6.3: check for arbitrary software attack
        delegator.verifyDelegate(roleName, newDelegate);
        // Client workflow 5.6.4: Check against snapshot role’s targets version
        const version = newDelegate.signed.version;
        if (version != meta.version) {
            throw new error_1.BadVersionError(`Version ${version} of ${roleName} does not match snapshot version ${meta.version}`);
        }
        // Client workflow 5.6.5: check for a freeze attack
        if (newDelegate.signed.isExpired(this.referenceTime)) {
            throw new error_1.ExpiredMetadataError(`${roleName}.json is expired`);
        }
        this.trustedSet[roleName] = newDelegate;
    }
    // Verifies and loads data as trusted root metadata.
    // Note that an expired initial root is still considered valid.
    loadTrustedRoot(bytesBuffer) {
        const data = JSON.parse(bytesBuffer.toString('utf8'));
        const root = models_1.Metadata.fromJSON(models_1.MetadataKind.Root, data);
        if (root.signed.type != models_1.MetadataKind.Root) {
            throw new error_1.RepositoryError(`Expected 'root', got ${root.signed.type}`);
        }
        root.verifyDelegate(models_1.MetadataKind.Root, root);
        this.trustedSet['root'] = root;
    }
    checkFinalTimestamp() {
        // Timestamp MUST be loaded
        if (!this.timestamp) {
            throw new ReferenceError('No trusted timestamp metadata');
        }
        // Client workflow 5.4.4: check for freeze attack
        if (this.timestamp.signed.isExpired(this.referenceTime)) {
            throw new error_1.ExpiredMetadataError('Final timestamp.json is expired');
        }
    }
    checkFinalSnapsnot() {
        // Snapshot and timestamp MUST be loaded
        if (!this.snapshot) {
            throw new ReferenceError('No trusted snapshot metadata');
        }
        if (!this.timestamp) {
            throw new ReferenceError('No trusted timestamp metadata');
        }
        // Client workflow 5.5.6: check for freeze attack
        if (this.snapshot.signed.isExpired(this.referenceTime)) {
            throw new error_1.ExpiredMetadataError('snapshot.json is expired');
        }
        // Client workflow 5.5.4: check against timestamp role’s snapshot version
        const snapshotMeta = this.timestamp.signed.snapshotMeta;
        if (this.snapshot.signed.version !== snapshotMeta.version) {
            throw new error_1.BadVersionError("Snapshot version doesn't match timestamp");
        }
    }
}
exports.TrustedMetadataStore = TrustedMetadataStore;
PK~\dЈ/tuf-js/dist/error.jsnu["use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DownloadHTTPError = exports.DownloadLengthMismatchError = exports.DownloadError = exports.ExpiredMetadataError = exports.EqualVersionError = exports.BadVersionError = exports.RepositoryError = exports.PersistError = exports.RuntimeError = exports.ValueError = void 0;
// An error about insufficient values
class ValueError extends Error {
}
exports.ValueError = ValueError;
class RuntimeError extends Error {
}
exports.RuntimeError = RuntimeError;
class PersistError extends Error {
}
exports.PersistError = PersistError;
// An error with a repository's state, such as a missing file.
// It covers all exceptions that come from the repository side when
// looking from the perspective of users of metadata API or ngclient.
class RepositoryError extends Error {
}
exports.RepositoryError = RepositoryError;
// An error for metadata that contains an invalid version number.
class BadVersionError extends RepositoryError {
}
exports.BadVersionError = BadVersionError;
// An error for metadata containing a previously verified version number.
class EqualVersionError extends BadVersionError {
}
exports.EqualVersionError = EqualVersionError;
// Indicate that a TUF Metadata file has expired.
class ExpiredMetadataError extends RepositoryError {
}
exports.ExpiredMetadataError = ExpiredMetadataError;
//----- Download Errors -------------------------------------------------------
// An error occurred while attempting to download a file.
class DownloadError extends Error {
}
exports.DownloadError = DownloadError;
// Indicate that a mismatch of lengths was seen while downloading a file
class DownloadLengthMismatchError extends DownloadError {
}
exports.DownloadLengthMismatchError = DownloadLengthMismatchError;
// Returned by FetcherInterface implementations for HTTP errors.
class DownloadHTTPError extends DownloadError {
    constructor(message, statusCode) {
        super(message);
        this.statusCode = statusCode;
    }
}
exports.DownloadHTTPError = DownloadHTTPError;
PK~\$46O''libnpmexec/package.jsonnu[{
  "_id": "libnpmexec@8.1.2",
  "_inBundle": true,
  "_location": "/npm/libnpmexec",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm"
  ],
  "author": {
    "name": "GitHub Inc."
  },
  "bugs": {
    "url": "https://github.com/npm/cli/issues"
  },
  "contributors": [
    {
      "name": "Ruy Adorno",
      "url": "https://ruyadorno.com"
    }
  ],
  "dependencies": {
    "@npmcli/arborist": "^7.5.3",
    "@npmcli/run-script": "^8.1.0",
    "ci-info": "^4.0.0",
    "npm-package-arg": "^11.0.2",
    "pacote": "^18.0.6",
    "proc-log": "^4.2.0",
    "read": "^3.0.1",
    "read-package-json-fast": "^3.0.2",
    "semver": "^7.3.7",
    "walk-up-path": "^3.0.1"
  },
  "description": "npm exec (npx) programmatic API",
  "devDependencies": {
    "@npmcli/eslint-config": "^4.0.0",
    "@npmcli/mock-registry": "^1.0.0",
    "@npmcli/template-oss": "4.22.0",
    "bin-links": "^4.0.4",
    "chalk": "^5.2.0",
    "just-extend": "^6.2.0",
    "just-safe-set": "^4.2.1",
    "tap": "^16.3.8"
  },
  "engines": {
    "node": "^16.14.0 || >=18.0.0"
  },
  "files": [
    "bin/",
    "lib/"
  ],
  "homepage": "https://github.com/npm/cli#readme",
  "keywords": [
    "npm",
    "npmcli",
    "libnpm",
    "cli",
    "workspaces",
    "libnpmexec"
  ],
  "license": "ISC",
  "main": "lib/index.js",
  "name": "libnpmexec",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/cli.git",
    "directory": "workspaces/libnpmexec"
  },
  "scripts": {
    "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"",
    "lintfix": "npm run lint -- --fix",
    "postlint": "template-oss-check",
    "posttest": "npm run lint",
    "snap": "tap",
    "template-oss-apply": "template-oss-apply --force",
    "test": "tap"
  },
  "tap": {
    "files": "test/*.js",
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.22.0",
    "content": "../../scripts/template-oss/index.js"
  },
  "version": "8.1.2"
}
PK~\..libnpmexec/lib/is-windows.jsnu[module.exports = process.platform === 'win32'
PK~\y9Nvvlibnpmexec/lib/run-script.jsnu[const ciInfo = require('ci-info')
const runScript = require('@npmcli/run-script')
const readPackageJson = require('read-package-json-fast')
const { log, output } = require('proc-log')
const noTTY = require('./no-tty.js')

const run = async ({
  args,
  call,
  flatOptions,
  locationMsg,
  path,
  binPaths,
  runPath,
  scriptShell,
}) => {
  // turn list of args into command string
  const script = call || args.shift() || scriptShell

  // do the fakey runScript dance
  // still should work if no package.json in cwd
  const realPkg = await readPackageJson(`${path}/package.json`).catch(() => ({}))
  const pkg = {
    ...realPkg,
    scripts: {
      ...(realPkg.scripts || {}),
      npx: script,
    },
  }

  if (script === scriptShell) {
    if (!noTTY()) {
      if (ciInfo.isCI) {
        return log.warn('exec', 'Interactive mode disabled in CI environment')
      }

      const { chalk } = flatOptions

      output.standard(`${
        chalk.reset('\nEntering npm script environment')
      }${
        chalk.reset(locationMsg || ` at location:\n${chalk.dim(runPath)}`)
      }${
        chalk.bold('\nType \'exit\' or ^D when finished\n')
      }`)
    }
  }
  return runScript({
    ...flatOptions,
    pkg,
    // we always run in cwd, not --prefix
    path: runPath,
    binPaths,
    event: 'npx',
    args,
    stdio: 'inherit',
    scriptShell,
  })
}

module.exports = run
PK~\X,,libnpmexec/lib/no-tty.jsnu[module.exports = () => !process.stdin.isTTY
PK~\ %%libnpmexec/lib/index.jsnu['use strict'

const { mkdir } = require('node:fs/promises')
const Arborist = require('@npmcli/arborist')
const ciInfo = require('ci-info')
const crypto = require('node:crypto')
const { log, input } = require('proc-log')
const npa = require('npm-package-arg')
const pacote = require('pacote')
const { read } = require('read')
const semver = require('semver')
const { fileExists, localFileExists } = require('./file-exists.js')
const getBinFromManifest = require('./get-bin-from-manifest.js')
const noTTY = require('./no-tty.js')
const runScript = require('./run-script.js')
const isWindows = require('./is-windows.js')
const { dirname, resolve } = require('node:path')

const binPaths = []

// when checking the local tree we look up manifests, cache those results by
// spec.raw so we don't have to fetch again when we check npxCache
const manifests = new Map()

const getManifest = async (spec, flatOptions) => {
  if (!manifests.has(spec.raw)) {
    const manifest = await pacote.manifest(spec, { ...flatOptions, preferOnline: true })
    manifests.set(spec.raw, manifest)
  }
  return manifests.get(spec.raw)
}

// Returns the required manifest if the spec is missing from the tree
// Returns the found node if it is in the tree
const missingFromTree = async ({ spec, tree, flatOptions, isNpxTree }) => {
  // If asking for a spec by name only (spec.raw === spec.name):
  //  - In local or global mode go with anything in the tree that matches
  //  - If looking in the npx cache check if a newer version is available
  const npxByNameOnly = isNpxTree && spec.name === spec.raw
  if (spec.registry && spec.type !== 'tag' && !npxByNameOnly) {
    // registry spec that is not a specific tag.
    const nodesBySpec = tree.inventory.query('packageName', spec.name)
    for (const node of nodesBySpec) {
      if (spec.rawSpec === '*') {
        return { node }
      }
      // package requested by specific version
      if (spec.type === 'version' && (node.pkgid === spec.raw)) {
        return { node }
      }
      // package requested by version range, only remaining registry type
      if (semver.satisfies(node.package.version, spec.rawSpec)) {
        return { node }
      }
    }
    const manifest = await getManifest(spec, flatOptions)
    return { manifest }
  } else {
    // non-registry spec, or a specific tag, or name only in npx tree.  Look up
    // manifest and check resolved to see if it's in the tree.
    const manifest = await getManifest(spec, flatOptions)
    if (spec.type === 'directory') {
      return { manifest }
    }
    const nodesByManifest = tree.inventory.query('packageName', manifest.name)
    for (const node of nodesByManifest) {
      if (node.package.resolved === manifest._resolved) {
        // we have a package by the same name and the same resolved destination, nothing to add.
        return { node }
      }
    }
    return { manifest }
  }
}

// see if the package.json at `path` has an entry that matches `cmd`
const hasPkgBin = (path, cmd, flatOptions) =>
  pacote.manifest(path, flatOptions)
    .then(manifest => manifest?.bin?.[cmd]).catch(() => null)

const exec = async (opts) => {
  const {
    args = [],
    call = '',
    localBin = resolve('./node_modules/.bin'),
    locationMsg = undefined,
    globalBin = '',
    globalPath,
    // dereference values because we manipulate it later
    packages: [...packages] = [],
    path = '.',
    runPath = '.',
    scriptShell = isWindows ? process.env.ComSpec || 'cmd' : 'sh',
    ...flatOptions
  } = opts

  let pkgPaths = opts.pkgPath
  if (typeof pkgPaths === 'string') {
    pkgPaths = [pkgPaths]
  }
  if (!pkgPaths) {
    pkgPaths = ['.']
  }
  let yes = opts.yes
  const run = () => runScript({
    args,
    call,
    flatOptions,
    locationMsg,
    path,
    binPaths,
    runPath,
    scriptShell,
  })

  // interactive mode
  if (!call && !args.length && !packages.length) {
    return run()
  }

  // Look in the local tree too
  pkgPaths.push(path)

  let needPackageCommandSwap = (args.length > 0) && (packages.length === 0)
  // If they asked for a command w/o specifying a package, see if there is a
  // bin that directly matches that name:
  // - in any local packages (pkgPaths can have workspaces in them or just the root)
  // - in the local tree (path)
  // - globally
  if (needPackageCommandSwap) {
    // Local packages and local tree
    for (const p of pkgPaths) {
      if (await hasPkgBin(p, args[0], flatOptions)) {
        // we have to install the local package into the npx cache so that its
        // bin links get set up
        flatOptions.installLinks = false
        // args[0] will exist when the package is installed
        packages.push(p)
        yes = true
        needPackageCommandSwap = false
        break
      }
    }
    if (needPackageCommandSwap) {
      // no bin entry in local packages or in tree, now we look for binPaths
      const dir = dirname(dirname(localBin))
      const localBinPath = await localFileExists(dir, args[0], '/')
      if (localBinPath) {
        binPaths.push(localBinPath)
        return await run()
      } else if (globalPath && await fileExists(`${globalBin}/${args[0]}`)) {
        binPaths.push(globalBin)
        return await run()
      }
      // We swap out args[0] with the bin from the manifest later
      packages.push(args[0])
    }
  }

  // Resolve any directory specs so that the npx directory is unique to the
  // resolved directory, not the potentially relative one (i.e. "npx .")
  for (const i in packages) {
    const pkg = packages[i]
    const spec = npa(pkg)
    if (spec.type === 'directory') {
      packages[i] = spec.fetchSpec
    }
  }

  const localArb = new Arborist({ ...flatOptions, path })
  const localTree = await localArb.loadActual()

  // Find anything that isn't installed locally
  const needInstall = []
  let commandManifest
  await Promise.all(packages.map(async (pkg, i) => {
    const spec = npa(pkg, path)
    const { manifest, node } = await missingFromTree({ spec, tree: localTree, flatOptions })
    if (manifest) {
      // Package does not exist in the local tree
      needInstall.push({ spec, manifest })
      if (i === 0) {
        commandManifest = manifest
      }
    } else if (i === 0) {
      // The node.package has enough to look up the bin
      commandManifest = node.package
    }
  }))

  if (needPackageCommandSwap) {
    const spec = npa(args[0])

    if (spec.type === 'directory') {
      yes = true
    }

    args[0] = getBinFromManifest(commandManifest)

    if (needInstall.length > 0 && globalPath) {
      // See if the package is installed globally, and run the translated bin
      const globalArb = new Arborist({ ...flatOptions, path: globalPath, global: true })
      const globalTree = await globalArb.loadActual()
      const { manifest: globalManifest } =
        await missingFromTree({ spec, tree: globalTree, flatOptions })
      if (!globalManifest && await fileExists(`${globalBin}/${args[0]}`)) {
        binPaths.push(globalBin)
        return await run()
      }
    }
  }

  const add = []
  if (needInstall.length > 0) {
    // Install things to the npx cache, if needed
    const { npxCache } = flatOptions
    if (!npxCache) {
      throw new Error('Must provide a valid npxCache path')
    }
    const hash = crypto.createHash('sha512')
      .update(packages.map(p => {
        // Keeps the npx directory unique to the resolved directory, not the
        // potentially relative one (i.e. "npx .")
        const spec = npa(p)
        if (spec.type === 'directory') {
          return spec.fetchSpec
        }
        return p
      }).sort((a, b) => a.localeCompare(b, 'en')).join('\n'))
      .digest('hex')
      .slice(0, 16)
    const installDir = resolve(npxCache, hash)
    await mkdir(installDir, { recursive: true })
    const npxArb = new Arborist({
      ...flatOptions,
      path: installDir,
    })
    const npxTree = await npxArb.loadActual()
    await Promise.all(needInstall.map(async ({ spec }) => {
      const { manifest } = await missingFromTree({
        spec,
        tree: npxTree,
        flatOptions,
        isNpxTree: true,
      })
      if (manifest) {
        // Manifest is not in npxCache, we need to install it there
        if (!spec.registry) {
          add.push(manifest._from)
        } else {
          add.push(manifest._id)
        }
      }
    }))

    if (add.length) {
      if (!yes) {
        const addList = add.map(a => `${a.replace(/@$/, '')}`)

        // set -n to always say no
        if (yes === false) {
          // Error message lists missing package(s) when process is canceled
          /* eslint-disable-next-line max-len */
          throw new Error(`npx canceled due to missing packages and no YES option: ${JSON.stringify(addList)}`)
        }

        if (noTTY() || ciInfo.isCI) {
          /* eslint-disable-next-line max-len */
          log.warn('exec', `The following package${add.length === 1 ? ' was' : 's were'} not found and will be installed: ${addList.join(', ')}`)
        } else {
          const confirm = await input.read(() => read({
            /* eslint-disable-next-line max-len */
            prompt: `Need to install the following packages:\n${addList.join('\n')}\nOk to proceed? `,
            default: 'y',
          }))
          if (confirm.trim().toLowerCase().charAt(0) !== 'y') {
            throw new Error('canceled')
          }
        }
      }
      await npxArb.reify({
        ...flatOptions,
        add,
      })
    }
    binPaths.push(resolve(installDir, 'node_modules/.bin'))
  }

  return await run()
}

module.exports = exec
PK~\vI'libnpmexec/lib/get-bin-from-manifest.jsnu[const getBinFromManifest = (mani) => {
  // if we have a bin matching (unscoped portion of) packagename, use that
  // otherwise if there's 1 bin or all bin value is the same (alias), use
  // that, otherwise fail
  const bin = mani.bin || {}
  if (new Set(Object.values(bin)).size === 1) {
    return Object.keys(bin)[0]
  }

  // XXX probably a util to parse this better?
  const name = mani.name.replace(/^@[^/]+\//, '')
  if (bin[name]) {
    return name
  }

  // XXX need better error message
  throw Object.assign(new Error('could not determine executable to run'), {
    pkgid: mani._id,
  })
}

module.exports = getBinFromManifest
PK~\پ1libnpmexec/lib/file-exists.jsnu[const { resolve } = require('node:path')
const { stat } = require('node:fs/promises')
const { walkUp } = require('walk-up-path')

const fileExists = async (file) => {
  try {
    const res = await stat(file)
    return res.isFile()
  } catch {
    return false
  }
}

const localFileExists = async (dir, binName, root) => {
  for (const path of walkUp(dir)) {
    const binDir = resolve(path, 'node_modules', '.bin')

    if (await fileExists(resolve(binDir, binName))) {
      return binDir
    }

    if (path.toLowerCase() === resolve(root).toLowerCase()) {
      return false
    }
  }

  return false
}

module.exports = {
  fileExists,
  localFileExists,
}
PK~\Flibnpmexec/LICENSEnu[The ISC License

Copyright (c) GitHub Inc.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
PK~\&J:	:	libnpmexec/README.mdnu[# libnpmexec

[![npm version](https://img.shields.io/npm/v/libnpmexec.svg)](https://npm.im/libnpmexec)
[![license](https://img.shields.io/npm/l/libnpmexec.svg)](https://npm.im/libnpmexec)
[![CI - libnpmexec](https://github.com/npm/cli/actions/workflows/ci-libnpmexec.yml/badge.svg)](https://github.com/npm/cli/actions/workflows/ci-libnpmexec.yml)

The `npm exec` (`npx`) Programmatic API

## Install

`npm install libnpmexec`

## Usage:

```js
const libexec = require('libnpmexec')
await libexec({
  args: ['yosay', 'Bom dia!'],
  cache: '~/.npm/_cacache',
  npxCache: '~/.npm/_npx',
  yes: true,
})
```

## API:

### `libexec(opts)`

- `opts`:
  - `args`: List of pkgs to execute **Array**, defaults to `[]`
  - `call`: An alternative command to run when using `packages` option **String**, defaults to empty string.
  - `cache`: The path location to where the npm cache folder is placed **String**
  - `npxCache`: The path location to where the npx cache folder is placed **String**
  - `chalk`: Chalk instance to use for colors? **Required**
  - `localBin`: Location to the `node_modules/.bin` folder of the local project to start scanning for bin files **String**, defaults to `./node_modules/.bin`. **libexec** will walk up the directory structure looking for `node_modules/.bin` folders in parent folders that might satisfy the current `arg` and will use that bin if found.
  - `locationMsg`: Overrides "at location" message when entering interactive mode **String**
  - `globalBin`: Location to the global space bin folder, same as: `$(npm bin -g)` **String**, defaults to empty string.
  - `packages`: A list of packages to be used (possibly fetch from the registry) **Array**, defaults to `[]`
  - `path`: Location to where to read local project info (`package.json`) **String**, defaults to `.`
  - `runPath`: Location to where to execute the script **String**, defaults to `.`
  - `scriptShell`: Default shell to be used **String**, defaults to `sh` on POSIX systems, `process.env.ComSpec` OR `cmd` on Windows
  - `yes`: Should skip download confirmation prompt when fetching missing packages from the registry? **Boolean**
  - `registry`, `cache`, and more options that are forwarded to [@npmcli/arborist](https://github.com/npm/arborist/) and [pacote](https://github.com/npm/pacote/#options) **Object**

## LICENSE

[ISC](./LICENSE)
PK~\iXhttp-proxy-agent/package.jsonnu[{
  "_id": "http-proxy-agent@7.0.2",
  "_inBundle": true,
  "_location": "/npm/http-proxy-agent",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm/@npmcli/agent"
  ],
  "author": {
    "name": "Nathan Rajlich",
    "email": "nathan@tootallnate.net",
    "url": "http://n8.io/"
  },
  "bugs": {
    "url": "https://github.com/TooTallNate/proxy-agents/issues"
  },
  "dependencies": {
    "agent-base": "^7.1.0",
    "debug": "^4.3.4"
  },
  "description": "An HTTP(s) proxy `http.Agent` implementation for HTTP",
  "devDependencies": {
    "@types/debug": "^4.1.7",
    "@types/jest": "^29.5.1",
    "@types/node": "^14.18.45",
    "async-listen": "^3.0.0",
    "jest": "^29.5.0",
    "proxy": "2.1.1",
    "ts-jest": "^29.1.0",
    "tsconfig": "0.0.0",
    "typescript": "^5.0.4"
  },
  "engines": {
    "node": ">= 14"
  },
  "files": [
    "dist"
  ],
  "homepage": "https://github.com/TooTallNate/proxy-agents#readme",
  "keywords": [
    "http",
    "proxy",
    "endpoint",
    "agent"
  ],
  "license": "MIT",
  "main": "./dist/index.js",
  "name": "http-proxy-agent",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/TooTallNate/proxy-agents.git",
    "directory": "packages/http-proxy-agent"
  },
  "scripts": {
    "build": "tsc",
    "lint": "eslint . --ext .ts",
    "pack": "node ../../scripts/pack.mjs",
    "test": "jest --env node --verbose --bail"
  },
  "types": "./dist/index.d.ts",
  "version": "7.0.2"
}
PK~\jNNhttp-proxy-agent/LICENSEnu[(The MIT License)

Copyright (c) 2013 Nathan Rajlich 

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
PK~\Fhttp-proxy-agent/dist/index.jsnu["use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpProxyAgent = void 0;
const net = __importStar(require("net"));
const tls = __importStar(require("tls"));
const debug_1 = __importDefault(require("debug"));
const events_1 = require("events");
const agent_base_1 = require("agent-base");
const url_1 = require("url");
const debug = (0, debug_1.default)('http-proxy-agent');
/**
 * The `HttpProxyAgent` implements an HTTP Agent subclass that connects
 * to the specified "HTTP proxy server" in order to proxy HTTP requests.
 */
class HttpProxyAgent extends agent_base_1.Agent {
    constructor(proxy, opts) {
        super(opts);
        this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy;
        this.proxyHeaders = opts?.headers ?? {};
        debug('Creating new HttpProxyAgent instance: %o', this.proxy.href);
        // Trim off the brackets from IPv6 addresses
        const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, '');
        const port = this.proxy.port
            ? parseInt(this.proxy.port, 10)
            : this.proxy.protocol === 'https:'
                ? 443
                : 80;
        this.connectOpts = {
            ...(opts ? omit(opts, 'headers') : null),
            host,
            port,
        };
    }
    addRequest(req, opts) {
        req._header = null;
        this.setRequestProps(req, opts);
        // @ts-expect-error `addRequest()` isn't defined in `@types/node`
        super.addRequest(req, opts);
    }
    setRequestProps(req, opts) {
        const { proxy } = this;
        const protocol = opts.secureEndpoint ? 'https:' : 'http:';
        const hostname = req.getHeader('host') || 'localhost';
        const base = `${protocol}//${hostname}`;
        const url = new url_1.URL(req.path, base);
        if (opts.port !== 80) {
            url.port = String(opts.port);
        }
        // Change the `http.ClientRequest` instance's "path" field
        // to the absolute path of the URL that will be requested.
        req.path = String(url);
        // Inject the `Proxy-Authorization` header if necessary.
        const headers = typeof this.proxyHeaders === 'function'
            ? this.proxyHeaders()
            : { ...this.proxyHeaders };
        if (proxy.username || proxy.password) {
            const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
            headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`;
        }
        if (!headers['Proxy-Connection']) {
            headers['Proxy-Connection'] = this.keepAlive
                ? 'Keep-Alive'
                : 'close';
        }
        for (const name of Object.keys(headers)) {
            const value = headers[name];
            if (value) {
                req.setHeader(name, value);
            }
        }
    }
    async connect(req, opts) {
        req._header = null;
        if (!req.path.includes('://')) {
            this.setRequestProps(req, opts);
        }
        // At this point, the http ClientRequest's internal `_header` field
        // might have already been set. If this is the case then we'll need
        // to re-generate the string since we just changed the `req.path`.
        let first;
        let endOfHeaders;
        debug('Regenerating stored HTTP header string for request');
        req._implicitHeader();
        if (req.outputData && req.outputData.length > 0) {
            debug('Patching connection write() output buffer with updated header');
            first = req.outputData[0].data;
            endOfHeaders = first.indexOf('\r\n\r\n') + 4;
            req.outputData[0].data =
                req._header + first.substring(endOfHeaders);
            debug('Output buffer: %o', req.outputData[0].data);
        }
        // Create a socket connection to the proxy server.
        let socket;
        if (this.proxy.protocol === 'https:') {
            debug('Creating `tls.Socket`: %o', this.connectOpts);
            socket = tls.connect(this.connectOpts);
        }
        else {
            debug('Creating `net.Socket`: %o', this.connectOpts);
            socket = net.connect(this.connectOpts);
        }
        // Wait for the socket's `connect` event, so that this `callback()`
        // function throws instead of the `http` request machinery. This is
        // important for i.e. `PacProxyAgent` which determines a failed proxy
        // connection via the `callback()` function throwing.
        await (0, events_1.once)(socket, 'connect');
        return socket;
    }
}
HttpProxyAgent.protocols = ['http', 'https'];
exports.HttpProxyAgent = HttpProxyAgent;
function omit(obj, ...keys) {
    const ret = {};
    let key;
    for (key in obj) {
        if (!keys.includes(key)) {
            ret[key] = obj[key];
        }
    }
    return ret;
}
//# sourceMappingURL=index.js.mapPK~\$0A}}libnpmversion/package.jsonnu[{
  "_id": "libnpmversion@6.0.3",
  "_inBundle": true,
  "_location": "/npm/libnpmversion",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm"
  ],
  "author": {
    "name": "GitHub Inc."
  },
  "bugs": {
    "url": "https://github.com/npm/cli/issues"
  },
  "dependencies": {
    "@npmcli/git": "^5.0.7",
    "@npmcli/run-script": "^8.1.0",
    "json-parse-even-better-errors": "^3.0.2",
    "proc-log": "^4.2.0",
    "semver": "^7.3.7"
  },
  "description": "library to do the things that 'npm version' does",
  "devDependencies": {
    "@npmcli/eslint-config": "^4.0.0",
    "@npmcli/template-oss": "4.22.0",
    "require-inject": "^1.4.4",
    "tap": "^16.3.8"
  },
  "engines": {
    "node": "^16.14.0 || >=18.0.0"
  },
  "files": [
    "bin/",
    "lib/"
  ],
  "homepage": "https://github.com/npm/cli#readme",
  "license": "ISC",
  "main": "lib/index.js",
  "name": "libnpmversion",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/cli.git",
    "directory": "workspaces/libnpmversion"
  },
  "scripts": {
    "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"",
    "lintfix": "npm run lint -- --fix",
    "postlint": "template-oss-check",
    "posttest": "npm run lint",
    "snap": "tap",
    "template-oss-apply": "template-oss-apply --force",
    "test": "tap"
  },
  "tap": {
    "coverage-map": "map.js",
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.22.0",
    "content": "../../scripts/template-oss/index.js"
  },
  "version": "6.0.3"
}
PK~\
m !libnpmversion/lib/retrieve-tag.jsnu[const { spawn } = require('@npmcli/git')
const semver = require('semver')

module.exports = async opts => {
  const tag = (await spawn(
    ['describe', '--tags', '--abbrev=0', '--match=*.*.*'],
    opts)).stdout.trim()
  const ver = semver.coerce(tag, { loose: true })
  if (ver) {
    return ver.version
  }
  throw new Error(`Tag is not a valid version: ${JSON.stringify(tag)}`)
}
PK~\H33

libnpmversion/lib/index.jsnu[const readJson = require('./read-json.js')
const version = require('./version.js')

module.exports = async (newversion, opts = {}) => {
  const {
    path = process.cwd(),
    allowSameVersion = false,
    tagVersionPrefix = 'v',
    commitHooks = true,
    gitTagVersion = true,
    signGitCommit = false,
    signGitTag = false,
    force = false,
    ignoreScripts = false,
    scriptShell = undefined,
    preid = null,
    message = 'v%s',
  } = opts

  const pkg = opts.pkg || await readJson(path + '/package.json')

  return version(newversion, {
    path,
    cwd: path,
    allowSameVersion,
    tagVersionPrefix,
    commitHooks,
    gitTagVersion,
    signGitCommit,
    signGitTag,
    force,
    ignoreScripts,
    scriptShell,
    preid,
    pkg,
    message,
  })
}
PK~\žlibnpmversion/lib/commit.jsnu[const git = require('@npmcli/git')

module.exports = (version, opts) => {
  const { commitHooks, allowSameVersion, signGitCommit, message } = opts
  const args = ['commit']
  if (commitHooks === false) {
    args.push('-n')
  }
  if (allowSameVersion) {
    args.push('--allow-empty')
  }
  if (signGitCommit) {
    args.push('-S')
  }
  args.push('-m')
  return git.spawn([...args, message.replace(/%s/g, version)], opts)
}
PK~\ņlibnpmversion/lib/write-json.jsnu[// write the json back, preserving the line breaks and indent
const { writeFile } = require('node:fs/promises')
const kIndent = Symbol.for('indent')
const kNewline = Symbol.for('newline')

module.exports = async (path, pkg) => {
  const {
    [kIndent]: indent = 2,
    [kNewline]: newline = '\n',
  } = pkg
  delete pkg._id
  const raw = JSON.stringify(pkg, null, indent) + '\n'
  const data = newline === '\n' ? raw : raw.split('\n').join(newline)
  return writeFile(path, data)
}
PK~\QLH''libnpmversion/lib/read-json.jsnu[// can't use read-package-json-fast, because we want to ensure
// that we make as few changes as possible, even for safety issues.
const { readFile } = require('node:fs/promises')
const parse = require('json-parse-even-better-errors')

module.exports = async path => parse(await readFile(path))
PK~\ٜ*libnpmversion/lib/tag.jsnu[const git = require('@npmcli/git')

module.exports = async (version, opts) => {
  const {
    signGitTag,
    allowSameVersion,
    tagVersionPrefix,
    message,
  } = opts

  const tag = `${tagVersionPrefix}${version}`
  const flags = ['-']

  if (signGitTag) {
    flags.push('s')
  }

  if (allowSameVersion) {
    flags.push('f')
  }

  flags.push('m')

  return git.spawn([
    'tag',
    flags.join(''),
    message.replace(/%s/g, version),
    tag,
  ], opts)
}
PK~\a`eII"libnpmversion/lib/enforce-clean.jsnu[const git = require('@npmcli/git')
const { log } = require('proc-log')

// returns true if it's cool to do git stuff
// throws if it's unclean, and not forced.
module.exports = async opts => {
  const { force } = opts
  let hadError = false
  const clean = await git.isClean(opts).catch(er => {
    if (er.code === 'ENOGIT') {
      log.warn(
        'version',
        'This is a Git checkout, but the git command was not found.',
        'npm could not create a Git tag for this release!'
      )
      hadError = true
      // how can merges be real if our git isn't real?
      return true
    } else {
      throw er
    }
  })

  if (!clean) {
    if (!force) {
      throw new Error('Git working directory not clean.')
    }
    log.warn('version', 'Git working directory not clean, proceeding forcefully.')
  }

  return !hadError
}
PK~\ <libnpmversion/lib/version.jsnu[// called with all the options already set to their defaults

const retrieveTag = require('./retrieve-tag.js')
const semver = require('semver')
const enforceClean = require('./enforce-clean.js')
const writeJson = require('./write-json.js')
const readJson = require('./read-json.js')
const git = require('@npmcli/git')
const commit = require('./commit.js')
const tag = require('./tag.js')
const { log } = require('proc-log')

const runScript = require('@npmcli/run-script')

module.exports = async (newversion, opts) => {
  const {
    path,
    allowSameVersion,
    gitTagVersion,
    ignoreScripts,
    preid,
    pkg,
  } = opts

  const { valid, clean, inc } = semver
  const current = pkg.version || '0.0.0'
  const currentClean = clean(current)

  let newV
  if (valid(newversion, { loose: true })) {
    newV = clean(newversion, { loose: true })
  } else if (newversion === 'from-git') {
    newV = await retrieveTag(opts)
  } else {
    newV = inc(currentClean, newversion, { loose: true }, preid)
  }

  if (!newV) {
    throw Object.assign(new Error('Invalid version: ' + newversion), {
      current,
      requested: newversion,
    })
  }

  if (newV === currentClean && !allowSameVersion) {
    throw Object.assign(new Error('Version not changed'), {
      current,
      requested: newversion,
      newVersion: newV,
    })
  }

  const isGitDir = newversion === 'from-git' || await git.is(opts)

  // ok!  now we know the new version, and the old version is in pkg

  // - check if git dir is clean
  // returns false if we should not keep doing git stuff
  const doGit = gitTagVersion && isGitDir && await enforceClean(opts)

  if (!ignoreScripts) {
    await runScript({
      ...opts,
      pkg,
      stdio: 'inherit',
      event: 'preversion',
      env: {
        npm_old_version: current,
        npm_new_version: newV,
      },
    })
  }

  // - update the files
  pkg.version = newV
  delete pkg._id
  await writeJson(`${path}/package.json`, pkg)

  // try to update shrinkwrap, but ok if this fails
  const locks = [`${path}/package-lock.json`, `${path}/npm-shrinkwrap.json`]
  const haveLocks = []
  for (const lock of locks) {
    try {
      const sw = await readJson(lock)
      sw.version = newV
      if (sw.packages && sw.packages['']) {
        sw.packages[''].version = newV
      }
      await writeJson(lock, sw)
      haveLocks.push(lock)
    } catch {
      // ignore errors
    }
  }

  if (!ignoreScripts) {
    await runScript({
      ...opts,
      pkg,
      stdio: 'inherit',
      event: 'version',
      env: {
        npm_old_version: current,
        npm_new_version: newV,
      },
    })
  }

  if (doGit) {
    // - git add, git commit, git tag
    await git.spawn(['add', `${path}/package.json`], opts)
    // sometimes people .gitignore their lockfiles
    for (const lock of haveLocks) {
      await git.spawn(['add', lock], opts).catch(() => {})
    }
    await commit(newV, opts)
    await tag(newV, opts)
  } else {
    log.verbose('version', 'Not tagging: not in a git repo or no git cmd')
  }

  if (!ignoreScripts) {
    await runScript({
      ...opts,
      pkg,
      stdio: 'inherit',
      event: 'postversion',
      env: {
        npm_old_version: current,
        npm_new_version: newV,
      },
    })
  }

  return newV
}
PK~\?&libnpmversion/LICENSEnu[The ISC License

Copyright (c) Isaac Z. Schlueter

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
PK~\$libnpmversion/README.mdnu[# libnpmversion

[![npm version](https://img.shields.io/npm/v/libnpmversion.svg)](https://npm.im/libnpmversion)
[![license](https://img.shields.io/npm/l/libnpmversion.svg)](https://npm.im/libnpmversion)
[![CI - libnpmversion](https://github.com/npm/cli/actions/workflows/ci-libnpmversion.yml/badge.svg)](https://github.com/npm/cli/actions/workflows/ci-libnpmversion.yml)

Library to do the things that 'npm version' does.

## USAGE

```js
const npmVersion = require('libnpmversion')

// argument can be one of:
// - any semver version string (set to that exact version)
// - 'major', 'minor', 'patch', 'pre{major,minor,patch}' (increment at
//   that value)
// - 'from-git' (set to the latest semver-lookin git tag - this skips
//   gitTagVersion, but will still sign if asked)
npmVersion(arg, {
  path: '/path/to/my/pkg', // defaults to cwd

  allowSameVersion: false, // allow tagging/etc to the current version
  preid: '', // when arg=='pre', define the prerelease string, like 'beta' etc.
  tagVersionPrefix: 'v', // tag as 'v1.2.3' when versioning to 1.2.3
  commitHooks: true, // default true, run git commit hooks, default true
  gitTagVersion: true, // default true, tag the version
  signGitCommit: false, // default false, gpg sign the git commit
  signGitTag: false, // default false, gpg sign the git tag
  force: false, // push forward recklessly if any problems happen
  ignoreScripts: false, // do not run pre/post/version lifecycle scripts
  scriptShell: '/bin/bash', // shell to run lifecycle scripts in
  message: 'v%s', // message for tag and commit, replace %s with the version
}).then(newVersion => {
  console.error('version updated!', newVersion)
})
```

## Description

Run this in a package directory to bump the version and write the new data
back to `package.json`, `package-lock.json`, and, if present,
`npm-shrinkwrap.json`.

The `newversion` argument should be a valid semver string, a valid second
argument to [semver.inc](https://github.com/npm/node-semver#functions) (one
of `patch`, `minor`, `major`, `prepatch`, `preminor`, `premajor`,
`prerelease`), or `from-git`. In the second case, the existing version will
be incremented by 1 in the specified field.  `from-git` will try to read
the latest git tag, and use that as the new npm version.

If run in a git repo, it will also create a version commit and tag.  This
behavior is controlled by `gitTagVersion` (see below), and can be
disabled by setting `gitTagVersion: false` in the options.
It will fail if the working directory is not clean, unless `force: true` is
set.

If supplied with a `message` string option, it will
use it as a commit message when creating a version commit.  If the
`message` option contains `%s` then that will be replaced with the
resulting version number.

If the `signGitTag` option is set, then the tag will be signed using
the `-s` flag to git.  Note that you must have a default GPG key set up in
your git config for this to work properly.

If `preversion`, `version`, or `postversion` are in the `scripts` property
of the package.json, they will be executed in the appropriate sequence.

The exact order of execution is as follows:

1. Check to make sure the git working directory is clean before we get
   started.  Your scripts may add files to the commit in future steps.
   This step is skipped if the `force` flag is set.
2. Run the `preversion` script.  These scripts have access to the old
   `version` in package.json.  A typical use would be running your full
   test suite before deploying.  Any files you want added to the commit
   should be explicitly added using `git add`.
3. Bump `version` in `package.json` as requested (`patch`, `minor`,
   `major`, explicit version number, etc).
4. Run the `version` script. These scripts have access to the new `version`
   in package.json (so they can incorporate it into file headers in
   generated files for example).  Again, scripts should explicitly add
   generated files to the commit using `git add`.
5. Commit and tag.
6. Run the `postversion` script. Use it to clean up the file system or
   automatically push the commit and/or tag.

Take the following example:

```json
{
  "scripts": {
    "preversion": "npm test",
    "version": "npm run build && git add -A dist",
    "postversion": "git push && git push --tags && rm -rf build/temp"
  }
}
```

This runs all your tests, and proceeds only if they pass. Then runs your
`build` script, and adds everything in the `dist` directory to the commit.
After the commit, it pushes the new commit and tag up to the server, and
deletes the `build/temp` directory.

## API

### `npmVersion(newversion, options = {}) -> Promise`

Do the things.  Returns a promise that resolves to the new version if
all is well, or rejects if any errors are encountered.

### Options

#### `path` String

The path to the package being versionified.  Defaults to process.cwd().

#### `allowSameVersion` Boolean

Allow setting the version to the current version in package.json.  Default
`false`.

#### `preid` String
When the `newversion` is pre, premajor, preminor, or prepatch, this
defines the prerelease string, like 'beta' etc.

#### `tagVersionPrefix` String

The prefix to add to the raw semver string for the tag name.  Defaults to
`'v'`.  (So, by default it tags as 'v1.2.3' when versioning to 1.2.3.)

#### `commitHooks` Boolean

Run git commit hooks.  Default true.

#### `gitTagVersion` Boolean

Tag the version, default true.

#### `signGitCommit` Boolean

GPG sign the git commit.  Default `false`.

#### `signGitTag` Boolean

GPG sign the git tag.  Default `false`.

#### `force` Boolean

Push forward recklessly if any problems happen.  Default `false`.

#### `ignoreScripts` Boolean

Do not run pre/post/version lifecycle scripts.  Default `false`.

#### `scriptShell` String

Path to the shell, which should execute the lifecycle scripts.  Defaults to `/bin/sh` on unix, or `cmd.exe` on windows.

#### `message` String

The message for the git commit and annotated git tag that are created.
PK~\
R	R	$postcss-selector-parser/package.jsonnu[{
  "_id": "postcss-selector-parser@6.1.0",
  "_inBundle": true,
  "_location": "/npm/postcss-selector-parser",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm/@npmcli/query"
  ],
  "ava": {
    "require": [
      "@babel/register"
    ],
    "concurrency": 5,
    "timeout": "25s",
    "nodeArguments": []
  },
  "bugs": {
    "url": "https://github.com/postcss/postcss-selector-parser/issues"
  },
  "contributors": [
    {
      "name": "Ben Briggs",
      "email": "beneb.info@gmail.com",
      "url": "http://beneb.info"
    },
    {
      "name": "Chris Eppstein",
      "email": "chris@eppsteins.net",
      "url": "http://twitter.com/chriseppstein"
    }
  ],
  "dependencies": {
    "cssesc": "^3.0.0",
    "util-deprecate": "^1.0.2"
  },
  "devDependencies": {
    "@babel/cli": "^7.11.6",
    "@babel/core": "^7.11.6",
    "@babel/eslint-parser": "^7.11.5",
    "@babel/eslint-plugin": "^7.11.5",
    "@babel/plugin-proposal-class-properties": "^7.10.4",
    "@babel/preset-env": "^7.11.5",
    "@babel/register": "^7.11.5",
    "ava": "^5.1.0",
    "babel-plugin-add-module-exports": "^1.0.4",
    "coveralls": "^3.1.0",
    "del-cli": "^5.0.0",
    "eslint": "^8.28.0",
    "eslint-plugin-import": "^2.26.0",
    "glob": "^8.0.3",
    "minimist": "^1.2.5",
    "nyc": "^15.1.0",
    "postcss": "^8.4.31",
    "semver": "^7.3.2",
    "typescript": "^4.0.3"
  },
  "engines": {
    "node": ">=4"
  },
  "files": [
    "API.md",
    "CHANGELOG.md",
    "LICENSE-MIT",
    "dist",
    "postcss-selector-parser.d.ts",
    "!**/__tests__"
  ],
  "homepage": "https://github.com/postcss/postcss-selector-parser",
  "license": "MIT",
  "main": "dist/index.js",
  "name": "postcss-selector-parser",
  "nyc": {
    "exclude": [
      "node_modules",
      "**/__tests__"
    ]
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/postcss/postcss-selector-parser.git"
  },
  "scripts": {
    "lintfix": "eslint --fix src",
    "prepare": "del-cli dist && BABEL_ENV=publish babel src --out-dir dist --ignore /__tests__/",
    "pretest": "eslint src && npm run typecheck",
    "report": "nyc report --reporter=html",
    "test": "nyc ava src/__tests__/*.mjs",
    "testone": "ava",
    "typecheck": "tsc --noEmit --strict postcss-selector-parser.d.ts postcss-selector-parser.test.ts"
  },
  "types": "postcss-selector-parser.d.ts",
  "version": "6.1.0"
}
PK~\
R
Rpostcss-selector-parser/API.mdnu[# API Documentation

*Please use only this documented API when working with the parser. Methods
not documented here are subject to change at any point.*

## `parser` function

This is the module's main entry point.

```js
const parser = require('postcss-selector-parser');
```

### `parser([transform], [options])`

Creates a new `processor` instance

```js
const processor = parser();
```

Or, with optional transform function

```js
const transform = selectors => {
    selectors.walkUniversals(selector => {
        selector.remove();
    });
};

const processor = parser(transform)

// Example
const result = processor.processSync('*.class');
// => .class
```

[See processor documentation](#processor)

Arguments:

* `transform (function)`: Provide a function to work with the parsed AST.
* `options (object)`: Provide default options for all calls on the returned `Processor`.

### `parser.attribute([props])`

Creates a new attribute selector.

```js
parser.attribute({attribute: 'href'});
// => [href]
```

Arguments:

* `props (object)`: The new node's properties.

### `parser.className([props])`

Creates a new class selector.

```js
parser.className({value: 'button'});
// => .button
```

Arguments:

* `props (object)`: The new node's properties.

### `parser.combinator([props])`

Creates a new selector combinator.

```js
parser.combinator({value: '+'});
// => +
```

Arguments:

* `props (object)`: The new node's properties.

Notes:
* **Descendant Combinators** The value of descendant combinators created by the
  parser always just a single space (`" "`). For descendant selectors with no
  comments, additional space is now stored in `node.spaces.before`. Depending
  on the location of comments, additional spaces may be stored in
  `node.raws.spaces.before`, `node.raws.spaces.after`, or `node.raws.value`.
* **Named Combinators** Although, nonstandard and unlikely to ever become a standard,
  named combinators like `/deep/` and `/for/` are parsed as combinators. The
  `node.value` is name after being unescaped and normalized as lowercase. The
  original value for the combinator name is stored in `node.raws.value`.


### `parser.comment([props])`

Creates a new comment.

```js
parser.comment({value: '/* Affirmative, Dave. I read you. */'});
// => /* Affirmative, Dave. I read you. */
```

Arguments:

* `props (object)`: The new node's properties.

### `parser.id([props])`

Creates a new id selector.

```js
parser.id({value: 'search'});
// => #search
```

Arguments:

* `props (object)`: The new node's properties.

### `parser.nesting([props])`

Creates a new nesting selector.

```js
parser.nesting();
// => &
```

Arguments:

* `props (object)`: The new node's properties.

### `parser.pseudo([props])`

Creates a new pseudo selector.

```js
parser.pseudo({value: '::before'});
// => ::before
```

Arguments:

* `props (object)`: The new node's properties.

### `parser.root([props])`

Creates a new root node.

```js
parser.root();
// => (empty)
```

Arguments:

* `props (object)`: The new node's properties.

### `parser.selector([props])`

Creates a new selector node.

```js
parser.selector();
// => (empty)
```

Arguments:

* `props (object)`: The new node's properties.

### `parser.string([props])`

Creates a new string node.

```js
parser.string();
// => (empty)
```

Arguments:

* `props (object)`: The new node's properties.

### `parser.tag([props])`

Creates a new tag selector.

```js
parser.tag({value: 'button'});
// => button
```

Arguments:

* `props (object)`: The new node's properties.

### `parser.universal([props])`

Creates a new universal selector.

```js
parser.universal();
// => *
```

Arguments:

* `props (object)`: The new node's properties.

## Node types

### `node.type`

A string representation of the selector type. It can be one of the following;
`attribute`, `class`, `combinator`, `comment`, `id`, `nesting`, `pseudo`,
`root`, `selector`, `string`, `tag`, or `universal`. Note that for convenience,
these constants are exposed on the main `parser` as uppercased keys. So for
example you can get `id` by querying `parser.ID`.

```js
parser.attribute({attribute: 'href'}).type;
// => 'attribute'
```

### `node.parent`

Returns the parent node.

```js
root.nodes[0].parent === root;
```

### `node.toString()`, `String(node)`, or `'' + node`

Returns a string representation of the node.

```js
const id = parser.id({value: 'search'});
console.log(String(id));
// => #search
```

### `node.next()` & `node.prev()`

Returns the next/previous child of the parent node.

```js
const next = id.next();
if (next && next.type !== 'combinator') {
    throw new Error('Qualified IDs are not allowed!');
}
```

### `node.replaceWith(node)`

Replace a node with another.

```js
const attr = selectors.first.first;
const className = parser.className({value: 'test'});
attr.replaceWith(className);
```

Arguments:

* `node`: The node to substitute the original with.

### `node.remove()`

Removes the node from its parent node.

```js
if (node.type === 'id') {
    node.remove();
}
```

### `node.clone([opts])`

Returns a copy of a node, detached from any parent containers that the
original might have had.

```js
const cloned = node.clone();
```

### `node.isAtPosition(line, column)`

Return a `boolean` indicating whether this node includes the character at the
position of the given line and column. Returns `undefined` if the nodes lack
sufficient source metadata to determine the position.

Arguments:

* `line`: 1-index based line number relative to the start of the selector.
* `column`: 1-index based column number relative to the start of the selector.

### `node.spaces`

Extra whitespaces around the node will be moved into `node.spaces.before` and
`node.spaces.after`. So for example, these spaces will be moved as they have
no semantic meaning:

```css
      h1     ,     h2   {}
```

For descendent selectors, the value is always a single space.

```css
h1        h2 {}
```

Additional whitespace is found in either the `node.spaces.before` and `node.spaces.after` depending on the presence of comments or other whitespace characters. If the actual whitespace does not start or end with a single space, the node's raw value is set to the actual space(s) found in the source.

### `node.source`

An object describing the node's start/end, line/column source position.

Within the following CSS, the `.bar` class node ...

```css
.foo,
  .bar {}
```

... will contain the following `source` object.

```js
source: {
    start: {
        line: 2,
        column: 3
    },
    end: {
        line: 2,
        column: 6
    }
}
```

### `node.sourceIndex`

The zero-based index of the node within the original source string.

Within the following CSS, the `.baz` class node will have a `sourceIndex` of `12`.

```css
.foo, .bar, .baz {}
```

## Container types

The `root`, `selector`, and `pseudo` nodes have some helper methods for working
with their children.

### `container.nodes`

An array of the container's children.

```js
// Input: h1 h2
selectors.at(0).nodes.length   // => 3
selectors.at(0).nodes[0].value // => 'h1'
selectors.at(0).nodes[1].value // => ' '
```

### `container.first` & `container.last`

The first/last child of the container.

```js
selector.first === selector.nodes[0];
selector.last === selector.nodes[selector.nodes.length - 1];
```

### `container.at(index)`

Returns the node at position `index`.

```js
selector.at(0) === selector.first;
selector.at(0) === selector.nodes[0];
```

Arguments:

* `index`: The index of the node to return.

### `container.atPosition(line, column)`

Returns the node at the source position `line` and `column`.

```js
// Input: :not(.foo),\n#foo > :matches(ol, ul)
selector.atPosition(1, 1); // => :not(.foo)
selector.atPosition(2, 1); // => \n#foo
```

Arguments:

* `line`: The line number of the node to return.
* `column`: The column number of the node to return.

### `container.index(node)`

Return the index of the node within its container.

```js
selector.index(selector.nodes[2]) // => 2
```

Arguments:

* `node`: A node within the current container.

### `container.length`

Proxy to the length of the container's nodes.

```js
container.length === container.nodes.length
```

### `container` Array iterators

The container class provides proxies to certain Array methods; these are:

* `container.map === container.nodes.map`
* `container.reduce === container.nodes.reduce`
* `container.every === container.nodes.every`
* `container.some === container.nodes.some`
* `container.filter === container.nodes.filter`
* `container.sort === container.nodes.sort`

Note that these methods only work on a container's immediate children; recursive
iteration is provided by `container.walk`.

### `container.each(callback)`

Iterate the container's immediate children, calling `callback` for each child.
You may return `false` within the callback to break the iteration.

```js
let className;
selectors.each((selector, index) => {
    if (selector.type === 'class') {
        className = selector.value;
        return false;
    }
});
```

Note that unlike `Array#forEach()`, this iterator is safe to use whilst adding
or removing nodes from the container.

Arguments:

* `callback (function)`: A function to call for each node, which receives `node`
  and `index` arguments.

### `container.walk(callback)`

Like `container#each`, but will also iterate child nodes as long as they are
`container` types.

```js
selectors.walk((selector, index) => {
    // all nodes
});
```

Arguments:

* `callback (function)`: A function to call for each node, which receives `node`
  and `index` arguments.

This iterator is safe to use whilst mutating `container.nodes`,
like `container#each`.

### `container.walk` proxies

The container class provides proxy methods for iterating over types of nodes,
so that it is easier to write modules that target specific selectors. Those
methods are:

* `container.walkAttributes`
* `container.walkClasses`
* `container.walkCombinators`
* `container.walkComments`
* `container.walkIds`
* `container.walkNesting`
* `container.walkPseudos`
* `container.walkTags`
* `container.walkUniversals`

### `container.split(callback)`

This method allows you to split a group of nodes by returning `true` from
a callback. It returns an array of arrays, where each inner array corresponds
to the groups that you created via the callback.

```js
// (input) => h1 h2>>h3
const list = selectors.first.split(selector => {
    return selector.type === 'combinator';
});

// (node values) => [['h1', ' '], ['h2', '>>'], ['h3']]
```

Arguments:

* `callback (function)`: A function to call for each node, which receives `node`
  as an argument.

### `container.prepend(node)` & `container.append(node)`

Add a node to the start/end of the container. Note that doing so will set
the parent property of the node to this container.

```js
const id = parser.id({value: 'search'});
selector.append(id);
```

Arguments:

* `node`: The node to add.

### `container.insertBefore(old, new)` & `container.insertAfter(old, new)`

Add a node before or after an existing node in a container:

```js
selectors.walk(selector => {
    if (selector.type !== 'class') {
        const className = parser.className({value: 'theme-name'});
        selector.parent.insertAfter(selector, className);
    }
});
```

Arguments:

* `old`: The existing node in the container.
* `new`: The new node to add before/after the existing node.

### `container.removeChild(node)`

Remove the node from the container. Note that you can also use
`node.remove()` if you would like to remove just a single node.

```js
selector.length // => 2
selector.remove(id)
selector.length // => 1;
id.parent       // undefined
```

Arguments:

* `node`: The node to remove.

### `container.removeAll()` or `container.empty()`

Remove all children from the container.

```js
selector.removeAll();
selector.length // => 0
```

## Root nodes

A root node represents a comma separated list of selectors. Indeed, all
a root's `toString()` method does is join its selector children with a ','.
Other than this, it has no special functionality and acts like a container.

### `root.trailingComma`

This will be set to `true` if the input has a trailing comma, in order to
support parsing of legacy CSS hacks.

## Selector nodes

A selector node represents a single complex selector. For example, this
selector string `h1 h2 h3, [href] > p`, is represented as two selector nodes.
It has no special functionality of its own.

## Pseudo nodes

A pseudo selector extends a container node; if it has any parameters of its
own (such as `h1:not(h2, h3)`), they will be its children. Note that the pseudo
`value` will always contain the colons preceding the pseudo identifier. This
is so that both `:before` and `::before` are properly represented in the AST.

## Attribute nodes

### `attribute.quoted`

Returns `true` if the attribute's value is wrapped in quotation marks, false if it is not.
Remains `undefined` if there is no attribute value.

```css
[href=foo] /* false */
[href='foo'] /* true */
[href="foo"] /* true */
[href] /* undefined */
```

### `attribute.qualifiedAttribute`

Returns the attribute name qualified with the namespace if one is given.

### `attribute.offsetOf(part)`

 Returns the offset of the attribute part specified relative to the
 start of the node of the output string. This is useful in raising
 error messages about a specific part of the attribute, especially
 in combination with `attribute.sourceIndex`.

 Returns `-1` if the name is invalid or the value doesn't exist in this
 attribute.

 The legal values for `part` are:

 * `"ns"` - alias for "namespace"
 * `"namespace"` - the namespace if it exists.
 * `"attribute"` - the attribute name
 * `"attributeNS"` - the start of the attribute or its namespace
 * `"operator"` - the match operator of the attribute
 * `"value"` - The value (string or identifier)
 * `"insensitive"` - the case insensitivity flag

### `attribute.raws.unquoted`

Returns the unquoted content of the attribute's value.
Remains `undefined` if there is no attribute value.

```css
[href=foo] /* foo */
[href='foo'] /* foo */
[href="foo"] /* foo */
[href] /* undefined */
```

### `attribute.spaces`

Like `node.spaces` with the `before` and `after` values containing the spaces
around the element, the parts of the attribute can also have spaces before
and after them. The for each of `attribute`, `operator`, `value` and
`insensitive` there is corresponding property of the same nam in
`node.spaces` that has an optional `before` or `after` string containing only
whitespace.

Note that corresponding values in `attributes.raws.spaces` contain values
including any comments. If set, these values will override the
`attribute.spaces` value. Take care to remove them if changing
`attribute.spaces`.

### `attribute.raws`

The raws object stores comments and other information necessary to re-render
the node exactly as it was in the source.

If a comment is embedded within the identifiers for the `namespace`, `attribute`
or `value` then a property is placed in the raws for that value containing the full source of the propery including comments.

If a comment is embedded within the space between parts of the attribute
then the raw for that space is set accordingly.

Setting an attribute's property `raws` value to be deleted.

For now, changing the spaces required also updating or removing any of the
raws values that override them.

Example: `[ /*before*/ href /* after-attr */ = /* after-operator */ te/*inside-value*/st/* wow */ /*omg*/i/*bbq*/ /*whodoesthis*/]` would parse as:

```js
{
  attribute: "href",
  operator: "=",
  value: "test",
  spaces: {
    before: '',
    after: '',
    attribute: { before: '  ', after: '  ' },
    operator: { after: '  ' },
    value: { after: ' ' },
    insensitive: { after: ' ' }
  },
  raws: {
    spaces: {
      attribute: { before: ' /*before*/ ', after: ' /* after-attr */ ' },
      operator: { after: ' /* after-operator */ ' },
      value: { after: '/* wow */ /*omg*/' },
      insensitive: { after: '/*bbq*/ /*whodoesthis*/' }
    },
    unquoted: 'test',
    value: 'te/*inside-value*/st'
  }
}
```

## `Processor`

### `ProcessorOptions`

* `lossless` - When `true`, whitespace is preserved. Defaults to `true`.
* `updateSelector` - When `true`, if any processor methods are passed a postcss
  `Rule` node instead of a string, then that Rule's selector is updated
  with the results of the processing. Defaults to `true`.

### `process|processSync(selectors, [options])`

Processes the `selectors`, returning a string from the result of processing.

Note: when the `updateSelector` option is set, the rule's selector
will be updated with the resulting string.

**Example:**

```js
const parser = require("postcss-selector-parser");
const processor = parser();

let result = processor.processSync(' .class');
console.log(result);
// =>  .class

// Asynchronous operation
let promise = processor.process(' .class').then(result => {
    console.log(result)
    // => .class
});

// To have the parser normalize whitespace values, utilize the options
result = processor.processSync('  .class  ', {lossless: false});
console.log(result);
// => .class

// For better syntax errors, pass a PostCSS Rule node.
const postcss = require('postcss');
rule = postcss.rule({selector: ' #foo    > a,  .class  '});
processor.process(rule, {lossless: false, updateSelector: true}).then(result => {
    console.log(result);
    // => #foo>a,.class
    console.log("rule:", rule.selector);
    // => rule: #foo>a,.class
})
```

Arguments:

* `selectors (string|postcss.Rule)`: Either a selector string or a PostCSS Rule
  node.
* `[options] (object)`: Process options


### `ast|astSync(selectors, [options])`

Like `process()` and `processSync()` but after
processing the `selectors` these methods return the `Root` node of the result
instead of a string.

Note: when the `updateSelector` option is set, the rule's selector
will be updated with the resulting string.

### `transform|transformSync(selectors, [options])`

Like `process()` and `processSync()` but after
processing the `selectors` these methods return the value returned by the
processor callback.

Note: when the `updateSelector` option is set, the rule's selector
will be updated with the resulting string.

### Error Handling Within Selector Processors

The root node passed to the selector processor callback
has a method `error(message, options)` that returns an
error object. This method should always be used to raise
errors relating to the syntax of selectors. The options
to this method are passed to postcss's error constructor
([documentation](http://api.postcss.org/Container.html#error)).

#### Async Error Example

```js
let processor = (root) => {
    return new Promise((resolve, reject) => {
        root.walkClasses((classNode) => {
            if (/^(.*)[-_]/.test(classNode.value)) {
                let msg = "classes may not have underscores or dashes in them";
                reject(root.error(msg, {
                    index: classNode.sourceIndex + RegExp.$1.length + 1,
                    word: classNode.value
                }));
            }
        });
        resolve();
    });
};

const postcss = require("postcss");
const parser = require("postcss-selector-parser");
const selectorProcessor = parser(processor);
const plugin = postcss.plugin('classValidator', (options) => {
    return (root) => {
        let promises = [];
        root.walkRules(rule => {
            promises.push(selectorProcessor.process(rule));
        });
        return Promise.all(promises);
    };
});
postcss(plugin()).process(`
.foo-bar {
  color: red;
}
`.trim(), {from: 'test.css'}).catch((e) => console.error(e.toString()));

// CssSyntaxError: classValidator: ./test.css:1:5: classes may not have underscores or dashes in them
//
// > 1 | .foo-bar {
//     |     ^
//   2 |   color: red;
//   3 | }
```

#### Synchronous Error Example

```js
let processor = (root) => {
    root.walkClasses((classNode) => {
        if (/.*[-_]/.test(classNode.value)) {
            let msg = "classes may not have underscores or dashes in them";
            throw root.error(msg, {
                index: classNode.sourceIndex,
                word: classNode.value
            });
        }
    });
};

const postcss = require("postcss");
const parser = require("postcss-selector-parser");
const selectorProcessor = parser(processor);
const plugin = postcss.plugin('classValidator', (options) => {
    return (root) => {
        root.walkRules(rule => {
            selectorProcessor.processSync(rule);
        });
    };
});
postcss(plugin()).process(`
.foo-bar {
  color: red;
}
`.trim(), {from: 'test.css'}).catch((e) => console.error(e.toString()));

// CssSyntaxError: classValidator: ./test.css:1:5: classes may not have underscores or dashes in them
//
// > 1 | .foo-bar {
//     |     ^
//   2 |   color: red;
//   3 | }
```
PK~\ㅌ-postcss-selector-parser/dist/sortAscending.jsnu["use strict";

exports.__esModule = true;
exports["default"] = sortAscending;
function sortAscending(list) {
  return list.sort(function (a, b) {
    return a - b;
  });
}
;
module.exports = exports.default;PK~\u!!(postcss-selector-parser/dist/tokenize.jsnu["use strict";

exports.__esModule = true;
exports.FIELDS = void 0;
exports["default"] = tokenize;
var t = _interopRequireWildcard(require("./tokenTypes"));
var _unescapable, _wordDelimiters;
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
var wordDelimiters = (_wordDelimiters = {}, _wordDelimiters[t.space] = true, _wordDelimiters[t.tab] = true, _wordDelimiters[t.newline] = true, _wordDelimiters[t.cr] = true, _wordDelimiters[t.feed] = true, _wordDelimiters[t.ampersand] = true, _wordDelimiters[t.asterisk] = true, _wordDelimiters[t.bang] = true, _wordDelimiters[t.comma] = true, _wordDelimiters[t.colon] = true, _wordDelimiters[t.semicolon] = true, _wordDelimiters[t.openParenthesis] = true, _wordDelimiters[t.closeParenthesis] = true, _wordDelimiters[t.openSquare] = true, _wordDelimiters[t.closeSquare] = true, _wordDelimiters[t.singleQuote] = true, _wordDelimiters[t.doubleQuote] = true, _wordDelimiters[t.plus] = true, _wordDelimiters[t.pipe] = true, _wordDelimiters[t.tilde] = true, _wordDelimiters[t.greaterThan] = true, _wordDelimiters[t.equals] = true, _wordDelimiters[t.dollar] = true, _wordDelimiters[t.caret] = true, _wordDelimiters[t.slash] = true, _wordDelimiters);
var hex = {};
var hexChars = "0123456789abcdefABCDEF";
for (var i = 0; i < hexChars.length; i++) {
  hex[hexChars.charCodeAt(i)] = true;
}

/**
 *  Returns the last index of the bar css word
 * @param {string} css The string in which the word begins
 * @param {number} start The index into the string where word's first letter occurs
 */
function consumeWord(css, start) {
  var next = start;
  var code;
  do {
    code = css.charCodeAt(next);
    if (wordDelimiters[code]) {
      return next - 1;
    } else if (code === t.backslash) {
      next = consumeEscape(css, next) + 1;
    } else {
      // All other characters are part of the word
      next++;
    }
  } while (next < css.length);
  return next - 1;
}

/**
 *  Returns the last index of the escape sequence
 * @param {string} css The string in which the sequence begins
 * @param {number} start The index into the string where escape character (`\`) occurs.
 */
function consumeEscape(css, start) {
  var next = start;
  var code = css.charCodeAt(next + 1);
  if (unescapable[code]) {
    // just consume the escape char
  } else if (hex[code]) {
    var hexDigits = 0;
    // consume up to 6 hex chars
    do {
      next++;
      hexDigits++;
      code = css.charCodeAt(next + 1);
    } while (hex[code] && hexDigits < 6);
    // if fewer than 6 hex chars, a trailing space ends the escape
    if (hexDigits < 6 && code === t.space) {
      next++;
    }
  } else {
    // the next char is part of the current word
    next++;
  }
  return next;
}
var FIELDS = {
  TYPE: 0,
  START_LINE: 1,
  START_COL: 2,
  END_LINE: 3,
  END_COL: 4,
  START_POS: 5,
  END_POS: 6
};
exports.FIELDS = FIELDS;
function tokenize(input) {
  var tokens = [];
  var css = input.css.valueOf();
  var _css = css,
    length = _css.length;
  var offset = -1;
  var line = 1;
  var start = 0;
  var end = 0;
  var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  function unclosed(what, fix) {
    if (input.safe) {
      // fyi: this is never set to true.
      css += fix;
      next = css.length - 1;
    } else {
      throw input.error('Unclosed ' + what, line, start - offset, start);
    }
  }
  while (start < length) {
    code = css.charCodeAt(start);
    if (code === t.newline) {
      offset = start;
      line += 1;
    }
    switch (code) {
      case t.space:
      case t.tab:
      case t.newline:
      case t.cr:
      case t.feed:
        next = start;
        do {
          next += 1;
          code = css.charCodeAt(next);
          if (code === t.newline) {
            offset = next;
            line += 1;
          }
        } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
        tokenType = t.space;
        endLine = line;
        endColumn = next - offset - 1;
        end = next;
        break;
      case t.plus:
      case t.greaterThan:
      case t.tilde:
      case t.pipe:
        next = start;
        do {
          next += 1;
          code = css.charCodeAt(next);
        } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
        tokenType = t.combinator;
        endLine = line;
        endColumn = start - offset;
        end = next;
        break;

      // Consume these characters as single tokens.
      case t.asterisk:
      case t.ampersand:
      case t.bang:
      case t.comma:
      case t.equals:
      case t.dollar:
      case t.caret:
      case t.openSquare:
      case t.closeSquare:
      case t.colon:
      case t.semicolon:
      case t.openParenthesis:
      case t.closeParenthesis:
        next = start;
        tokenType = code;
        endLine = line;
        endColumn = start - offset;
        end = next + 1;
        break;
      case t.singleQuote:
      case t.doubleQuote:
        quote = code === t.singleQuote ? "'" : '"';
        next = start;
        do {
          escaped = false;
          next = css.indexOf(quote, next + 1);
          if (next === -1) {
            unclosed('quote', quote);
          }
          escapePos = next;
          while (css.charCodeAt(escapePos - 1) === t.backslash) {
            escapePos -= 1;
            escaped = !escaped;
          }
        } while (escaped);
        tokenType = t.str;
        endLine = line;
        endColumn = start - offset;
        end = next + 1;
        break;
      default:
        if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
          next = css.indexOf('*/', start + 2) + 1;
          if (next === 0) {
            unclosed('comment', '*/');
          }
          content = css.slice(start, next + 1);
          lines = content.split('\n');
          last = lines.length - 1;
          if (last > 0) {
            nextLine = line + last;
            nextOffset = next - lines[last].length;
          } else {
            nextLine = line;
            nextOffset = offset;
          }
          tokenType = t.comment;
          line = nextLine;
          endLine = nextLine;
          endColumn = next - nextOffset;
        } else if (code === t.slash) {
          next = start;
          tokenType = code;
          endLine = line;
          endColumn = start - offset;
          end = next + 1;
        } else {
          next = consumeWord(css, start);
          tokenType = t.word;
          endLine = line;
          endColumn = next - offset;
        }
        end = next + 1;
        break;
    }

    // Ensure that the token structure remains consistent
    tokens.push([tokenType,
    // [0] Token type
    line,
    // [1] Starting line
    start - offset,
    // [2] Starting column
    endLine,
    // [3] Ending line
    endColumn,
    // [4] Ending column
    start,
    // [5] Start position / Source index
    end // [6] End position
    ]);

    // Reset offset for the next token
    if (nextOffset) {
      offset = nextOffset;
      nextOffset = null;
    }
    start = end;
  }
  return tokens;
}PK~\Kpc

*postcss-selector-parser/dist/tokenTypes.jsnu["use strict";

exports.__esModule = true;
exports.word = exports.tilde = exports.tab = exports.str = exports.space = exports.slash = exports.singleQuote = exports.semicolon = exports.plus = exports.pipe = exports.openSquare = exports.openParenthesis = exports.newline = exports.greaterThan = exports.feed = exports.equals = exports.doubleQuote = exports.dollar = exports.cr = exports.comment = exports.comma = exports.combinator = exports.colon = exports.closeSquare = exports.closeParenthesis = exports.caret = exports.bang = exports.backslash = exports.at = exports.asterisk = exports.ampersand = void 0;
var ampersand = 38; // `&`.charCodeAt(0);
exports.ampersand = ampersand;
var asterisk = 42; // `*`.charCodeAt(0);
exports.asterisk = asterisk;
var at = 64; // `@`.charCodeAt(0);
exports.at = at;
var comma = 44; // `,`.charCodeAt(0);
exports.comma = comma;
var colon = 58; // `:`.charCodeAt(0);
exports.colon = colon;
var semicolon = 59; // `;`.charCodeAt(0);
exports.semicolon = semicolon;
var openParenthesis = 40; // `(`.charCodeAt(0);
exports.openParenthesis = openParenthesis;
var closeParenthesis = 41; // `)`.charCodeAt(0);
exports.closeParenthesis = closeParenthesis;
var openSquare = 91; // `[`.charCodeAt(0);
exports.openSquare = openSquare;
var closeSquare = 93; // `]`.charCodeAt(0);
exports.closeSquare = closeSquare;
var dollar = 36; // `$`.charCodeAt(0);
exports.dollar = dollar;
var tilde = 126; // `~`.charCodeAt(0);
exports.tilde = tilde;
var caret = 94; // `^`.charCodeAt(0);
exports.caret = caret;
var plus = 43; // `+`.charCodeAt(0);
exports.plus = plus;
var equals = 61; // `=`.charCodeAt(0);
exports.equals = equals;
var pipe = 124; // `|`.charCodeAt(0);
exports.pipe = pipe;
var greaterThan = 62; // `>`.charCodeAt(0);
exports.greaterThan = greaterThan;
var space = 32; // ` `.charCodeAt(0);
exports.space = space;
var singleQuote = 39; // `'`.charCodeAt(0);
exports.singleQuote = singleQuote;
var doubleQuote = 34; // `"`.charCodeAt(0);
exports.doubleQuote = doubleQuote;
var slash = 47; // `/`.charCodeAt(0);
exports.slash = slash;
var bang = 33; // `!`.charCodeAt(0);
exports.bang = bang;
var backslash = 92; // '\\'.charCodeAt(0);
exports.backslash = backslash;
var cr = 13; // '\r'.charCodeAt(0);
exports.cr = cr;
var feed = 12; // '\f'.charCodeAt(0);
exports.feed = feed;
var newline = 10; // '\n'.charCodeAt(0);
exports.newline = newline;
var tab = 9; // '\t'.charCodeAt(0);

// Expose aliases primarily for readability.
exports.tab = tab;
var str = singleQuote;

// No good single character representation!
exports.str = str;
var comment = -1;
exports.comment = comment;
var word = -2;
exports.word = word;
var combinator = -3;
exports.combinator = combinator;PK~\
|VV&postcss-selector-parser/dist/parser.jsnu["use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _root = _interopRequireDefault(require("./selectors/root"));
var _selector = _interopRequireDefault(require("./selectors/selector"));
var _className = _interopRequireDefault(require("./selectors/className"));
var _comment = _interopRequireDefault(require("./selectors/comment"));
var _id = _interopRequireDefault(require("./selectors/id"));
var _tag = _interopRequireDefault(require("./selectors/tag"));
var _string = _interopRequireDefault(require("./selectors/string"));
var _pseudo = _interopRequireDefault(require("./selectors/pseudo"));
var _attribute = _interopRequireWildcard(require("./selectors/attribute"));
var _universal = _interopRequireDefault(require("./selectors/universal"));
var _combinator = _interopRequireDefault(require("./selectors/combinator"));
var _nesting = _interopRequireDefault(require("./selectors/nesting"));
var _sortAscending = _interopRequireDefault(require("./sortAscending"));
var _tokenize = _interopRequireWildcard(require("./tokenize"));
var tokens = _interopRequireWildcard(require("./tokenTypes"));
var types = _interopRequireWildcard(require("./selectors/types"));
var _util = require("./util");
var _WHITESPACE_TOKENS, _Object$assign;
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
var WHITESPACE_TOKENS = (_WHITESPACE_TOKENS = {}, _WHITESPACE_TOKENS[tokens.space] = true, _WHITESPACE_TOKENS[tokens.cr] = true, _WHITESPACE_TOKENS[tokens.feed] = true, _WHITESPACE_TOKENS[tokens.newline] = true, _WHITESPACE_TOKENS[tokens.tab] = true, _WHITESPACE_TOKENS);
var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
function tokenStart(token) {
  return {
    line: token[_tokenize.FIELDS.START_LINE],
    column: token[_tokenize.FIELDS.START_COL]
  };
}
function tokenEnd(token) {
  return {
    line: token[_tokenize.FIELDS.END_LINE],
    column: token[_tokenize.FIELDS.END_COL]
  };
}
function getSource(startLine, startColumn, endLine, endColumn) {
  return {
    start: {
      line: startLine,
      column: startColumn
    },
    end: {
      line: endLine,
      column: endColumn
    }
  };
}
function getTokenSource(token) {
  return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
}
function getTokenSourceSpan(startToken, endToken) {
  if (!startToken) {
    return undefined;
  }
  return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
}
function unescapeProp(node, prop) {
  var value = node[prop];
  if (typeof value !== "string") {
    return;
  }
  if (value.indexOf("\\") !== -1) {
    (0, _util.ensureObject)(node, 'raws');
    node[prop] = (0, _util.unesc)(value);
    if (node.raws[prop] === undefined) {
      node.raws[prop] = value;
    }
  }
  return node;
}
function indexesOf(array, item) {
  var i = -1;
  var indexes = [];
  while ((i = array.indexOf(item, i + 1)) !== -1) {
    indexes.push(i);
  }
  return indexes;
}
function uniqs() {
  var list = Array.prototype.concat.apply([], arguments);
  return list.filter(function (item, i) {
    return i === list.indexOf(item);
  });
}
var Parser = /*#__PURE__*/function () {
  function Parser(rule, options) {
    if (options === void 0) {
      options = {};
    }
    this.rule = rule;
    this.options = Object.assign({
      lossy: false,
      safe: false
    }, options);
    this.position = 0;
    this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
    this.tokens = (0, _tokenize["default"])({
      css: this.css,
      error: this._errorGenerator(),
      safe: this.options.safe
    });
    var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
    this.root = new _root["default"]({
      source: rootSource
    });
    this.root.errorGenerator = this._errorGenerator();
    var selector = new _selector["default"]({
      source: {
        start: {
          line: 1,
          column: 1
        }
      },
      sourceIndex: 0
    });
    this.root.append(selector);
    this.current = selector;
    this.loop();
  }
  var _proto = Parser.prototype;
  _proto._errorGenerator = function _errorGenerator() {
    var _this = this;
    return function (message, errorOptions) {
      if (typeof _this.rule === 'string') {
        return new Error(message);
      }
      return _this.rule.error(message, errorOptions);
    };
  };
  _proto.attribute = function attribute() {
    var attr = [];
    var startingToken = this.currToken;
    this.position++;
    while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
      attr.push(this.currToken);
      this.position++;
    }
    if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
      return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
    }
    var len = attr.length;
    var node = {
      source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
      sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
    };
    if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
      return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
    }
    var pos = 0;
    var spaceBefore = '';
    var commentBefore = '';
    var lastAdded = null;
    var spaceAfterMeaningfulToken = false;
    while (pos < len) {
      var token = attr[pos];
      var content = this.content(token);
      var next = attr[pos + 1];
      switch (token[_tokenize.FIELDS.TYPE]) {
        case tokens.space:
          // if (
          //     len === 1 ||
          //     pos === 0 && this.content(next) === '|'
          // ) {
          //     return this.expected('attribute', token[TOKEN.START_POS], content);
          // }
          spaceAfterMeaningfulToken = true;
          if (this.options.lossy) {
            break;
          }
          if (lastAdded) {
            (0, _util.ensureObject)(node, 'spaces', lastAdded);
            var prevContent = node.spaces[lastAdded].after || '';
            node.spaces[lastAdded].after = prevContent + content;
            var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
            if (existingComment) {
              node.raws.spaces[lastAdded].after = existingComment + content;
            }
          } else {
            spaceBefore = spaceBefore + content;
            commentBefore = commentBefore + content;
          }
          break;
        case tokens.asterisk:
          if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
            node.operator = content;
            lastAdded = 'operator';
          } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
            if (spaceBefore) {
              (0, _util.ensureObject)(node, 'spaces', 'attribute');
              node.spaces.attribute.before = spaceBefore;
              spaceBefore = '';
            }
            if (commentBefore) {
              (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
              node.raws.spaces.attribute.before = spaceBefore;
              commentBefore = '';
            }
            node.namespace = (node.namespace || "") + content;
            var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null;
            if (rawValue) {
              node.raws.namespace += content;
            }
            lastAdded = 'namespace';
          }
          spaceAfterMeaningfulToken = false;
          break;
        case tokens.dollar:
          if (lastAdded === "value") {
            var oldRawValue = (0, _util.getProp)(node, 'raws', 'value');
            node.value += "$";
            if (oldRawValue) {
              node.raws.value = oldRawValue + "$";
            }
            break;
          }
        // Falls through
        case tokens.caret:
          if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
            node.operator = content;
            lastAdded = 'operator';
          }
          spaceAfterMeaningfulToken = false;
          break;
        case tokens.combinator:
          if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
            node.operator = content;
            lastAdded = 'operator';
          }
          if (content !== '|') {
            spaceAfterMeaningfulToken = false;
            break;
          }
          if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
            node.operator = content;
            lastAdded = 'operator';
          } else if (!node.namespace && !node.attribute) {
            node.namespace = true;
          }
          spaceAfterMeaningfulToken = false;
          break;
        case tokens.word:
          if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals &&
          // this look-ahead probably fails with comment nodes involved.
          !node.operator && !node.namespace) {
            node.namespace = content;
            lastAdded = 'namespace';
          } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
            if (spaceBefore) {
              (0, _util.ensureObject)(node, 'spaces', 'attribute');
              node.spaces.attribute.before = spaceBefore;
              spaceBefore = '';
            }
            if (commentBefore) {
              (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
              node.raws.spaces.attribute.before = commentBefore;
              commentBefore = '';
            }
            node.attribute = (node.attribute || "") + content;
            var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null;
            if (_rawValue) {
              node.raws.attribute += content;
            }
            lastAdded = 'attribute';
          } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) {
            var _unescaped = (0, _util.unesc)(content);
            var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || '';
            var oldValue = node.value || '';
            node.value = oldValue + _unescaped;
            node.quoteMark = null;
            if (_unescaped !== content || _oldRawValue) {
              (0, _util.ensureObject)(node, 'raws');
              node.raws.value = (_oldRawValue || oldValue) + content;
            }
            lastAdded = 'value';
          } else {
            var insensitive = content === 'i' || content === "I";
            if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
              node.insensitive = insensitive;
              if (!insensitive || content === "I") {
                (0, _util.ensureObject)(node, 'raws');
                node.raws.insensitiveFlag = content;
              }
              lastAdded = 'insensitive';
              if (spaceBefore) {
                (0, _util.ensureObject)(node, 'spaces', 'insensitive');
                node.spaces.insensitive.before = spaceBefore;
                spaceBefore = '';
              }
              if (commentBefore) {
                (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive');
                node.raws.spaces.insensitive.before = commentBefore;
                commentBefore = '';
              }
            } else if (node.value || node.value === '') {
              lastAdded = 'value';
              node.value += content;
              if (node.raws.value) {
                node.raws.value += content;
              }
            }
          }
          spaceAfterMeaningfulToken = false;
          break;
        case tokens.str:
          if (!node.attribute || !node.operator) {
            return this.error("Expected an attribute followed by an operator preceding the string.", {
              index: token[_tokenize.FIELDS.START_POS]
            });
          }
          var _unescapeValue = (0, _attribute.unescapeValue)(content),
            unescaped = _unescapeValue.unescaped,
            quoteMark = _unescapeValue.quoteMark;
          node.value = unescaped;
          node.quoteMark = quoteMark;
          lastAdded = 'value';
          (0, _util.ensureObject)(node, 'raws');
          node.raws.value = content;
          spaceAfterMeaningfulToken = false;
          break;
        case tokens.equals:
          if (!node.attribute) {
            return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
          }
          if (node.value) {
            return this.error('Unexpected "=" found; an operator was already defined.', {
              index: token[_tokenize.FIELDS.START_POS]
            });
          }
          node.operator = node.operator ? node.operator + content : content;
          lastAdded = 'operator';
          spaceAfterMeaningfulToken = false;
          break;
        case tokens.comment:
          if (lastAdded) {
            if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
              var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || '';
              var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
              (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded);
              node.raws.spaces[lastAdded].after = rawLastComment + content;
            } else {
              var lastValue = node[lastAdded] || '';
              var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue;
              (0, _util.ensureObject)(node, 'raws');
              node.raws[lastAdded] = rawLastValue + content;
            }
          } else {
            commentBefore = commentBefore + content;
          }
          break;
        default:
          return this.error("Unexpected \"" + content + "\" found.", {
            index: token[_tokenize.FIELDS.START_POS]
          });
      }
      pos++;
    }
    unescapeProp(node, "attribute");
    unescapeProp(node, "namespace");
    this.newNode(new _attribute["default"](node));
    this.position++;
  }

  /**
   * return a node containing meaningless garbage up to (but not including) the specified token position.
   * if the token position is negative, all remaining tokens are consumed.
   *
   * This returns an array containing a single string node if all whitespace,
   * otherwise an array of comment nodes with space before and after.
   *
   * These tokens are not added to the current selector, the caller can add them or use them to amend
   * a previous node's space metadata.
   *
   * In lossy mode, this returns only comments.
   */;
  _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
    if (stopPosition < 0) {
      stopPosition = this.tokens.length;
    }
    var startPosition = this.position;
    var nodes = [];
    var space = "";
    var lastComment = undefined;
    do {
      if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
        if (!this.options.lossy) {
          space += this.content();
        }
      } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
        var spaces = {};
        if (space) {
          spaces.before = space;
          space = "";
        }
        lastComment = new _comment["default"]({
          value: this.content(),
          source: getTokenSource(this.currToken),
          sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
          spaces: spaces
        });
        nodes.push(lastComment);
      }
    } while (++this.position < stopPosition);
    if (space) {
      if (lastComment) {
        lastComment.spaces.after = space;
      } else if (!this.options.lossy) {
        var firstToken = this.tokens[startPosition];
        var lastToken = this.tokens[this.position - 1];
        nodes.push(new _string["default"]({
          value: '',
          source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
          sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
          spaces: {
            before: space,
            after: ''
          }
        }));
      }
    }
    return nodes;
  }

  /**
   *
   * @param {*} nodes
   */;
  _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
    var _this2 = this;
    if (requiredSpace === void 0) {
      requiredSpace = false;
    }
    var space = "";
    var rawSpace = "";
    nodes.forEach(function (n) {
      var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
      var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
      space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
      rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
    });
    if (rawSpace === space) {
      rawSpace = undefined;
    }
    var result = {
      space: space,
      rawSpace: rawSpace
    };
    return result;
  };
  _proto.isNamedCombinator = function isNamedCombinator(position) {
    if (position === void 0) {
      position = this.position;
    }
    return this.tokens[position + 0] && this.tokens[position + 0][_tokenize.FIELDS.TYPE] === tokens.slash && this.tokens[position + 1] && this.tokens[position + 1][_tokenize.FIELDS.TYPE] === tokens.word && this.tokens[position + 2] && this.tokens[position + 2][_tokenize.FIELDS.TYPE] === tokens.slash;
  };
  _proto.namedCombinator = function namedCombinator() {
    if (this.isNamedCombinator()) {
      var nameRaw = this.content(this.tokens[this.position + 1]);
      var name = (0, _util.unesc)(nameRaw).toLowerCase();
      var raws = {};
      if (name !== nameRaw) {
        raws.value = "/" + nameRaw + "/";
      }
      var node = new _combinator["default"]({
        value: "/" + name + "/",
        source: getSource(this.currToken[_tokenize.FIELDS.START_LINE], this.currToken[_tokenize.FIELDS.START_COL], this.tokens[this.position + 2][_tokenize.FIELDS.END_LINE], this.tokens[this.position + 2][_tokenize.FIELDS.END_COL]),
        sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
        raws: raws
      });
      this.position = this.position + 3;
      return node;
    } else {
      this.unexpected();
    }
  };
  _proto.combinator = function combinator() {
    var _this3 = this;
    if (this.content() === '|') {
      return this.namespace();
    }
    // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
    var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
    if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma) {
      var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
      if (nodes.length > 0) {
        var last = this.current.last;
        if (last) {
          var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
            space = _this$convertWhitespa.space,
            rawSpace = _this$convertWhitespa.rawSpace;
          if (rawSpace !== undefined) {
            last.rawSpaceAfter += rawSpace;
          }
          last.spaces.after += space;
        } else {
          nodes.forEach(function (n) {
            return _this3.newNode(n);
          });
        }
      }
      return;
    }
    var firstToken = this.currToken;
    var spaceOrDescendantSelectorNodes = undefined;
    if (nextSigTokenPos > this.position) {
      spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
    }
    var node;
    if (this.isNamedCombinator()) {
      node = this.namedCombinator();
    } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
      node = new _combinator["default"]({
        value: this.content(),
        source: getTokenSource(this.currToken),
        sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
      });
      this.position++;
    } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
      // pass
    } else if (!spaceOrDescendantSelectorNodes) {
      this.unexpected();
    }
    if (node) {
      if (spaceOrDescendantSelectorNodes) {
        var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
          _space = _this$convertWhitespa2.space,
          _rawSpace = _this$convertWhitespa2.rawSpace;
        node.spaces.before = _space;
        node.rawSpaceBefore = _rawSpace;
      }
    } else {
      // descendant combinator
      var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
        _space2 = _this$convertWhitespa3.space,
        _rawSpace2 = _this$convertWhitespa3.rawSpace;
      if (!_rawSpace2) {
        _rawSpace2 = _space2;
      }
      var spaces = {};
      var raws = {
        spaces: {}
      };
      if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
        spaces.before = _space2.slice(0, _space2.length - 1);
        raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
      } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) {
        spaces.after = _space2.slice(1);
        raws.spaces.after = _rawSpace2.slice(1);
      } else {
        raws.value = _rawSpace2;
      }
      node = new _combinator["default"]({
        value: ' ',
        source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
        sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
        spaces: spaces,
        raws: raws
      });
    }
    if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
      node.spaces.after = this.optionalSpace(this.content());
      this.position++;
    }
    return this.newNode(node);
  };
  _proto.comma = function comma() {
    if (this.position === this.tokens.length - 1) {
      this.root.trailingComma = true;
      this.position++;
      return;
    }
    this.current._inferEndPosition();
    var selector = new _selector["default"]({
      source: {
        start: tokenStart(this.tokens[this.position + 1])
      },
      sourceIndex: this.tokens[this.position + 1][_tokenize.FIELDS.START_POS]
    });
    this.current.parent.append(selector);
    this.current = selector;
    this.position++;
  };
  _proto.comment = function comment() {
    var current = this.currToken;
    this.newNode(new _comment["default"]({
      value: this.content(),
      source: getTokenSource(current),
      sourceIndex: current[_tokenize.FIELDS.START_POS]
    }));
    this.position++;
  };
  _proto.error = function error(message, opts) {
    throw this.root.error(message, opts);
  };
  _proto.missingBackslash = function missingBackslash() {
    return this.error('Expected a backslash preceding the semicolon.', {
      index: this.currToken[_tokenize.FIELDS.START_POS]
    });
  };
  _proto.missingParenthesis = function missingParenthesis() {
    return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  };
  _proto.missingSquareBracket = function missingSquareBracket() {
    return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  };
  _proto.unexpected = function unexpected() {
    return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  };
  _proto.unexpectedPipe = function unexpectedPipe() {
    return this.error("Unexpected '|'.", this.currToken[_tokenize.FIELDS.START_POS]);
  };
  _proto.namespace = function namespace() {
    var before = this.prevToken && this.content(this.prevToken) || true;
    if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
      this.position++;
      return this.word(before);
    } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
      this.position++;
      return this.universal(before);
    }
    this.unexpectedPipe();
  };
  _proto.nesting = function nesting() {
    if (this.nextToken) {
      var nextContent = this.content(this.nextToken);
      if (nextContent === "|") {
        this.position++;
        return;
      }
    }
    var current = this.currToken;
    this.newNode(new _nesting["default"]({
      value: this.content(),
      source: getTokenSource(current),
      sourceIndex: current[_tokenize.FIELDS.START_POS]
    }));
    this.position++;
  };
  _proto.parentheses = function parentheses() {
    var last = this.current.last;
    var unbalanced = 1;
    this.position++;
    if (last && last.type === types.PSEUDO) {
      var selector = new _selector["default"]({
        source: {
          start: tokenStart(this.tokens[this.position])
        },
        sourceIndex: this.tokens[this.position][_tokenize.FIELDS.START_POS]
      });
      var cache = this.current;
      last.append(selector);
      this.current = selector;
      while (this.position < this.tokens.length && unbalanced) {
        if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
          unbalanced++;
        }
        if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
          unbalanced--;
        }
        if (unbalanced) {
          this.parse();
        } else {
          this.current.source.end = tokenEnd(this.currToken);
          this.current.parent.source.end = tokenEnd(this.currToken);
          this.position++;
        }
      }
      this.current = cache;
    } else {
      // I think this case should be an error. It's used to implement a basic parse of media queries
      // but I don't think it's a good idea.
      var parenStart = this.currToken;
      var parenValue = "(";
      var parenEnd;
      while (this.position < this.tokens.length && unbalanced) {
        if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
          unbalanced++;
        }
        if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
          unbalanced--;
        }
        parenEnd = this.currToken;
        parenValue += this.parseParenthesisToken(this.currToken);
        this.position++;
      }
      if (last) {
        last.appendToPropertyAndEscape("value", parenValue, parenValue);
      } else {
        this.newNode(new _string["default"]({
          value: parenValue,
          source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
          sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
        }));
      }
    }
    if (unbalanced) {
      return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
    }
  };
  _proto.pseudo = function pseudo() {
    var _this4 = this;
    var pseudoStr = '';
    var startingToken = this.currToken;
    while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
      pseudoStr += this.content();
      this.position++;
    }
    if (!this.currToken) {
      return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
    }
    if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
      this.splitWord(false, function (first, length) {
        pseudoStr += first;
        _this4.newNode(new _pseudo["default"]({
          value: pseudoStr,
          source: getTokenSourceSpan(startingToken, _this4.currToken),
          sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
        }));
        if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
          _this4.error('Misplaced parenthesis.', {
            index: _this4.nextToken[_tokenize.FIELDS.START_POS]
          });
        }
      });
    } else {
      return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
    }
  };
  _proto.space = function space() {
    var content = this.content();
    // Handle space before and after the selector
    if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
      return node.type === 'comment';
    })) {
      this.spaces = this.optionalSpace(content);
      this.position++;
    } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
      this.current.last.spaces.after = this.optionalSpace(content);
      this.position++;
    } else {
      this.combinator();
    }
  };
  _proto.string = function string() {
    var current = this.currToken;
    this.newNode(new _string["default"]({
      value: this.content(),
      source: getTokenSource(current),
      sourceIndex: current[_tokenize.FIELDS.START_POS]
    }));
    this.position++;
  };
  _proto.universal = function universal(namespace) {
    var nextToken = this.nextToken;
    if (nextToken && this.content(nextToken) === '|') {
      this.position++;
      return this.namespace();
    }
    var current = this.currToken;
    this.newNode(new _universal["default"]({
      value: this.content(),
      source: getTokenSource(current),
      sourceIndex: current[_tokenize.FIELDS.START_POS]
    }), namespace);
    this.position++;
  };
  _proto.splitWord = function splitWord(namespace, firstCallback) {
    var _this5 = this;
    var nextToken = this.nextToken;
    var word = this.content();
    while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
      this.position++;
      var current = this.content();
      word += current;
      if (current.lastIndexOf('\\') === current.length - 1) {
        var next = this.nextToken;
        if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
          word += this.requiredSpace(this.content(next));
          this.position++;
        }
      }
      nextToken = this.nextToken;
    }
    var hasClass = indexesOf(word, '.').filter(function (i) {
      // Allow escaped dot within class name
      var escapedDot = word[i - 1] === '\\';
      // Allow decimal numbers percent in @keyframes
      var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
      return !escapedDot && !isKeyframesPercent;
    });
    var hasId = indexesOf(word, '#').filter(function (i) {
      return word[i - 1] !== '\\';
    });
    // Eliminate Sass interpolations from the list of id indexes
    var interpolations = indexesOf(word, '#{');
    if (interpolations.length) {
      hasId = hasId.filter(function (hashIndex) {
        return !~interpolations.indexOf(hashIndex);
      });
    }
    var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
    indices.forEach(function (ind, i) {
      var index = indices[i + 1] || word.length;
      var value = word.slice(ind, index);
      if (i === 0 && firstCallback) {
        return firstCallback.call(_this5, value, indices.length);
      }
      var node;
      var current = _this5.currToken;
      var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
      var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
      if (~hasClass.indexOf(ind)) {
        var classNameOpts = {
          value: value.slice(1),
          source: source,
          sourceIndex: sourceIndex
        };
        node = new _className["default"](unescapeProp(classNameOpts, "value"));
      } else if (~hasId.indexOf(ind)) {
        var idOpts = {
          value: value.slice(1),
          source: source,
          sourceIndex: sourceIndex
        };
        node = new _id["default"](unescapeProp(idOpts, "value"));
      } else {
        var tagOpts = {
          value: value,
          source: source,
          sourceIndex: sourceIndex
        };
        unescapeProp(tagOpts, "value");
        node = new _tag["default"](tagOpts);
      }
      _this5.newNode(node, namespace);
      // Ensure that the namespace is used only once
      namespace = null;
    });
    this.position++;
  };
  _proto.word = function word(namespace) {
    var nextToken = this.nextToken;
    if (nextToken && this.content(nextToken) === '|') {
      this.position++;
      return this.namespace();
    }
    return this.splitWord(namespace);
  };
  _proto.loop = function loop() {
    while (this.position < this.tokens.length) {
      this.parse(true);
    }
    this.current._inferEndPosition();
    return this.root;
  };
  _proto.parse = function parse(throwOnParenthesis) {
    switch (this.currToken[_tokenize.FIELDS.TYPE]) {
      case tokens.space:
        this.space();
        break;
      case tokens.comment:
        this.comment();
        break;
      case tokens.openParenthesis:
        this.parentheses();
        break;
      case tokens.closeParenthesis:
        if (throwOnParenthesis) {
          this.missingParenthesis();
        }
        break;
      case tokens.openSquare:
        this.attribute();
        break;
      case tokens.dollar:
      case tokens.caret:
      case tokens.equals:
      case tokens.word:
        this.word();
        break;
      case tokens.colon:
        this.pseudo();
        break;
      case tokens.comma:
        this.comma();
        break;
      case tokens.asterisk:
        this.universal();
        break;
      case tokens.ampersand:
        this.nesting();
        break;
      case tokens.slash:
      case tokens.combinator:
        this.combinator();
        break;
      case tokens.str:
        this.string();
        break;
      // These cases throw; no break needed.
      case tokens.closeSquare:
        this.missingSquareBracket();
      case tokens.semicolon:
        this.missingBackslash();
      default:
        this.unexpected();
    }
  }

  /**
   * Helpers
   */;
  _proto.expected = function expected(description, index, found) {
    if (Array.isArray(description)) {
      var last = description.pop();
      description = description.join(', ') + " or " + last;
    }
    var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
    if (!found) {
      return this.error("Expected " + an + " " + description + ".", {
        index: index
      });
    }
    return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
      index: index
    });
  };
  _proto.requiredSpace = function requiredSpace(space) {
    return this.options.lossy ? ' ' : space;
  };
  _proto.optionalSpace = function optionalSpace(space) {
    return this.options.lossy ? '' : space;
  };
  _proto.lossySpace = function lossySpace(space, required) {
    if (this.options.lossy) {
      return required ? ' ' : '';
    } else {
      return space;
    }
  };
  _proto.parseParenthesisToken = function parseParenthesisToken(token) {
    var content = this.content(token);
    if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
      return this.requiredSpace(content);
    } else {
      return content;
    }
  };
  _proto.newNode = function newNode(node, namespace) {
    if (namespace) {
      if (/^ +$/.test(namespace)) {
        if (!this.options.lossy) {
          this.spaces = (this.spaces || '') + namespace;
        }
        namespace = true;
      }
      node.namespace = namespace;
      unescapeProp(node, "namespace");
    }
    if (this.spaces) {
      node.spaces.before = this.spaces;
      this.spaces = '';
    }
    return this.current.append(node);
  };
  _proto.content = function content(token) {
    if (token === void 0) {
      token = this.currToken;
    }
    return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  };
  /**
   * returns the index of the next non-whitespace, non-comment token.
   * returns -1 if no meaningful token is found.
   */
  _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
    if (startPosition === void 0) {
      startPosition = this.position + 1;
    }
    var searchPosition = startPosition;
    while (searchPosition < this.tokens.length) {
      if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
        searchPosition++;
        continue;
      } else {
        return searchPosition;
      }
    }
    return -1;
  };
  _createClass(Parser, [{
    key: "currToken",
    get: function get() {
      return this.tokens[this.position];
    }
  }, {
    key: "nextToken",
    get: function get() {
      return this.tokens[this.position + 1];
    }
  }, {
    key: "prevToken",
    get: function get() {
      return this.tokens[this.position - 1];
    }
  }]);
  return Parser;
}();
exports["default"] = Parser;
module.exports = exports.default;PK~\]ZZ)postcss-selector-parser/dist/processor.jsnu["use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _parser = _interopRequireDefault(require("./parser"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var Processor = /*#__PURE__*/function () {
  function Processor(func, options) {
    this.func = func || function noop() {};
    this.funcRes = null;
    this.options = options;
  }
  var _proto = Processor.prototype;
  _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
    if (options === void 0) {
      options = {};
    }
    var merged = Object.assign({}, this.options, options);
    if (merged.updateSelector === false) {
      return false;
    } else {
      return typeof rule !== "string";
    }
  };
  _proto._isLossy = function _isLossy(options) {
    if (options === void 0) {
      options = {};
    }
    var merged = Object.assign({}, this.options, options);
    if (merged.lossless === false) {
      return true;
    } else {
      return false;
    }
  };
  _proto._root = function _root(rule, options) {
    if (options === void 0) {
      options = {};
    }
    var parser = new _parser["default"](rule, this._parseOptions(options));
    return parser.root;
  };
  _proto._parseOptions = function _parseOptions(options) {
    return {
      lossy: this._isLossy(options)
    };
  };
  _proto._run = function _run(rule, options) {
    var _this = this;
    if (options === void 0) {
      options = {};
    }
    return new Promise(function (resolve, reject) {
      try {
        var root = _this._root(rule, options);
        Promise.resolve(_this.func(root)).then(function (transform) {
          var string = undefined;
          if (_this._shouldUpdateSelector(rule, options)) {
            string = root.toString();
            rule.selector = string;
          }
          return {
            transform: transform,
            root: root,
            string: string
          };
        }).then(resolve, reject);
      } catch (e) {
        reject(e);
        return;
      }
    });
  };
  _proto._runSync = function _runSync(rule, options) {
    if (options === void 0) {
      options = {};
    }
    var root = this._root(rule, options);
    var transform = this.func(root);
    if (transform && typeof transform.then === "function") {
      throw new Error("Selector processor returned a promise to a synchronous call.");
    }
    var string = undefined;
    if (options.updateSelector && typeof rule !== "string") {
      string = root.toString();
      rule.selector = string;
    }
    return {
      transform: transform,
      root: root,
      string: string
    };
  }

  /**
   * Process rule into a selector AST.
   *
   * @param rule {postcss.Rule | string} The css selector to be processed
   * @param options The options for processing
   * @returns {Promise} The AST of the selector after processing it.
   */;
  _proto.ast = function ast(rule, options) {
    return this._run(rule, options).then(function (result) {
      return result.root;
    });
  }

  /**
   * Process rule into a selector AST synchronously.
   *
   * @param rule {postcss.Rule | string} The css selector to be processed
   * @param options The options for processing
   * @returns {parser.Root} The AST of the selector after processing it.
   */;
  _proto.astSync = function astSync(rule, options) {
    return this._runSync(rule, options).root;
  }

  /**
   * Process a selector into a transformed value asynchronously
   *
   * @param rule {postcss.Rule | string} The css selector to be processed
   * @param options The options for processing
   * @returns {Promise} The value returned by the processor.
   */;
  _proto.transform = function transform(rule, options) {
    return this._run(rule, options).then(function (result) {
      return result.transform;
    });
  }

  /**
   * Process a selector into a transformed value synchronously.
   *
   * @param rule {postcss.Rule | string} The css selector to be processed
   * @param options The options for processing
   * @returns {any} The value returned by the processor.
   */;
  _proto.transformSync = function transformSync(rule, options) {
    return this._runSync(rule, options).transform;
  }

  /**
   * Process a selector into a new selector string asynchronously.
   *
   * @param rule {postcss.Rule | string} The css selector to be processed
   * @param options The options for processing
   * @returns {string} the selector after processing.
   */;
  _proto.process = function process(rule, options) {
    return this._run(rule, options).then(function (result) {
      return result.string || result.root.toString();
    });
  }

  /**
   * Process a selector into a new selector string synchronously.
   *
   * @param rule {postcss.Rule | string} The css selector to be processed
   * @param options The options for processing
   * @returns {string} the selector after processing.
   */;
  _proto.processSync = function processSync(rule, options) {
    var result = this._runSync(rule, options);
    return result.string || result.root.toString();
  };
  return Processor;
}();
exports["default"] = Processor;
module.exports = exports.default;PK~\ݖ%postcss-selector-parser/dist/index.jsnu["use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _processor = _interopRequireDefault(require("./processor"));
var selectors = _interopRequireWildcard(require("./selectors"));
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var parser = function parser(processor) {
  return new _processor["default"](processor);
};
Object.assign(parser, selectors);
delete parser.__esModule;
var _default = parser;
exports["default"] = _default;
module.exports = exports.default;PK~\eRAA3postcss-selector-parser/dist/selectors/attribute.jsnu["use strict";

exports.__esModule = true;
exports["default"] = void 0;
exports.unescapeValue = unescapeValue;
var _cssesc = _interopRequireDefault(require("cssesc"));
var _unesc = _interopRequireDefault(require("../util/unesc"));
var _namespace = _interopRequireDefault(require("./namespace"));
var _types = require("./types");
var _CSSESC_QUOTE_OPTIONS;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var deprecate = require("util-deprecate");
var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
function unescapeValue(value) {
  var deprecatedUsage = false;
  var quoteMark = null;
  var unescaped = value;
  var m = unescaped.match(WRAPPED_IN_QUOTES);
  if (m) {
    quoteMark = m[1];
    unescaped = m[2];
  }
  unescaped = (0, _unesc["default"])(unescaped);
  if (unescaped !== value) {
    deprecatedUsage = true;
  }
  return {
    deprecatedUsage: deprecatedUsage,
    unescaped: unescaped,
    quoteMark: quoteMark
  };
}
function handleDeprecatedContructorOpts(opts) {
  if (opts.quoteMark !== undefined) {
    return opts;
  }
  if (opts.value === undefined) {
    return opts;
  }
  warnOfDeprecatedConstructor();
  var _unescapeValue = unescapeValue(opts.value),
    quoteMark = _unescapeValue.quoteMark,
    unescaped = _unescapeValue.unescaped;
  if (!opts.raws) {
    opts.raws = {};
  }
  if (opts.raws.value === undefined) {
    opts.raws.value = opts.value;
  }
  opts.value = unescaped;
  opts.quoteMark = quoteMark;
  return opts;
}
var Attribute = /*#__PURE__*/function (_Namespace) {
  _inheritsLoose(Attribute, _Namespace);
  function Attribute(opts) {
    var _this;
    if (opts === void 0) {
      opts = {};
    }
    _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
    _this.type = _types.ATTRIBUTE;
    _this.raws = _this.raws || {};
    Object.defineProperty(_this.raws, 'unquoted', {
      get: deprecate(function () {
        return _this.value;
      }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
      set: deprecate(function () {
        return _this.value;
      }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
    });
    _this._constructed = true;
    return _this;
  }

  /**
   * Returns the Attribute's value quoted such that it would be legal to use
   * in the value of a css file. The original value's quotation setting
   * used for stringification is left unchanged. See `setValue(value, options)`
   * if you want to control the quote settings of a new value for the attribute.
   *
   * You can also change the quotation used for the current value by setting quoteMark.
   *
   * Options:
   *   * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
   *     option is not set, the original value for quoteMark will be used. If
   *     indeterminate, a double quote is used. The legal values are:
   *     * `null` - the value will be unquoted and characters will be escaped as necessary.
   *     * `'` - the value will be quoted with a single quote and single quotes are escaped.
   *     * `"` - the value will be quoted with a double quote and double quotes are escaped.
   *   * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
   *     over the quoteMark option value.
   *   * smart {boolean} - if true, will select a quote mark based on the value
   *     and the other options specified here. See the `smartQuoteMark()`
   *     method.
   **/
  var _proto = Attribute.prototype;
  _proto.getQuotedValue = function getQuotedValue(options) {
    if (options === void 0) {
      options = {};
    }
    var quoteMark = this._determineQuoteMark(options);
    var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
    var escaped = (0, _cssesc["default"])(this._value, cssescopts);
    return escaped;
  };
  _proto._determineQuoteMark = function _determineQuoteMark(options) {
    return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  }

  /**
   * Set the unescaped value with the specified quotation options. The value
   * provided must not include any wrapping quote marks -- those quotes will
   * be interpreted as part of the value and escaped accordingly.
   */;
  _proto.setValue = function setValue(value, options) {
    if (options === void 0) {
      options = {};
    }
    this._value = value;
    this._quoteMark = this._determineQuoteMark(options);
    this._syncRawValue();
  }

  /**
   * Intelligently select a quoteMark value based on the value's contents. If
   * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
   * mark will be picked that minimizes the number of escapes.
   *
   * If there's no clear winner, the quote mark from these options is used,
   * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
   * true). If the quoteMark is unspecified, a double quote is used.
   *
   * @param options This takes the quoteMark and preferCurrentQuoteMark options
   * from the quoteValue method.
   */;
  _proto.smartQuoteMark = function smartQuoteMark(options) {
    var v = this.value;
    var numSingleQuotes = v.replace(/[^']/g, '').length;
    var numDoubleQuotes = v.replace(/[^"]/g, '').length;
    if (numSingleQuotes + numDoubleQuotes === 0) {
      var escaped = (0, _cssesc["default"])(v, {
        isIdentifier: true
      });
      if (escaped === v) {
        return Attribute.NO_QUOTE;
      } else {
        var pref = this.preferredQuoteMark(options);
        if (pref === Attribute.NO_QUOTE) {
          // pick a quote mark that isn't none and see if it's smaller
          var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
          var opts = CSSESC_QUOTE_OPTIONS[quote];
          var quoteValue = (0, _cssesc["default"])(v, opts);
          if (quoteValue.length < escaped.length) {
            return quote;
          }
        }
        return pref;
      }
    } else if (numDoubleQuotes === numSingleQuotes) {
      return this.preferredQuoteMark(options);
    } else if (numDoubleQuotes < numSingleQuotes) {
      return Attribute.DOUBLE_QUOTE;
    } else {
      return Attribute.SINGLE_QUOTE;
    }
  }

  /**
   * Selects the preferred quote mark based on the options and the current quote mark value.
   * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
   * instead.
   */;
  _proto.preferredQuoteMark = function preferredQuoteMark(options) {
    var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
    if (quoteMark === undefined) {
      quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
    }
    if (quoteMark === undefined) {
      quoteMark = Attribute.DOUBLE_QUOTE;
    }
    return quoteMark;
  };
  _proto._syncRawValue = function _syncRawValue() {
    var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
    if (rawValue === this._value) {
      if (this.raws) {
        delete this.raws.value;
      }
    } else {
      this.raws.value = rawValue;
    }
  };
  _proto._handleEscapes = function _handleEscapes(prop, value) {
    if (this._constructed) {
      var escaped = (0, _cssesc["default"])(value, {
        isIdentifier: true
      });
      if (escaped !== value) {
        this.raws[prop] = escaped;
      } else {
        delete this.raws[prop];
      }
    }
  };
  _proto._spacesFor = function _spacesFor(name) {
    var attrSpaces = {
      before: '',
      after: ''
    };
    var spaces = this.spaces[name] || {};
    var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
    return Object.assign(attrSpaces, spaces, rawSpaces);
  };
  _proto._stringFor = function _stringFor(name, spaceName, concat) {
    if (spaceName === void 0) {
      spaceName = name;
    }
    if (concat === void 0) {
      concat = defaultAttrConcat;
    }
    var attrSpaces = this._spacesFor(spaceName);
    return concat(this.stringifyProperty(name), attrSpaces);
  }

  /**
   * returns the offset of the attribute part specified relative to the
   * start of the node of the output string.
   *
   * * "ns" - alias for "namespace"
   * * "namespace" - the namespace if it exists.
   * * "attribute" - the attribute name
   * * "attributeNS" - the start of the attribute or its namespace
   * * "operator" - the match operator of the attribute
   * * "value" - The value (string or identifier)
   * * "insensitive" - the case insensitivity flag;
   * @param part One of the possible values inside an attribute.
   * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
   */;
  _proto.offsetOf = function offsetOf(name) {
    var count = 1;
    var attributeSpaces = this._spacesFor("attribute");
    count += attributeSpaces.before.length;
    if (name === "namespace" || name === "ns") {
      return this.namespace ? count : -1;
    }
    if (name === "attributeNS") {
      return count;
    }
    count += this.namespaceString.length;
    if (this.namespace) {
      count += 1;
    }
    if (name === "attribute") {
      return count;
    }
    count += this.stringifyProperty("attribute").length;
    count += attributeSpaces.after.length;
    var operatorSpaces = this._spacesFor("operator");
    count += operatorSpaces.before.length;
    var operator = this.stringifyProperty("operator");
    if (name === "operator") {
      return operator ? count : -1;
    }
    count += operator.length;
    count += operatorSpaces.after.length;
    var valueSpaces = this._spacesFor("value");
    count += valueSpaces.before.length;
    var value = this.stringifyProperty("value");
    if (name === "value") {
      return value ? count : -1;
    }
    count += value.length;
    count += valueSpaces.after.length;
    var insensitiveSpaces = this._spacesFor("insensitive");
    count += insensitiveSpaces.before.length;
    if (name === "insensitive") {
      return this.insensitive ? count : -1;
    }
    return -1;
  };
  _proto.toString = function toString() {
    var _this2 = this;
    var selector = [this.rawSpaceBefore, '['];
    selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
    if (this.operator && (this.value || this.value === '')) {
      selector.push(this._stringFor('operator'));
      selector.push(this._stringFor('value'));
      selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
        if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
          attrSpaces.before = " ";
        }
        return defaultAttrConcat(attrValue, attrSpaces);
      }));
    }
    selector.push(']');
    selector.push(this.rawSpaceAfter);
    return selector.join('');
  };
  _createClass(Attribute, [{
    key: "quoted",
    get: function get() {
      var qm = this.quoteMark;
      return qm === "'" || qm === '"';
    },
    set: function set(value) {
      warnOfDeprecatedQuotedAssignment();
    }

    /**
     * returns a single (`'`) or double (`"`) quote character if the value is quoted.
     * returns `null` if the value is not quoted.
     * returns `undefined` if the quotation state is unknown (this can happen when
     * the attribute is constructed without specifying a quote mark.)
     */
  }, {
    key: "quoteMark",
    get: function get() {
      return this._quoteMark;
    }

    /**
     * Set the quote mark to be used by this attribute's value.
     * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
     * value is updated accordingly.
     *
     * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
     */,
    set: function set(quoteMark) {
      if (!this._constructed) {
        this._quoteMark = quoteMark;
        return;
      }
      if (this._quoteMark !== quoteMark) {
        this._quoteMark = quoteMark;
        this._syncRawValue();
      }
    }
  }, {
    key: "qualifiedAttribute",
    get: function get() {
      return this.qualifiedName(this.raws.attribute || this.attribute);
    }
  }, {
    key: "insensitiveFlag",
    get: function get() {
      return this.insensitive ? 'i' : '';
    }
  }, {
    key: "value",
    get: function get() {
      return this._value;
    },
    set:
    /**
     * Before 3.0, the value had to be set to an escaped value including any wrapped
     * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
     * is unescaped during parsing and any quote marks are removed.
     *
     * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
     * a deprecation warning is raised when the new value contains any characters that would
     * require escaping (including if it contains wrapped quotes).
     *
     * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
     * how the new value is quoted.
     */
    function set(v) {
      if (this._constructed) {
        var _unescapeValue2 = unescapeValue(v),
          deprecatedUsage = _unescapeValue2.deprecatedUsage,
          unescaped = _unescapeValue2.unescaped,
          quoteMark = _unescapeValue2.quoteMark;
        if (deprecatedUsage) {
          warnOfDeprecatedValueAssignment();
        }
        if (unescaped === this._value && quoteMark === this._quoteMark) {
          return;
        }
        this._value = unescaped;
        this._quoteMark = quoteMark;
        this._syncRawValue();
      } else {
        this._value = v;
      }
    }
  }, {
    key: "insensitive",
    get: function get() {
      return this._insensitive;
    }

    /**
     * Set the case insensitive flag.
     * If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag`
     * of the attribute is updated accordingly.
     *
     * @param {true | false} insensitive true if the attribute should match case-insensitively.
     */,
    set: function set(insensitive) {
      if (!insensitive) {
        this._insensitive = false;

        // "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation.
        // When setting `attr.insensitive = false` both should be erased to ensure correct serialization.
        if (this.raws && (this.raws.insensitiveFlag === 'I' || this.raws.insensitiveFlag === 'i')) {
          this.raws.insensitiveFlag = undefined;
        }
      }
      this._insensitive = insensitive;
    }
  }, {
    key: "attribute",
    get: function get() {
      return this._attribute;
    },
    set: function set(name) {
      this._handleEscapes("attribute", name);
      this._attribute = name;
    }
  }]);
  return Attribute;
}(_namespace["default"]);
exports["default"] = Attribute;
Attribute.NO_QUOTE = null;
Attribute.SINGLE_QUOTE = "'";
Attribute.DOUBLE_QUOTE = '"';
var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
  "'": {
    quotes: 'single',
    wrap: true
  },
  '"': {
    quotes: 'double',
    wrap: true
  }
}, _CSSESC_QUOTE_OPTIONS[null] = {
  isIdentifier: true
}, _CSSESC_QUOTE_OPTIONS);
function defaultAttrConcat(attrValue, attrSpaces) {
  return "" + attrSpaces.before + attrValue + attrSpaces.after;
}PK~\:J.J.3postcss-selector-parser/dist/selectors/container.jsnu["use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _node = _interopRequireDefault(require("./node"));
var types = _interopRequireWildcard(require("./types"));
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var Container = /*#__PURE__*/function (_Node) {
  _inheritsLoose(Container, _Node);
  function Container(opts) {
    var _this;
    _this = _Node.call(this, opts) || this;
    if (!_this.nodes) {
      _this.nodes = [];
    }
    return _this;
  }
  var _proto = Container.prototype;
  _proto.append = function append(selector) {
    selector.parent = this;
    this.nodes.push(selector);
    return this;
  };
  _proto.prepend = function prepend(selector) {
    selector.parent = this;
    this.nodes.unshift(selector);
    return this;
  };
  _proto.at = function at(index) {
    return this.nodes[index];
  };
  _proto.index = function index(child) {
    if (typeof child === 'number') {
      return child;
    }
    return this.nodes.indexOf(child);
  };
  _proto.removeChild = function removeChild(child) {
    child = this.index(child);
    this.at(child).parent = undefined;
    this.nodes.splice(child, 1);
    var index;
    for (var id in this.indexes) {
      index = this.indexes[id];
      if (index >= child) {
        this.indexes[id] = index - 1;
      }
    }
    return this;
  };
  _proto.removeAll = function removeAll() {
    for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) {
      var node = _step.value;
      node.parent = undefined;
    }
    this.nodes = [];
    return this;
  };
  _proto.empty = function empty() {
    return this.removeAll();
  };
  _proto.insertAfter = function insertAfter(oldNode, newNode) {
    newNode.parent = this;
    var oldIndex = this.index(oldNode);
    this.nodes.splice(oldIndex + 1, 0, newNode);
    newNode.parent = this;
    var index;
    for (var id in this.indexes) {
      index = this.indexes[id];
      if (oldIndex <= index) {
        this.indexes[id] = index + 1;
      }
    }
    return this;
  };
  _proto.insertBefore = function insertBefore(oldNode, newNode) {
    newNode.parent = this;
    var oldIndex = this.index(oldNode);
    this.nodes.splice(oldIndex, 0, newNode);
    newNode.parent = this;
    var index;
    for (var id in this.indexes) {
      index = this.indexes[id];
      if (index <= oldIndex) {
        this.indexes[id] = index + 1;
      }
    }
    return this;
  };
  _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
    var found = undefined;
    this.each(function (node) {
      if (node.atPosition) {
        var foundChild = node.atPosition(line, col);
        if (foundChild) {
          found = foundChild;
          return false;
        }
      } else if (node.isAtPosition(line, col)) {
        found = node;
        return false;
      }
    });
    return found;
  }

  /**
   * Return the most specific node at the line and column number given.
   * The source location is based on the original parsed location, locations aren't
   * updated as selector nodes are mutated.
   * 
   * Note that this location is relative to the location of the first character
   * of the selector, and not the location of the selector in the overall document
   * when used in conjunction with postcss.
   *
   * If not found, returns undefined.
   * @param {number} line The line number of the node to find. (1-based index)
   * @param {number} col  The column number of the node to find. (1-based index)
   */;
  _proto.atPosition = function atPosition(line, col) {
    if (this.isAtPosition(line, col)) {
      return this._findChildAtPosition(line, col) || this;
    } else {
      return undefined;
    }
  };
  _proto._inferEndPosition = function _inferEndPosition() {
    if (this.last && this.last.source && this.last.source.end) {
      this.source = this.source || {};
      this.source.end = this.source.end || {};
      Object.assign(this.source.end, this.last.source.end);
    }
  };
  _proto.each = function each(callback) {
    if (!this.lastEach) {
      this.lastEach = 0;
    }
    if (!this.indexes) {
      this.indexes = {};
    }
    this.lastEach++;
    var id = this.lastEach;
    this.indexes[id] = 0;
    if (!this.length) {
      return undefined;
    }
    var index, result;
    while (this.indexes[id] < this.length) {
      index = this.indexes[id];
      result = callback(this.at(index), index);
      if (result === false) {
        break;
      }
      this.indexes[id] += 1;
    }
    delete this.indexes[id];
    if (result === false) {
      return false;
    }
  };
  _proto.walk = function walk(callback) {
    return this.each(function (node, i) {
      var result = callback(node, i);
      if (result !== false && node.length) {
        result = node.walk(callback);
      }
      if (result === false) {
        return false;
      }
    });
  };
  _proto.walkAttributes = function walkAttributes(callback) {
    var _this2 = this;
    return this.walk(function (selector) {
      if (selector.type === types.ATTRIBUTE) {
        return callback.call(_this2, selector);
      }
    });
  };
  _proto.walkClasses = function walkClasses(callback) {
    var _this3 = this;
    return this.walk(function (selector) {
      if (selector.type === types.CLASS) {
        return callback.call(_this3, selector);
      }
    });
  };
  _proto.walkCombinators = function walkCombinators(callback) {
    var _this4 = this;
    return this.walk(function (selector) {
      if (selector.type === types.COMBINATOR) {
        return callback.call(_this4, selector);
      }
    });
  };
  _proto.walkComments = function walkComments(callback) {
    var _this5 = this;
    return this.walk(function (selector) {
      if (selector.type === types.COMMENT) {
        return callback.call(_this5, selector);
      }
    });
  };
  _proto.walkIds = function walkIds(callback) {
    var _this6 = this;
    return this.walk(function (selector) {
      if (selector.type === types.ID) {
        return callback.call(_this6, selector);
      }
    });
  };
  _proto.walkNesting = function walkNesting(callback) {
    var _this7 = this;
    return this.walk(function (selector) {
      if (selector.type === types.NESTING) {
        return callback.call(_this7, selector);
      }
    });
  };
  _proto.walkPseudos = function walkPseudos(callback) {
    var _this8 = this;
    return this.walk(function (selector) {
      if (selector.type === types.PSEUDO) {
        return callback.call(_this8, selector);
      }
    });
  };
  _proto.walkTags = function walkTags(callback) {
    var _this9 = this;
    return this.walk(function (selector) {
      if (selector.type === types.TAG) {
        return callback.call(_this9, selector);
      }
    });
  };
  _proto.walkUniversals = function walkUniversals(callback) {
    var _this10 = this;
    return this.walk(function (selector) {
      if (selector.type === types.UNIVERSAL) {
        return callback.call(_this10, selector);
      }
    });
  };
  _proto.split = function split(callback) {
    var _this11 = this;
    var current = [];
    return this.reduce(function (memo, node, index) {
      var split = callback.call(_this11, node);
      current.push(node);
      if (split) {
        memo.push(current);
        current = [];
      } else if (index === _this11.length - 1) {
        memo.push(current);
      }
      return memo;
    }, []);
  };
  _proto.map = function map(callback) {
    return this.nodes.map(callback);
  };
  _proto.reduce = function reduce(callback, memo) {
    return this.nodes.reduce(callback, memo);
  };
  _proto.every = function every(callback) {
    return this.nodes.every(callback);
  };
  _proto.some = function some(callback) {
    return this.nodes.some(callback);
  };
  _proto.filter = function filter(callback) {
    return this.nodes.filter(callback);
  };
  _proto.sort = function sort(callback) {
    return this.nodes.sort(callback);
  };
  _proto.toString = function toString() {
    return this.map(String).join('');
  };
  _createClass(Container, [{
    key: "first",
    get: function get() {
      return this.at(0);
    }
  }, {
    key: "last",
    get: function get() {
      return this.at(this.length - 1);
    }
  }, {
    key: "length",
    get: function get() {
      return this.nodes.length;
    }
  }]);
  return Container;
}(_node["default"]);
exports["default"] = Container;
module.exports = exports.default;PK~\^E*	*	3postcss-selector-parser/dist/selectors/className.jsnu["use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _cssesc = _interopRequireDefault(require("cssesc"));
var _util = require("../util");
var _node = _interopRequireDefault(require("./node"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var ClassName = /*#__PURE__*/function (_Node) {
  _inheritsLoose(ClassName, _Node);
  function ClassName(opts) {
    var _this;
    _this = _Node.call(this, opts) || this;
    _this.type = _types.CLASS;
    _this._constructed = true;
    return _this;
  }
  var _proto = ClassName.prototype;
  _proto.valueToString = function valueToString() {
    return '.' + _Node.prototype.valueToString.call(this);
  };
  _createClass(ClassName, [{
    key: "value",
    get: function get() {
      return this._value;
    },
    set: function set(v) {
      if (this._constructed) {
        var escaped = (0, _cssesc["default"])(v, {
          isIdentifier: true
        });
        if (escaped !== v) {
          (0, _util.ensureObject)(this, "raws");
          this.raws.value = escaped;
        } else if (this.raws) {
          delete this.raws.value;
        }
      }
      this._value = v;
    }
  }]);
  return ClassName;
}(_node["default"]);
exports["default"] = ClassName;
module.exports = exports.default;PK~\C\QQ/postcss-selector-parser/dist/selectors/types.jsnu["use strict";

exports.__esModule = true;
exports.UNIVERSAL = exports.TAG = exports.STRING = exports.SELECTOR = exports.ROOT = exports.PSEUDO = exports.NESTING = exports.ID = exports.COMMENT = exports.COMBINATOR = exports.CLASS = exports.ATTRIBUTE = void 0;
var TAG = 'tag';
exports.TAG = TAG;
var STRING = 'string';
exports.STRING = STRING;
var SELECTOR = 'selector';
exports.SELECTOR = SELECTOR;
var ROOT = 'root';
exports.ROOT = ROOT;
var PSEUDO = 'pseudo';
exports.PSEUDO = PSEUDO;
var NESTING = 'nesting';
exports.NESTING = NESTING;
var ID = 'id';
exports.ID = ID;
var COMMENT = 'comment';
exports.COMMENT = COMMENT;
var COMBINATOR = 'combinator';
exports.COMBINATOR = COMBINATOR;
var CLASS = 'class';
exports.CLASS = CLASS;
var ATTRIBUTE = 'attribute';
exports.ATTRIBUTE = ATTRIBUTE;
var UNIVERSAL = 'universal';
exports.UNIVERSAL = UNIVERSAL;PK~\`*wC	C	6postcss-selector-parser/dist/selectors/constructors.jsnu["use strict";

exports.__esModule = true;
exports.universal = exports.tag = exports.string = exports.selector = exports.root = exports.pseudo = exports.nesting = exports.id = exports.comment = exports.combinator = exports.className = exports.attribute = void 0;
var _attribute = _interopRequireDefault(require("./attribute"));
var _className = _interopRequireDefault(require("./className"));
var _combinator = _interopRequireDefault(require("./combinator"));
var _comment = _interopRequireDefault(require("./comment"));
var _id = _interopRequireDefault(require("./id"));
var _nesting = _interopRequireDefault(require("./nesting"));
var _pseudo = _interopRequireDefault(require("./pseudo"));
var _root = _interopRequireDefault(require("./root"));
var _selector = _interopRequireDefault(require("./selector"));
var _string = _interopRequireDefault(require("./string"));
var _tag = _interopRequireDefault(require("./tag"));
var _universal = _interopRequireDefault(require("./universal"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var attribute = function attribute(opts) {
  return new _attribute["default"](opts);
};
exports.attribute = attribute;
var className = function className(opts) {
  return new _className["default"](opts);
};
exports.className = className;
var combinator = function combinator(opts) {
  return new _combinator["default"](opts);
};
exports.combinator = combinator;
var comment = function comment(opts) {
  return new _comment["default"](opts);
};
exports.comment = comment;
var id = function id(opts) {
  return new _id["default"](opts);
};
exports.id = id;
var nesting = function nesting(opts) {
  return new _nesting["default"](opts);
};
exports.nesting = nesting;
var pseudo = function pseudo(opts) {
  return new _pseudo["default"](opts);
};
exports.pseudo = pseudo;
var root = function root(opts) {
  return new _root["default"](opts);
};
exports.root = root;
var selector = function selector(opts) {
  return new _selector["default"](opts);
};
exports.selector = selector;
var string = function string(opts) {
  return new _string["default"](opts);
};
exports.string = string;
var tag = function tag(opts) {
  return new _tag["default"](opts);
};
exports.tag = tag;
var universal = function universal(opts) {
  return new _universal["default"](opts);
};
exports.universal = universal;PK~\*4postcss-selector-parser/dist/selectors/combinator.jsnu["use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _node = _interopRequireDefault(require("./node"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var Combinator = /*#__PURE__*/function (_Node) {
  _inheritsLoose(Combinator, _Node);
  function Combinator(opts) {
    var _this;
    _this = _Node.call(this, opts) || this;
    _this.type = _types.COMBINATOR;
    return _this;
  }
  return Combinator;
}(_node["default"]);
exports["default"] = Combinator;
module.exports = exports.default;PK~\03postcss-selector-parser/dist/selectors/universal.jsnu["use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _namespace = _interopRequireDefault(require("./namespace"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var Universal = /*#__PURE__*/function (_Namespace) {
  _inheritsLoose(Universal, _Namespace);
  function Universal(opts) {
    var _this;
    _this = _Namespace.call(this, opts) || this;
    _this.type = _types.UNIVERSAL;
    _this.value = '*';
    return _this;
  }
  return Universal;
}(_namespace["default"]);
exports["default"] = Universal;
module.exports = exports.default;PK~\0
83postcss-selector-parser/dist/selectors/namespace.jsnu["use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _cssesc = _interopRequireDefault(require("cssesc"));
var _util = require("../util");
var _node = _interopRequireDefault(require("./node"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var Namespace = /*#__PURE__*/function (_Node) {
  _inheritsLoose(Namespace, _Node);
  function Namespace() {
    return _Node.apply(this, arguments) || this;
  }
  var _proto = Namespace.prototype;
  _proto.qualifiedName = function qualifiedName(value) {
    if (this.namespace) {
      return this.namespaceString + "|" + value;
    } else {
      return value;
    }
  };
  _proto.valueToString = function valueToString() {
    return this.qualifiedName(_Node.prototype.valueToString.call(this));
  };
  _createClass(Namespace, [{
    key: "namespace",
    get: function get() {
      return this._namespace;
    },
    set: function set(namespace) {
      if (namespace === true || namespace === "*" || namespace === "&") {
        this._namespace = namespace;
        if (this.raws) {
          delete this.raws.namespace;
        }
        return;
      }
      var escaped = (0, _cssesc["default"])(namespace, {
        isIdentifier: true
      });
      this._namespace = namespace;
      if (escaped !== namespace) {
        (0, _util.ensureObject)(this, "raws");
        this.raws.namespace = escaped;
      } else if (this.raws) {
        delete this.raws.namespace;
      }
    }
  }, {
    key: "ns",
    get: function get() {
      return this._namespace;
    },
    set: function set(namespace) {
      this.namespace = namespace;
    }
  }, {
    key: "namespaceString",
    get: function get() {
      if (this.namespace) {
        var ns = this.stringifyProperty("namespace");
        if (ns === true) {
          return '';
        } else {
          return ns;
        }
      } else {
        return '';
      }
    }
  }]);
  return Namespace;
}(_node["default"]);
exports["default"] = Namespace;
;
module.exports = exports.default;PK~\s2postcss-selector-parser/dist/selectors/selector.jsnu["use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _container = _interopRequireDefault(require("./container"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var Selector = /*#__PURE__*/function (_Container) {
  _inheritsLoose(Selector, _Container);
  function Selector(opts) {
    var _this;
    _this = _Container.call(this, opts) || this;
    _this.type = _types.SELECTOR;
    return _this;
  }
  return Selector;
}(_container["default"]);
exports["default"] = Selector;
module.exports = exports.default;PK~\1postcss-selector-parser/dist/selectors/comment.jsnu["use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _node = _interopRequireDefault(require("./node"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var Comment = /*#__PURE__*/function (_Node) {
  _inheritsLoose(Comment, _Node);
  function Comment(opts) {
    var _this;
    _this = _Node.call(this, opts) || this;
    _this.type = _types.COMMENT;
    return _this;
  }
  return Comment;
}(_node["default"]);
exports["default"] = Comment;
module.exports = exports.default;PK~\i +bb.postcss-selector-parser/dist/selectors/root.jsnu["use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _container = _interopRequireDefault(require("./container"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var Root = /*#__PURE__*/function (_Container) {
  _inheritsLoose(Root, _Container);
  function Root(opts) {
    var _this;
    _this = _Container.call(this, opts) || this;
    _this.type = _types.ROOT;
    return _this;
  }
  var _proto = Root.prototype;
  _proto.toString = function toString() {
    var str = this.reduce(function (memo, selector) {
      memo.push(String(selector));
      return memo;
    }, []).join(',');
    return this.trailingComma ? str + ',' : str;
  };
  _proto.error = function error(message, options) {
    if (this._error) {
      return this._error(message, options);
    } else {
      return new Error(message);
    }
  };
  _createClass(Root, [{
    key: "errorGenerator",
    set: function set(handler) {
      this._error = handler;
    }
  }]);
  return Root;
}(_container["default"]);
exports["default"] = Root;
module.exports = exports.default;PK~\/postcss-selector-parser/dist/selectors/index.jsnu["use strict";

exports.__esModule = true;
var _types = require("./types");
Object.keys(_types).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _types[key]) return;
  exports[key] = _types[key];
});
var _constructors = require("./constructors");
Object.keys(_constructors).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _constructors[key]) return;
  exports[key] = _constructors[key];
});
var _guards = require("./guards");
Object.keys(_guards).forEach(function (key) {
  if (key === "default" || key === "__esModule") return;
  if (key in exports && exports[key] === _guards[key]) return;
  exports[key] = _guards[key];
});PK~\1postcss-selector-parser/dist/selectors/nesting.jsnu["use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _node = _interopRequireDefault(require("./node"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var Nesting = /*#__PURE__*/function (_Node) {
  _inheritsLoose(Nesting, _Node);
  function Nesting(opts) {
    var _this;
    _this = _Node.call(this, opts) || this;
    _this.type = _types.NESTING;
    _this.value = '&';
    return _this;
  }
  return Nesting;
}(_node["default"]);
exports["default"] = Nesting;
module.exports = exports.default;PK~\jxl]0postcss-selector-parser/dist/selectors/string.jsnu["use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _node = _interopRequireDefault(require("./node"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var String = /*#__PURE__*/function (_Node) {
  _inheritsLoose(String, _Node);
  function String(opts) {
    var _this;
    _this = _Node.call(this, opts) || this;
    _this.type = _types.STRING;
    return _this;
  }
  return String;
}(_node["default"]);
exports["default"] = String;
module.exports = exports.default;PK~\t>>,postcss-selector-parser/dist/selectors/id.jsnu["use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _node = _interopRequireDefault(require("./node"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var ID = /*#__PURE__*/function (_Node) {
  _inheritsLoose(ID, _Node);
  function ID(opts) {
    var _this;
    _this = _Node.call(this, opts) || this;
    _this.type = _types.ID;
    return _this;
  }
  var _proto = ID.prototype;
  _proto.valueToString = function valueToString() {
    return '#' + _Node.prototype.valueToString.call(this);
  };
  return ID;
}(_node["default"]);
exports["default"] = ID;
module.exports = exports.default;PK~\%6

0postcss-selector-parser/dist/selectors/guards.jsnu["use strict";

exports.__esModule = true;
exports.isComment = exports.isCombinator = exports.isClassName = exports.isAttribute = void 0;
exports.isContainer = isContainer;
exports.isIdentifier = void 0;
exports.isNamespace = isNamespace;
exports.isNesting = void 0;
exports.isNode = isNode;
exports.isPseudo = void 0;
exports.isPseudoClass = isPseudoClass;
exports.isPseudoElement = isPseudoElement;
exports.isUniversal = exports.isTag = exports.isString = exports.isSelector = exports.isRoot = void 0;
var _types = require("./types");
var _IS_TYPE;
var IS_TYPE = (_IS_TYPE = {}, _IS_TYPE[_types.ATTRIBUTE] = true, _IS_TYPE[_types.CLASS] = true, _IS_TYPE[_types.COMBINATOR] = true, _IS_TYPE[_types.COMMENT] = true, _IS_TYPE[_types.ID] = true, _IS_TYPE[_types.NESTING] = true, _IS_TYPE[_types.PSEUDO] = true, _IS_TYPE[_types.ROOT] = true, _IS_TYPE[_types.SELECTOR] = true, _IS_TYPE[_types.STRING] = true, _IS_TYPE[_types.TAG] = true, _IS_TYPE[_types.UNIVERSAL] = true, _IS_TYPE);
function isNode(node) {
  return typeof node === "object" && IS_TYPE[node.type];
}
function isNodeType(type, node) {
  return isNode(node) && node.type === type;
}
var isAttribute = isNodeType.bind(null, _types.ATTRIBUTE);
exports.isAttribute = isAttribute;
var isClassName = isNodeType.bind(null, _types.CLASS);
exports.isClassName = isClassName;
var isCombinator = isNodeType.bind(null, _types.COMBINATOR);
exports.isCombinator = isCombinator;
var isComment = isNodeType.bind(null, _types.COMMENT);
exports.isComment = isComment;
var isIdentifier = isNodeType.bind(null, _types.ID);
exports.isIdentifier = isIdentifier;
var isNesting = isNodeType.bind(null, _types.NESTING);
exports.isNesting = isNesting;
var isPseudo = isNodeType.bind(null, _types.PSEUDO);
exports.isPseudo = isPseudo;
var isRoot = isNodeType.bind(null, _types.ROOT);
exports.isRoot = isRoot;
var isSelector = isNodeType.bind(null, _types.SELECTOR);
exports.isSelector = isSelector;
var isString = isNodeType.bind(null, _types.STRING);
exports.isString = isString;
var isTag = isNodeType.bind(null, _types.TAG);
exports.isTag = isTag;
var isUniversal = isNodeType.bind(null, _types.UNIVERSAL);
exports.isUniversal = isUniversal;
function isPseudoElement(node) {
  return isPseudo(node) && node.value && (node.value.startsWith("::") || node.value.toLowerCase() === ":before" || node.value.toLowerCase() === ":after" || node.value.toLowerCase() === ":first-letter" || node.value.toLowerCase() === ":first-line");
}
function isPseudoClass(node) {
  return isPseudo(node) && !isPseudoElement(node);
}
function isContainer(node) {
  return !!(isNode(node) && node.walk);
}
function isNamespace(node) {
  return isAttribute(node) || isTag(node);
}PK~\懈-postcss-selector-parser/dist/selectors/tag.jsnu["use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _namespace = _interopRequireDefault(require("./namespace"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var Tag = /*#__PURE__*/function (_Namespace) {
  _inheritsLoose(Tag, _Namespace);
  function Tag(opts) {
    var _this;
    _this = _Namespace.call(this, opts) || this;
    _this.type = _types.TAG;
    return _this;
  }
  return Tag;
}(_namespace["default"]);
exports["default"] = Tag;
module.exports = exports.default;PK~\D2}"".postcss-selector-parser/dist/selectors/node.jsnu["use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _util = require("../util");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
var cloneNode = function cloneNode(obj, parent) {
  if (typeof obj !== 'object' || obj === null) {
    return obj;
  }
  var cloned = new obj.constructor();
  for (var i in obj) {
    if (!obj.hasOwnProperty(i)) {
      continue;
    }
    var value = obj[i];
    var type = typeof value;
    if (i === 'parent' && type === 'object') {
      if (parent) {
        cloned[i] = parent;
      }
    } else if (value instanceof Array) {
      cloned[i] = value.map(function (j) {
        return cloneNode(j, cloned);
      });
    } else {
      cloned[i] = cloneNode(value, cloned);
    }
  }
  return cloned;
};
var Node = /*#__PURE__*/function () {
  function Node(opts) {
    if (opts === void 0) {
      opts = {};
    }
    Object.assign(this, opts);
    this.spaces = this.spaces || {};
    this.spaces.before = this.spaces.before || '';
    this.spaces.after = this.spaces.after || '';
  }
  var _proto = Node.prototype;
  _proto.remove = function remove() {
    if (this.parent) {
      this.parent.removeChild(this);
    }
    this.parent = undefined;
    return this;
  };
  _proto.replaceWith = function replaceWith() {
    if (this.parent) {
      for (var index in arguments) {
        this.parent.insertBefore(this, arguments[index]);
      }
      this.remove();
    }
    return this;
  };
  _proto.next = function next() {
    return this.parent.at(this.parent.index(this) + 1);
  };
  _proto.prev = function prev() {
    return this.parent.at(this.parent.index(this) - 1);
  };
  _proto.clone = function clone(overrides) {
    if (overrides === void 0) {
      overrides = {};
    }
    var cloned = cloneNode(this);
    for (var name in overrides) {
      cloned[name] = overrides[name];
    }
    return cloned;
  }

  /**
   * Some non-standard syntax doesn't follow normal escaping rules for css.
   * This allows non standard syntax to be appended to an existing property
   * by specifying the escaped value. By specifying the escaped value,
   * illegal characters are allowed to be directly inserted into css output.
   * @param {string} name the property to set
   * @param {any} value the unescaped value of the property
   * @param {string} valueEscaped optional. the escaped value of the property.
   */;
  _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
    if (!this.raws) {
      this.raws = {};
    }
    var originalValue = this[name];
    var originalEscaped = this.raws[name];
    this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
    if (originalEscaped || valueEscaped !== value) {
      this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
    } else {
      delete this.raws[name]; // delete any escaped value that was created by the setter.
    }
  }

  /**
   * Some non-standard syntax doesn't follow normal escaping rules for css.
   * This allows the escaped value to be specified directly, allowing illegal
   * characters to be directly inserted into css output.
   * @param {string} name the property to set
   * @param {any} value the unescaped value of the property
   * @param {string} valueEscaped the escaped value of the property.
   */;
  _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
    if (!this.raws) {
      this.raws = {};
    }
    this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
    this.raws[name] = valueEscaped;
  }

  /**
   * When you want a value to passed through to CSS directly. This method
   * deletes the corresponding raw value causing the stringifier to fallback
   * to the unescaped value.
   * @param {string} name the property to set.
   * @param {any} value The value that is both escaped and unescaped.
   */;
  _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
    this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
    if (this.raws) {
      delete this.raws[name];
    }
  }

  /**
   *
   * @param {number} line The number (starting with 1)
   * @param {number} column The column number (starting with 1)
   */;
  _proto.isAtPosition = function isAtPosition(line, column) {
    if (this.source && this.source.start && this.source.end) {
      if (this.source.start.line > line) {
        return false;
      }
      if (this.source.end.line < line) {
        return false;
      }
      if (this.source.start.line === line && this.source.start.column > column) {
        return false;
      }
      if (this.source.end.line === line && this.source.end.column < column) {
        return false;
      }
      return true;
    }
    return undefined;
  };
  _proto.stringifyProperty = function stringifyProperty(name) {
    return this.raws && this.raws[name] || this[name];
  };
  _proto.valueToString = function valueToString() {
    return String(this.stringifyProperty("value"));
  };
  _proto.toString = function toString() {
    return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join('');
  };
  _createClass(Node, [{
    key: "rawSpaceBefore",
    get: function get() {
      var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
      if (rawSpace === undefined) {
        rawSpace = this.spaces && this.spaces.before;
      }
      return rawSpace || "";
    },
    set: function set(raw) {
      (0, _util.ensureObject)(this, "raws", "spaces");
      this.raws.spaces.before = raw;
    }
  }, {
    key: "rawSpaceAfter",
    get: function get() {
      var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
      if (rawSpace === undefined) {
        rawSpace = this.spaces.after;
      }
      return rawSpace || "";
    },
    set: function set(raw) {
      (0, _util.ensureObject)(this, "raws", "spaces");
      this.raws.spaces.after = raw;
    }
  }]);
  return Node;
}();
exports["default"] = Node;
module.exports = exports.default;PK~\Ws0postcss-selector-parser/dist/selectors/pseudo.jsnu["use strict";

exports.__esModule = true;
exports["default"] = void 0;
var _container = _interopRequireDefault(require("./container"));
var _types = require("./types");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var Pseudo = /*#__PURE__*/function (_Container) {
  _inheritsLoose(Pseudo, _Container);
  function Pseudo(opts) {
    var _this;
    _this = _Container.call(this, opts) || this;
    _this.type = _types.PSEUDO;
    return _this;
  }
  var _proto = Pseudo.prototype;
  _proto.toString = function toString() {
    var params = this.length ? '(' + this.map(String).join(',') + ')' : '';
    return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
  };
  return Pseudo;
}(_container["default"]);
exports["default"] = Pseudo;
module.exports = exports.default;PK~\<u		2postcss-selector-parser/dist/util/stripComments.jsnu["use strict";

exports.__esModule = true;
exports["default"] = stripComments;
function stripComments(str) {
  var s = "";
  var commentStart = str.indexOf("/*");
  var lastEnd = 0;
  while (commentStart >= 0) {
    s = s + str.slice(lastEnd, commentStart);
    var commentEnd = str.indexOf("*/", commentStart + 2);
    if (commentEnd < 0) {
      return s;
    }
    lastEnd = commentEnd + 2;
    commentStart = str.indexOf("/*", lastEnd);
  }
  s = s + str.slice(lastEnd);
  return s;
}
module.exports = exports.default;PK~\%~*postcss-selector-parser/dist/util/index.jsnu["use strict";

exports.__esModule = true;
exports.unesc = exports.stripComments = exports.getProp = exports.ensureObject = void 0;
var _unesc = _interopRequireDefault(require("./unesc"));
exports.unesc = _unesc["default"];
var _getProp = _interopRequireDefault(require("./getProp"));
exports.getProp = _getProp["default"];
var _ensureObject = _interopRequireDefault(require("./ensureObject"));
exports.ensureObject = _ensureObject["default"];
var _stripComments = _interopRequireDefault(require("./stripComments"));
exports.stripComments = _stripComments["default"];
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }PK~\	i	,postcss-selector-parser/dist/util/getProp.jsnu["use strict";

exports.__esModule = true;
exports["default"] = getProp;
function getProp(obj) {
  for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    props[_key - 1] = arguments[_key];
  }
  while (props.length > 0) {
    var prop = props.shift();
    if (!obj[prop]) {
      return undefined;
    }
    obj = obj[prop];
  }
  return obj;
}
module.exports = exports.default;PK~\w"1postcss-selector-parser/dist/util/ensureObject.jsnu["use strict";

exports.__esModule = true;
exports["default"] = ensureObject;
function ensureObject(obj) {
  for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    props[_key - 1] = arguments[_key];
  }
  while (props.length > 0) {
    var prop = props.shift();
    if (!obj[prop]) {
      obj[prop] = {};
    }
    obj = obj[prop];
  }
}
module.exports = exports.default;PK~\䁮		*postcss-selector-parser/dist/util/unesc.jsnu["use strict";

exports.__esModule = true;
exports["default"] = unesc;
// Many thanks for this post which made this migration much easier.
// https://mathiasbynens.be/notes/css-escapes

/**
 * 
 * @param {string} str 
 * @returns {[string, number]|undefined}
 */
function gobbleHex(str) {
  var lower = str.toLowerCase();
  var hex = '';
  var spaceTerminated = false;
  for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
    var code = lower.charCodeAt(i);
    // check to see if we are dealing with a valid hex char [a-f|0-9]
    var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57;
    // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
    spaceTerminated = code === 32;
    if (!valid) {
      break;
    }
    hex += lower[i];
  }
  if (hex.length === 0) {
    return undefined;
  }
  var codePoint = parseInt(hex, 16);
  var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF;
  // Add special case for
  // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) {
    return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  }
  return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
}
var CONTAINS_ESCAPE = /\\/;
function unesc(str) {
  var needToProcess = CONTAINS_ESCAPE.test(str);
  if (!needToProcess) {
    return str;
  }
  var ret = "";
  for (var i = 0; i < str.length; i++) {
    if (str[i] === "\\") {
      var gobbled = gobbleHex(str.slice(i + 1, i + 7));
      if (gobbled !== undefined) {
        ret += gobbled[0];
        i += gobbled[1];
        continue;
      }

      // Retain a pair of \\ if double escaped `\\\\`
      // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
      if (str[i + 1] === "\\") {
        ret += "\\";
        i++;
        continue;
      }

      // if \\ is at the end of the string retain it
      // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
      if (str.length === i + 1) {
        ret += str[i];
      }
      continue;
    }
    ret += str[i];
  }
  return ret;
}
module.exports = exports.default;PK~\͍DD#postcss-selector-parser/LICENSE-MITnu[Copyright (c) Ben Briggs  (http://beneb.info)

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
PK~\0 json-stringify-nice/package.jsonnu[{
  "_id": "json-stringify-nice@1.1.4",
  "_inBundle": true,
  "_location": "/npm/json-stringify-nice",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm/@npmcli/arborist"
  ],
  "author": {
    "name": "Isaac Z. Schlueter",
    "email": "i@izs.me",
    "url": "https://izs.me"
  },
  "bugs": {
    "url": "https://github.com/isaacs/json-stringify-nice/issues"
  },
  "description": "Stringify an object sorting scalars before objects, and defaulting to 2-space indent",
  "devDependencies": {
    "eslint": "^7.25.0",
    "eslint-plugin-import": "^2.22.1",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-promise": "^5.1.0",
    "eslint-plugin-standard": "^5.0.0",
    "tap": "^15.0.6"
  },
  "files": [
    "index.js"
  ],
  "funding": {
    "url": "https://github.com/sponsors/isaacs"
  },
  "homepage": "https://github.com/isaacs/json-stringify-nice#readme",
  "license": "ISC",
  "name": "json-stringify-nice",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/isaacs/json-stringify-nice.git"
  },
  "scripts": {
    "eslint": "eslint",
    "lint": "npm run eslint -- index.js test/**/*.js",
    "lintfix": "npm run lint -- --fix",
    "postpublish": "git push origin --follow-tags",
    "postsnap": "npm run lintfix",
    "posttest": "npm run lint",
    "postversion": "npm publish",
    "preversion": "npm test",
    "snap": "tap",
    "test": "tap"
  },
  "tap": {
    "test-env": [
      "LC_ALL=sk"
    ],
    "check-coverage": true
  },
  "version": "1.1.4"
}
PK~\aGWjson-stringify-nice/LICENSEnu[The ISC License

Copyright (c) Isaac Z. Schlueter and Contributors

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
PK~\:v5json-stringify-nice/index.jsnu[const isObj = val => !!val && !Array.isArray(val) && typeof val === 'object'

const compare = (ak, bk, prefKeys) =>
  prefKeys.includes(ak) && !prefKeys.includes(bk) ? -1
  : prefKeys.includes(bk) && !prefKeys.includes(ak) ? 1
  : prefKeys.includes(ak) && prefKeys.includes(bk)
    ? prefKeys.indexOf(ak) - prefKeys.indexOf(bk)
    : ak.localeCompare(bk, 'en')

const sort = (replacer, seen) => (key, val) => {
  const prefKeys = Array.isArray(replacer) ? replacer : []

  if (typeof replacer === 'function')
    val = replacer(key, val)

  if (!isObj(val))
    return val

  if (seen.has(val))
    return seen.get(val)

  const ret = Object.entries(val).sort(
    ([ak, av], [bk, bv]) =>
      isObj(av) === isObj(bv) ? compare(ak, bk, prefKeys)
      : isObj(av) ? 1
      : -1
  ).reduce((set, [k, v]) => {
    set[k] = v
    return set
  }, {})

  seen.set(val, ret)
  return ret
}

module.exports = (obj, replacer, space = 2) =>
  JSON.stringify(obj, sort(replacer, new Map()), space)
  + (space ? '\n' : '')
PK~\6DDp-map/package.jsonnu[{
  "_id": "p-map@4.0.0",
  "_inBundle": true,
  "_location": "/npm/p-map",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm",
    "/npm/cacache"
  ],
  "author": {
    "name": "Sindre Sorhus",
    "email": "sindresorhus@gmail.com",
    "url": "https://sindresorhus.com"
  },
  "bugs": {
    "url": "https://github.com/sindresorhus/p-map/issues"
  },
  "dependencies": {
    "aggregate-error": "^3.0.0"
  },
  "description": "Map over promises concurrently",
  "devDependencies": {
    "ava": "^2.2.0",
    "delay": "^4.1.0",
    "in-range": "^2.0.0",
    "random-int": "^2.0.0",
    "time-span": "^3.1.0",
    "tsd": "^0.7.4",
    "xo": "^0.27.2"
  },
  "engines": {
    "node": ">=10"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "funding": "https://github.com/sponsors/sindresorhus",
  "homepage": "https://github.com/sindresorhus/p-map#readme",
  "keywords": [
    "promise",
    "map",
    "resolved",
    "wait",
    "collection",
    "iterable",
    "iterator",
    "race",
    "fulfilled",
    "async",
    "await",
    "promises",
    "concurrently",
    "concurrency",
    "parallel",
    "bluebird"
  ],
  "license": "MIT",
  "name": "p-map",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/sindresorhus/p-map.git"
  },
  "scripts": {
    "test": "xo && ava && tsd"
  },
  "version": "4.0.0"
}
PK~\=4hhp-map/index.jsnu['use strict';
const AggregateError = require('aggregate-error');

module.exports = async (
	iterable,
	mapper,
	{
		concurrency = Infinity,
		stopOnError = true
	} = {}
) => {
	return new Promise((resolve, reject) => {
		if (typeof mapper !== 'function') {
			throw new TypeError('Mapper function is required');
		}

		if (!((Number.isSafeInteger(concurrency) || concurrency === Infinity) && concurrency >= 1)) {
			throw new TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${concurrency}\` (${typeof concurrency})`);
		}

		const result = [];
		const errors = [];
		const iterator = iterable[Symbol.iterator]();
		let isRejected = false;
		let isIterableDone = false;
		let resolvingCount = 0;
		let currentIndex = 0;

		const next = () => {
			if (isRejected) {
				return;
			}

			const nextItem = iterator.next();
			const index = currentIndex;
			currentIndex++;

			if (nextItem.done) {
				isIterableDone = true;

				if (resolvingCount === 0) {
					if (!stopOnError && errors.length !== 0) {
						reject(new AggregateError(errors));
					} else {
						resolve(result);
					}
				}

				return;
			}

			resolvingCount++;

			(async () => {
				try {
					const element = await nextItem.value;
					result[index] = await mapper(element, index);
					resolvingCount--;
					next();
				} catch (error) {
					if (stopOnError) {
						isRejected = true;
						reject(error);
					} else {
						errors.push(error);
						resolvingCount--;
						next();
					}
				}
			})();
		};

		for (let i = 0; i < concurrency; i++) {
			next();

			if (isIterableDone) {
				break;
			}
		}
	});
};
PK~\i]]
p-map/licensenu[MIT License

Copyright (c) Sindre Sorhus  (https://sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
PK~\ip-regex/package.jsonnu[{
  "_id": "ip-regex@5.0.0",
  "_inBundle": true,
  "_location": "/npm/ip-regex",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm/cidr-regex"
  ],
  "author": {
    "name": "Sindre Sorhus",
    "email": "sindresorhus@gmail.com",
    "url": "sindresorhus.com"
  },
  "bugs": {
    "url": "https://github.com/sindresorhus/ip-regex/issues"
  },
  "description": "Regular expression for matching IP addresses (IPv4 & IPv6)",
  "devDependencies": {
    "ava": "^3.15.0",
    "tsd": "^0.19.1",
    "xo": "^0.47.0"
  },
  "engines": {
    "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
  },
  "exports": "./index.js",
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "funding": "https://github.com/sponsors/sindresorhus",
  "homepage": "https://github.com/sindresorhus/ip-regex#readme",
  "keywords": [
    "ip",
    "ipv6",
    "ipv4",
    "regex",
    "regexp",
    "re",
    "match",
    "test",
    "find",
    "text",
    "pattern",
    "internet",
    "protocol",
    "address",
    "validate"
  ],
  "license": "MIT",
  "name": "ip-regex",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/sindresorhus/ip-regex.git"
  },
  "scripts": {
    "test": "xo && ava && tsd"
  },
  "type": "module",
  "version": "5.0.0"
}
PK~\		ip-regex/index.jsnu[const word = '[a-fA-F\\d:]';

const boundry = options => options && options.includeBoundaries
	? `(?:(?<=\\s|^)(?=${word})|(?<=${word})(?=\\s|$))`
	: '';

const v4 = '(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}';

const v6segment = '[a-fA-F\\d]{1,4}';

const v6 = `
(?:
(?:${v6segment}:){7}(?:${v6segment}|:)|                                    // 1:2:3:4:5:6:7::  1:2:3:4:5:6:7:8
(?:${v6segment}:){6}(?:${v4}|:${v6segment}|:)|                             // 1:2:3:4:5:6::    1:2:3:4:5:6::8   1:2:3:4:5:6::8  1:2:3:4:5:6::1.2.3.4
(?:${v6segment}:){5}(?::${v4}|(?::${v6segment}){1,2}|:)|                   // 1:2:3:4:5::      1:2:3:4:5::7:8   1:2:3:4:5::8    1:2:3:4:5::7:1.2.3.4
(?:${v6segment}:){4}(?:(?::${v6segment}){0,1}:${v4}|(?::${v6segment}){1,3}|:)| // 1:2:3:4::        1:2:3:4::6:7:8   1:2:3:4::8      1:2:3:4::6:7:1.2.3.4
(?:${v6segment}:){3}(?:(?::${v6segment}){0,2}:${v4}|(?::${v6segment}){1,4}|:)| // 1:2:3::          1:2:3::5:6:7:8   1:2:3::8        1:2:3::5:6:7:1.2.3.4
(?:${v6segment}:){2}(?:(?::${v6segment}){0,3}:${v4}|(?::${v6segment}){1,5}|:)| // 1:2::            1:2::4:5:6:7:8   1:2::8          1:2::4:5:6:7:1.2.3.4
(?:${v6segment}:){1}(?:(?::${v6segment}){0,4}:${v4}|(?::${v6segment}){1,6}|:)| // 1::              1::3:4:5:6:7:8   1::8            1::3:4:5:6:7:1.2.3.4
(?::(?:(?::${v6segment}){0,5}:${v4}|(?::${v6segment}){1,7}|:))             // ::2:3:4:5:6:7:8  ::2:3:4:5:6:7:8  ::8             ::1.2.3.4
)(?:%[0-9a-zA-Z]{1,})?                                             // %eth0            %1
`.replace(/\s*\/\/.*$/gm, '').replace(/\n/g, '').trim();

// Pre-compile only the exact regexes because adding a global flag make regexes stateful
const v46Exact = new RegExp(`(?:^${v4}$)|(?:^${v6}$)`);
const v4exact = new RegExp(`^${v4}$`);
const v6exact = new RegExp(`^${v6}$`);

const ipRegex = options => options && options.exact
	? v46Exact
	: new RegExp(`(?:${boundry(options)}${v4}${boundry(options)})|(?:${boundry(options)}${v6}${boundry(options)})`, 'g');

ipRegex.v4 = options => options && options.exact ? v4exact : new RegExp(`${boundry(options)}${v4}${boundry(options)}`, 'g');
ipRegex.v6 = options => options && options.exact ? v6exact : new RegExp(`${boundry(options)}${v6}${boundry(options)}`, 'g');

export default ipRegex;
PK~\i]]ip-regex/licensenu[MIT License

Copyright (c) Sindre Sorhus  (https://sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
PK~\;*qrcode-terminal/package.jsonnu[{
  "_id": "qrcode-terminal@0.12.0",
  "_inBundle": true,
  "_location": "/npm/qrcode-terminal",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm"
  ],
  "bin": {
    "qrcode-terminal": "bin/qrcode-terminal.js"
  },
  "bugs": {
    "url": "https://github.com/gtanner/qrcode-terminal/issues"
  },
  "contributors": [
    {
      "name": "Gord Tanner",
      "email": "gtanner@gmail.com",
      "url": "http://github.com/gtanner"
    },
    {
      "name": "Michael Brooks",
      "email": "mikeywbrooks@gmail.com",
      "url": "http://github.com/mwbrooks"
    }
  ],
  "description": "QRCodes, in the terminal",
  "devDependencies": {
    "expect.js": "*",
    "jshint": "*",
    "mocha": "*",
    "sinon": "*"
  },
  "homepage": "https://github.com/gtanner/qrcode-terminal",
  "keywords": [
    "ansi",
    "ascii",
    "qrcode",
    "console"
  ],
  "licenses": [
    {
      "type": "Apache 2.0"
    }
  ],
  "main": "./lib/main",
  "name": "qrcode-terminal",
  "preferGlobal": false,
  "repository": {
    "type": "git",
    "url": "git+https://github.com/gtanner/qrcode-terminal.git"
  },
  "scripts": {
    "test": "./node_modules/jshint/bin/jshint lib vendor && node example/basic.js && ./node_modules/mocha/bin/mocha -R nyan"
  },
  "version": "0.12.0"
}
PK~\p11qrcode-terminal/lib/main.jsnu[var QRCode = require('./../vendor/QRCode'),
    QRErrorCorrectLevel = require('./../vendor/QRCode/QRErrorCorrectLevel'),
    black = "\033[40m  \033[0m",
    white = "\033[47m  \033[0m",
    toCell = function (isBlack) {
        return isBlack ? black : white;
    },
    repeat = function (color) {
        return {
            times: function (count) {
                return new Array(count).join(color);
            }
        };
    },
    fill = function(length, value) {
        var arr = new Array(length);
        for (var i = 0; i < length; i++) {
            arr[i] = value;
        }
        return arr;
    };

module.exports = {

    error: QRErrorCorrectLevel.L,

    generate: function (input, opts, cb) {
        if (typeof opts === 'function') {
            cb = opts;
            opts = {};
        }

        var qrcode = new QRCode(-1, this.error);
        qrcode.addData(input);
        qrcode.make();

        var output = '';
        if (opts && opts.small) {
            var BLACK = true, WHITE = false;
            var moduleCount = qrcode.getModuleCount();
            var moduleData = qrcode.modules.slice();

            var oddRow = moduleCount % 2 === 1;
            if (oddRow) {
                moduleData.push(fill(moduleCount, WHITE));
            }

            var platte= {
                WHITE_ALL: '\u2588',
                WHITE_BLACK: '\u2580',
                BLACK_WHITE: '\u2584',
                BLACK_ALL: ' ',
            };

            var borderTop = repeat(platte.BLACK_WHITE).times(moduleCount + 3);
            var borderBottom = repeat(platte.WHITE_BLACK).times(moduleCount + 3);
            output += borderTop + '\n';

            for (var row = 0; row < moduleCount; row += 2) {
                output += platte.WHITE_ALL;

                for (var col = 0; col < moduleCount; col++) {
                    if (moduleData[row][col] === WHITE && moduleData[row + 1][col] === WHITE) {
                        output += platte.WHITE_ALL;
                    } else if (moduleData[row][col] === WHITE && moduleData[row + 1][col] === BLACK) {
                        output += platte.WHITE_BLACK;
                    } else if (moduleData[row][col] === BLACK && moduleData[row + 1][col] === WHITE) {
                        output += platte.BLACK_WHITE;
                    } else {
                        output += platte.BLACK_ALL;
                    }
                }

                output += platte.WHITE_ALL + '\n';
            }

            if (!oddRow) {
                output += borderBottom;
            }
        } else {
            var border = repeat(white).times(qrcode.getModuleCount() + 3);

            output += border + '\n';
            qrcode.modules.forEach(function (row) {
                output += white;
                output += row.map(toCell).join(''); 
                output += white + '\n';
            });
            output += border;
        }

        if (cb) cb(output);
        else console.log(output);
    },

    setErrorLevel: function (error) {
        this.error = QRErrorCorrectLevel[error] || this.error;
    }

};
PK~\&i&&qrcode-terminal/.travis.ymlnu[language: node_js
node_js:
  - "0.10"
PK~\)Iqrcode-terminal/test/main.jsnu[var expect = require('expect.js'),
    qrcode = require('./../lib/main'),
    sinon = require('sinon');

describe('in the main module', function() {
    describe('the generate method', function () {
        describe('when not providing a callback', function () {
            beforeEach(function () {
                sinon.stub(console, 'log');
            });

            afterEach(function () {
                sinon.sandbox.restore();
                console.log.reset();
            });

            it('logs to the console', function () {
                qrcode.generate('test');
                expect(console.log.called).to.be(true);
            });
        });

        describe('when providing a callback', function () {
            it('will call the callback', function () {
                var cb = sinon.spy();
                qrcode.generate('test', cb);
                expect(cb.called).to.be(true);
            });

            it('will not call the console.log method', function () {
                qrcode.generate('test', sinon.spy());
                expect(console.log.called).to.be(false);
            });
        });

        describe('the QR Code', function () {
            it('should be a string', function (done) {
                qrcode.generate('test', function(result) {
                    expect(result).to.be.a('string');
                    done();
                });
            });

            it('should not end with a newline', function (done) {
                qrcode.generate('test', function(result) {
                    expect(result).not.to.match(/\n$/);
                    done();
                });
            });
        });

        describe('the error level', function () {
            it('should default to 1', function() {
                expect(qrcode.error).to.be(1);
            });

            it('should not allow other levels', function() {
                qrcode.setErrorLevel = 'something';
                expect(qrcode.error).to.be(1);
            }); 
        });
    });
});
PK~\k͸..qrcode-terminal/LICENSEnu[
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

==============================================================
This product also include the following software:
==============================================================

 QRCode for JavaScript

 Copyright (c) 2009 Kazuhiko Arase

 URL: http://www.d-project.com/

 Licensed under the MIT license:
   http://www.opensource.org/licenses/mit-license.php

 The word "QR Code" is registered trademark of 
 DENSO WAVE INCORPORATED
   http://www.denso-wave.com/qrcode/faqpatent-e.html

Located in ./vendor/QRCode
- project has been modified to work in Node and some refactoring was done for code cleanup
PK~\O44-qrcode-terminal/vendor/QRCode/QRPolynomial.jsnu[var QRMath = require('./QRMath');

function QRPolynomial(num, shift) {
	if (num.length === undefined) {
		throw new Error(num.length + "/" + shift);
	}

	var offset = 0;

	while (offset < num.length && num[offset] === 0) {
		offset++;
	}

	this.num = new Array(num.length - offset + shift);
	for (var i = 0; i < num.length - offset; i++) {
		this.num[i] = num[i + offset];
	}
}

QRPolynomial.prototype = {

	get : function(index) {
		return this.num[index];
	},
	
	getLength : function() {
		return this.num.length;
	},
	
	multiply : function(e) {
	
		var num = new Array(this.getLength() + e.getLength() - 1);
	
		for (var i = 0; i < this.getLength(); i++) {
			for (var j = 0; j < e.getLength(); j++) {
				num[i + j] ^= QRMath.gexp(QRMath.glog(this.get(i) ) + QRMath.glog(e.get(j) ) );
			}
		}
	
		return new QRPolynomial(num, 0);
	},
	
	mod : function(e) {
	
		if (this.getLength() - e.getLength() < 0) {
			return this;
		}
	
		var ratio = QRMath.glog(this.get(0) ) - QRMath.glog(e.get(0) );
	
		var num = new Array(this.getLength() );
		
		for (var i = 0; i < this.getLength(); i++) {
			num[i] = this.get(i);
		}
		
		for (var x = 0; x < e.getLength(); x++) {
			num[x] ^= QRMath.gexp(QRMath.glog(e.get(x) ) + ratio);
		}
	
		// recursive call
		return new QRPolynomial(num, 0).mod(e);
	}
};

module.exports = QRPolynomial;
PK~\!    'qrcode-terminal/vendor/QRCode/QRUtil.jsnu[var QRMode = require('./QRMode');
var QRPolynomial = require('./QRPolynomial');
var QRMath = require('./QRMath');
var QRMaskPattern = require('./QRMaskPattern');

var QRUtil = {

    PATTERN_POSITION_TABLE : [
        [],
        [6, 18],
        [6, 22],
        [6, 26],
        [6, 30],
        [6, 34],
        [6, 22, 38],
        [6, 24, 42],
        [6, 26, 46],
        [6, 28, 50],
        [6, 30, 54],        
        [6, 32, 58],
        [6, 34, 62],
        [6, 26, 46, 66],
        [6, 26, 48, 70],
        [6, 26, 50, 74],
        [6, 30, 54, 78],
        [6, 30, 56, 82],
        [6, 30, 58, 86],
        [6, 34, 62, 90],
        [6, 28, 50, 72, 94],
        [6, 26, 50, 74, 98],
        [6, 30, 54, 78, 102],
        [6, 28, 54, 80, 106],
        [6, 32, 58, 84, 110],
        [6, 30, 58, 86, 114],
        [6, 34, 62, 90, 118],
        [6, 26, 50, 74, 98, 122],
        [6, 30, 54, 78, 102, 126],
        [6, 26, 52, 78, 104, 130],
        [6, 30, 56, 82, 108, 134],
        [6, 34, 60, 86, 112, 138],
        [6, 30, 58, 86, 114, 142],
        [6, 34, 62, 90, 118, 146],
        [6, 30, 54, 78, 102, 126, 150],
        [6, 24, 50, 76, 102, 128, 154],
        [6, 28, 54, 80, 106, 132, 158],
        [6, 32, 58, 84, 110, 136, 162],
        [6, 26, 54, 82, 110, 138, 166],
        [6, 30, 58, 86, 114, 142, 170]
    ],

    G15 : (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0),
    G18 : (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0),
    G15_MASK : (1 << 14) | (1 << 12) | (1 << 10)    | (1 << 4) | (1 << 1),

    getBCHTypeInfo : function(data) {
        var d = data << 10;
        while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15) >= 0) {
            d ^= (QRUtil.G15 << (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15) ) );    
        }
        return ( (data << 10) | d) ^ QRUtil.G15_MASK;
    },

    getBCHTypeNumber : function(data) {
        var d = data << 12;
        while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18) >= 0) {
            d ^= (QRUtil.G18 << (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18) ) );    
        }
        return (data << 12) | d;
    },

    getBCHDigit : function(data) {

        var digit = 0;

        while (data !== 0) {
            digit++;
            data >>>= 1;
        }

        return digit;
    },

    getPatternPosition : function(typeNumber) {
        return QRUtil.PATTERN_POSITION_TABLE[typeNumber - 1];
    },

    getMask : function(maskPattern, i, j) {
        
        switch (maskPattern) {
            
        case QRMaskPattern.PATTERN000 : return (i + j) % 2 === 0;
        case QRMaskPattern.PATTERN001 : return i % 2 === 0;
        case QRMaskPattern.PATTERN010 : return j % 3 === 0;
        case QRMaskPattern.PATTERN011 : return (i + j) % 3 === 0;
        case QRMaskPattern.PATTERN100 : return (Math.floor(i / 2) + Math.floor(j / 3) ) % 2 === 0;
        case QRMaskPattern.PATTERN101 : return (i * j) % 2 + (i * j) % 3 === 0;
        case QRMaskPattern.PATTERN110 : return ( (i * j) % 2 + (i * j) % 3) % 2 === 0;
        case QRMaskPattern.PATTERN111 : return ( (i * j) % 3 + (i + j) % 2) % 2 === 0;

        default :
            throw new Error("bad maskPattern:" + maskPattern);
        }
    },

    getErrorCorrectPolynomial : function(errorCorrectLength) {

        var a = new QRPolynomial([1], 0);

        for (var i = 0; i < errorCorrectLength; i++) {
            a = a.multiply(new QRPolynomial([1, QRMath.gexp(i)], 0) );
        }

        return a;
    },

    getLengthInBits : function(mode, type) {

        if (1 <= type && type < 10) {

            // 1 - 9

            switch(mode) {
            case QRMode.MODE_NUMBER     : return 10;
            case QRMode.MODE_ALPHA_NUM  : return 9;
            case QRMode.MODE_8BIT_BYTE  : return 8;
            case QRMode.MODE_KANJI      : return 8;
            default :
                throw new Error("mode:" + mode);
            }

        } else if (type < 27) {

            // 10 - 26

            switch(mode) {
            case QRMode.MODE_NUMBER     : return 12;
            case QRMode.MODE_ALPHA_NUM  : return 11;
            case QRMode.MODE_8BIT_BYTE  : return 16;
            case QRMode.MODE_KANJI      : return 10;
            default :
                throw new Error("mode:" + mode);
            }

        } else if (type < 41) {

            // 27 - 40

            switch(mode) {
            case QRMode.MODE_NUMBER     : return 14;
            case QRMode.MODE_ALPHA_NUM  : return 13;
            case QRMode.MODE_8BIT_BYTE  : return 16;
            case QRMode.MODE_KANJI      : return 12;
            default :
                throw new Error("mode:" + mode);
            }

        } else {
            throw new Error("type:" + type);
        }
    },

    getLostPoint : function(qrCode) {
        
        var moduleCount = qrCode.getModuleCount();
        var lostPoint = 0;
        var row = 0; 
        var col = 0;

        
        // LEVEL1
        
        for (row = 0; row < moduleCount; row++) {

            for (col = 0; col < moduleCount; col++) {

                var sameCount = 0;
                var dark = qrCode.isDark(row, col);

                for (var r = -1; r <= 1; r++) {

                    if (row + r < 0 || moduleCount <= row + r) {
                        continue;
                    }

                    for (var c = -1; c <= 1; c++) {

                        if (col + c < 0 || moduleCount <= col + c) {
                            continue;
                        }

                        if (r === 0 && c === 0) {
                            continue;
                        }

                        if (dark === qrCode.isDark(row + r, col + c) ) {
                            sameCount++;
                        }
                    }
                }

                if (sameCount > 5) {
                    lostPoint += (3 + sameCount - 5);
                }
            }
        }

        // LEVEL2

        for (row = 0; row < moduleCount - 1; row++) {
            for (col = 0; col < moduleCount - 1; col++) {
                var count = 0;
                if (qrCode.isDark(row,     col    ) ) count++;
                if (qrCode.isDark(row + 1, col    ) ) count++;
                if (qrCode.isDark(row,     col + 1) ) count++;
                if (qrCode.isDark(row + 1, col + 1) ) count++;
                if (count === 0 || count === 4) {
                    lostPoint += 3;
                }
            }
        }

        // LEVEL3

        for (row = 0; row < moduleCount; row++) {
            for (col = 0; col < moduleCount - 6; col++) {
                if (qrCode.isDark(row, col) && 
                        !qrCode.isDark(row, col + 1) && 
                         qrCode.isDark(row, col + 2) && 
                         qrCode.isDark(row, col + 3) && 
                         qrCode.isDark(row, col + 4) && 
                        !qrCode.isDark(row, col + 5) && 
                         qrCode.isDark(row, col + 6) ) {
                    lostPoint += 40;
                }
            }
        }

        for (col = 0; col < moduleCount; col++) {
            for (row = 0; row < moduleCount - 6; row++) {
                if (qrCode.isDark(row, col) &&
                        !qrCode.isDark(row + 1, col) &&
                         qrCode.isDark(row + 2, col) &&
                         qrCode.isDark(row + 3, col) &&
                         qrCode.isDark(row + 4, col) &&
                        !qrCode.isDark(row + 5, col) &&
                         qrCode.isDark(row + 6, col) ) {
                    lostPoint += 40;
                }
            }
        }

        // LEVEL4
        
        var darkCount = 0;

        for (col = 0; col < moduleCount; col++) {
            for (row = 0; row < moduleCount; row++) {
                if (qrCode.isDark(row, col) ) {
                    darkCount++;
                }
            }
        }
        
        var ratio = Math.abs(100 * darkCount / moduleCount / moduleCount - 50) / 5;
        lostPoint += ratio * 10;

        return lostPoint;       
    }

};

module.exports = QRUtil;
PK~\>('qrcode-terminal/vendor/QRCode/QRMath.jsnu[var QRMath = {

	glog : function(n) {
	
		if (n < 1) {
			throw new Error("glog(" + n + ")");
		}
		
		return QRMath.LOG_TABLE[n];
	},
	
	gexp : function(n) {
	
		while (n < 0) {
			n += 255;
		}
	
		while (n >= 256) {
			n -= 255;
		}
	
		return QRMath.EXP_TABLE[n];
	},
	
	EXP_TABLE : new Array(256),
	
	LOG_TABLE : new Array(256)

};
	
for (var i = 0; i < 8; i++) {
	QRMath.EXP_TABLE[i] = 1 << i;
}
for (var i = 8; i < 256; i++) {
	QRMath.EXP_TABLE[i] = QRMath.EXP_TABLE[i - 4]
		^ QRMath.EXP_TABLE[i - 5]
		^ QRMath.EXP_TABLE[i - 6]
		^ QRMath.EXP_TABLE[i - 8];
}
for (var i = 0; i < 255; i++) {
	QRMath.LOG_TABLE[QRMath.EXP_TABLE[i] ] = i;
}

module.exports = QRMath;
PK~\"~~+qrcode-terminal/vendor/QRCode/QR8bitByte.jsnu[var QRMode = require('./QRMode');

function QR8bitByte(data) {
	this.mode = QRMode.MODE_8BIT_BYTE;
	this.data = data;
}

QR8bitByte.prototype = {

	getLength : function() {
		return this.data.length;
	},
	
	write : function(buffer) {
		for (var i = 0; i < this.data.length; i++) {
			// not JIS ...
			buffer.put(this.data.charCodeAt(i), 8);
		}
	}
};

module.exports = QR8bitByte;
PK~\&G))&qrcode-terminal/vendor/QRCode/index.jsnu[//---------------------------------------------------------------------
// QRCode for JavaScript
//
// Copyright (c) 2009 Kazuhiko Arase
//
// URL: http://www.d-project.com/
//
// Licensed under the MIT license:
//   http://www.opensource.org/licenses/mit-license.php
//
// The word "QR Code" is registered trademark of 
// DENSO WAVE INCORPORATED
//   http://www.denso-wave.com/qrcode/faqpatent-e.html
//
//---------------------------------------------------------------------
// Modified to work in node for this project (and some refactoring)
//---------------------------------------------------------------------

var QR8bitByte = require('./QR8bitByte');
var QRUtil = require('./QRUtil');
var QRPolynomial = require('./QRPolynomial');
var QRRSBlock = require('./QRRSBlock');
var QRBitBuffer = require('./QRBitBuffer');

function QRCode(typeNumber, errorCorrectLevel) {
	this.typeNumber = typeNumber;
	this.errorCorrectLevel = errorCorrectLevel;
	this.modules = null;
	this.moduleCount = 0;
	this.dataCache = null;
	this.dataList = [];
}

QRCode.prototype = {
	
	addData : function(data) {
		var newData = new QR8bitByte(data);
		this.dataList.push(newData);
		this.dataCache = null;
	},
	
	isDark : function(row, col) {
		if (row < 0 || this.moduleCount <= row || col < 0 || this.moduleCount <= col) {
			throw new Error(row + "," + col);
		}
		return this.modules[row][col];
	},

	getModuleCount : function() {
		return this.moduleCount;
	},
	
	make : function() {
		// Calculate automatically typeNumber if provided is < 1
		if (this.typeNumber < 1 ){
			var typeNumber = 1;
			for (typeNumber = 1; typeNumber < 40; typeNumber++) {
				var rsBlocks = QRRSBlock.getRSBlocks(typeNumber, this.errorCorrectLevel);

				var buffer = new QRBitBuffer();
				var totalDataCount = 0;
				for (var i = 0; i < rsBlocks.length; i++) {
					totalDataCount += rsBlocks[i].dataCount;
				}

				for (var x = 0; x < this.dataList.length; x++) {
					var data = this.dataList[x];
					buffer.put(data.mode, 4);
					buffer.put(data.getLength(), QRUtil.getLengthInBits(data.mode, typeNumber) );
					data.write(buffer);
				}
				if (buffer.getLengthInBits() <= totalDataCount * 8)
					break;
			}
			this.typeNumber = typeNumber;
		}
		this.makeImpl(false, this.getBestMaskPattern() );
	},
	
	makeImpl : function(test, maskPattern) {
		
		this.moduleCount = this.typeNumber * 4 + 17;
		this.modules = new Array(this.moduleCount);
		
		for (var row = 0; row < this.moduleCount; row++) {
			
			this.modules[row] = new Array(this.moduleCount);
			
			for (var col = 0; col < this.moduleCount; col++) {
				this.modules[row][col] = null;//(col + row) % 3;
			}
		}
	
		this.setupPositionProbePattern(0, 0);
		this.setupPositionProbePattern(this.moduleCount - 7, 0);
		this.setupPositionProbePattern(0, this.moduleCount - 7);
		this.setupPositionAdjustPattern();
		this.setupTimingPattern();
		this.setupTypeInfo(test, maskPattern);
		
		if (this.typeNumber >= 7) {
			this.setupTypeNumber(test);
		}
	
		if (this.dataCache === null) {
			this.dataCache = QRCode.createData(this.typeNumber, this.errorCorrectLevel, this.dataList);
		}
	
		this.mapData(this.dataCache, maskPattern);
	},

	setupPositionProbePattern : function(row, col)  {
		
		for (var r = -1; r <= 7; r++) {
			
			if (row + r <= -1 || this.moduleCount <= row + r) continue;
			
			for (var c = -1; c <= 7; c++) {
				
				if (col + c <= -1 || this.moduleCount <= col + c) continue;
				
				if ( (0 <= r && r <= 6 && (c === 0 || c === 6) ) || 
                     (0 <= c && c <= 6 && (r === 0 || r === 6) ) || 
                     (2 <= r && r <= 4 && 2 <= c && c <= 4) ) {
					this.modules[row + r][col + c] = true;
				} else {
					this.modules[row + r][col + c] = false;
				}
			}		
		}		
	},
	
	getBestMaskPattern : function() {
	
		var minLostPoint = 0;
		var pattern = 0;
	
		for (var i = 0; i < 8; i++) {
			
			this.makeImpl(true, i);
	
			var lostPoint = QRUtil.getLostPoint(this);
	
			if (i === 0 || minLostPoint >  lostPoint) {
				minLostPoint = lostPoint;
				pattern = i;
			}
		}
	
		return pattern;
	},
	
	createMovieClip : function(target_mc, instance_name, depth) {
	
		var qr_mc = target_mc.createEmptyMovieClip(instance_name, depth);
		var cs = 1;
	
		this.make();

		for (var row = 0; row < this.modules.length; row++) {
			
			var y = row * cs;
			
			for (var col = 0; col < this.modules[row].length; col++) {
	
				var x = col * cs;
				var dark = this.modules[row][col];
			
				if (dark) {
					qr_mc.beginFill(0, 100);
					qr_mc.moveTo(x, y);
					qr_mc.lineTo(x + cs, y);
					qr_mc.lineTo(x + cs, y + cs);
					qr_mc.lineTo(x, y + cs);
					qr_mc.endFill();
				}
			}
		}
		
		return qr_mc;
	},

	setupTimingPattern : function() {
		
		for (var r = 8; r < this.moduleCount - 8; r++) {
			if (this.modules[r][6] !== null) {
				continue;
			}
			this.modules[r][6] = (r % 2 === 0);
		}
	
		for (var c = 8; c < this.moduleCount - 8; c++) {
			if (this.modules[6][c] !== null) {
				continue;
			}
			this.modules[6][c] = (c % 2 === 0);
		}
	},
	
	setupPositionAdjustPattern : function() {
	
		var pos = QRUtil.getPatternPosition(this.typeNumber);
		
		for (var i = 0; i < pos.length; i++) {
		
			for (var j = 0; j < pos.length; j++) {
			
				var row = pos[i];
				var col = pos[j];
				
				if (this.modules[row][col] !== null) {
					continue;
				}
				
				for (var r = -2; r <= 2; r++) {
				
					for (var c = -2; c <= 2; c++) {
					
						if (Math.abs(r) === 2 || 
                            Math.abs(c) === 2 ||
                            (r === 0 && c === 0) ) {
							this.modules[row + r][col + c] = true;
						} else {
							this.modules[row + r][col + c] = false;
						}
					}
				}
			}
		}
	},
	
	setupTypeNumber : function(test) {
	
		var bits = QRUtil.getBCHTypeNumber(this.typeNumber);
        var mod;
	
		for (var i = 0; i < 18; i++) {
			mod = (!test && ( (bits >> i) & 1) === 1);
			this.modules[Math.floor(i / 3)][i % 3 + this.moduleCount - 8 - 3] = mod;
		}
	
		for (var x = 0; x < 18; x++) {
			mod = (!test && ( (bits >> x) & 1) === 1);
			this.modules[x % 3 + this.moduleCount - 8 - 3][Math.floor(x / 3)] = mod;
		}
	},
	
	setupTypeInfo : function(test, maskPattern) {
	
		var data = (this.errorCorrectLevel << 3) | maskPattern;
		var bits = QRUtil.getBCHTypeInfo(data);
        var mod;
	
		// vertical		
		for (var v = 0; v < 15; v++) {
	
			mod = (!test && ( (bits >> v) & 1) === 1);
	
			if (v < 6) {
				this.modules[v][8] = mod;
			} else if (v < 8) {
				this.modules[v + 1][8] = mod;
			} else {
				this.modules[this.moduleCount - 15 + v][8] = mod;
			}
		}
	
		// horizontal
		for (var h = 0; h < 15; h++) {
	
			mod = (!test && ( (bits >> h) & 1) === 1);
			
			if (h < 8) {
				this.modules[8][this.moduleCount - h - 1] = mod;
			} else if (h < 9) {
				this.modules[8][15 - h - 1 + 1] = mod;
			} else {
				this.modules[8][15 - h - 1] = mod;
			}
		}
	
		// fixed module
		this.modules[this.moduleCount - 8][8] = (!test);
	
	},
	
	mapData : function(data, maskPattern) {
		
		var inc = -1;
		var row = this.moduleCount - 1;
		var bitIndex = 7;
		var byteIndex = 0;
		
		for (var col = this.moduleCount - 1; col > 0; col -= 2) {
	
			if (col === 6) col--;
	
			while (true) {
	
				for (var c = 0; c < 2; c++) {
					
					if (this.modules[row][col - c] === null) {
						
						var dark = false;
	
						if (byteIndex < data.length) {
							dark = ( ( (data[byteIndex] >>> bitIndex) & 1) === 1);
						}
	
						var mask = QRUtil.getMask(maskPattern, row, col - c);
	
						if (mask) {
							dark = !dark;
						}
						
						this.modules[row][col - c] = dark;
						bitIndex--;
	
						if (bitIndex === -1) {
							byteIndex++;
							bitIndex = 7;
						}
					}
				}
								
				row += inc;
	
				if (row < 0 || this.moduleCount <= row) {
					row -= inc;
					inc = -inc;
					break;
				}
			}
		}
		
	}

};

QRCode.PAD0 = 0xEC;
QRCode.PAD1 = 0x11;

QRCode.createData = function(typeNumber, errorCorrectLevel, dataList) {
	
	var rsBlocks = QRRSBlock.getRSBlocks(typeNumber, errorCorrectLevel);
	
	var buffer = new QRBitBuffer();
	
	for (var i = 0; i < dataList.length; i++) {
		var data = dataList[i];
		buffer.put(data.mode, 4);
		buffer.put(data.getLength(), QRUtil.getLengthInBits(data.mode, typeNumber) );
		data.write(buffer);
	}

	// calc num max data.
	var totalDataCount = 0;
	for (var x = 0; x < rsBlocks.length; x++) {
		totalDataCount += rsBlocks[x].dataCount;
	}

	if (buffer.getLengthInBits() > totalDataCount * 8) {
		throw new Error("code length overflow. (" + 
            buffer.getLengthInBits() + 
            ">" +  
            totalDataCount * 8 + 
            ")");
	}

	// end code
	if (buffer.getLengthInBits() + 4 <= totalDataCount * 8) {
		buffer.put(0, 4);
	}

	// padding
	while (buffer.getLengthInBits() % 8 !== 0) {
		buffer.putBit(false);
	}

	// padding
	while (true) {
		
		if (buffer.getLengthInBits() >= totalDataCount * 8) {
			break;
		}
		buffer.put(QRCode.PAD0, 8);
		
		if (buffer.getLengthInBits() >= totalDataCount * 8) {
			break;
		}
		buffer.put(QRCode.PAD1, 8);
	}

	return QRCode.createBytes(buffer, rsBlocks);
};

QRCode.createBytes = function(buffer, rsBlocks) {

	var offset = 0;
	
	var maxDcCount = 0;
	var maxEcCount = 0;
	
	var dcdata = new Array(rsBlocks.length);
	var ecdata = new Array(rsBlocks.length);
	
	for (var r = 0; r < rsBlocks.length; r++) {

		var dcCount = rsBlocks[r].dataCount;
		var ecCount = rsBlocks[r].totalCount - dcCount;

		maxDcCount = Math.max(maxDcCount, dcCount);
		maxEcCount = Math.max(maxEcCount, ecCount);
		
		dcdata[r] = new Array(dcCount);
		
		for (var i = 0; i < dcdata[r].length; i++) {
			dcdata[r][i] = 0xff & buffer.buffer[i + offset];
		}
		offset += dcCount;
		
		var rsPoly = QRUtil.getErrorCorrectPolynomial(ecCount);
		var rawPoly = new QRPolynomial(dcdata[r], rsPoly.getLength() - 1);

		var modPoly = rawPoly.mod(rsPoly);
		ecdata[r] = new Array(rsPoly.getLength() - 1);
		for (var x = 0; x < ecdata[r].length; x++) {
            var modIndex = x + modPoly.getLength() - ecdata[r].length;
			ecdata[r][x] = (modIndex >= 0)? modPoly.get(modIndex) : 0;
		}

	}
	
	var totalCodeCount = 0;
	for (var y = 0; y < rsBlocks.length; y++) {
		totalCodeCount += rsBlocks[y].totalCount;
	}

	var data = new Array(totalCodeCount);
	var index = 0;

	for (var z = 0; z < maxDcCount; z++) {
		for (var s = 0; s < rsBlocks.length; s++) {
			if (z < dcdata[s].length) {
				data[index++] = dcdata[s][z];
			}
		}
	}

	for (var xx = 0; xx < maxEcCount; xx++) {
		for (var t = 0; t < rsBlocks.length; t++) {
			if (xx < ecdata[t].length) {
				data[index++] = ecdata[t][xx];
			}
		}
	}

	return data;

};

module.exports = QRCode;
PK~\Un664qrcode-terminal/vendor/QRCode/QRErrorCorrectLevel.jsnu[module.exports = {
	L : 1,
	M : 0,
	Q : 3,
	H : 2
};

PK~\gd|;*qrcode-terminal/vendor/QRCode/QRRSBlock.jsnu[var QRErrorCorrectLevel = require('./QRErrorCorrectLevel');

function QRRSBlock(totalCount, dataCount) {
	this.totalCount = totalCount;
	this.dataCount  = dataCount;
}

QRRSBlock.RS_BLOCK_TABLE = [

	// L
	// M
	// Q
	// H

	// 1
	[1, 26, 19],
	[1, 26, 16],
	[1, 26, 13],
	[1, 26, 9],
	
	// 2
	[1, 44, 34],
	[1, 44, 28],
	[1, 44, 22],
	[1, 44, 16],

	// 3
	[1, 70, 55],
	[1, 70, 44],
	[2, 35, 17],
	[2, 35, 13],

	// 4		
	[1, 100, 80],
	[2, 50, 32],
	[2, 50, 24],
	[4, 25, 9],
	
	// 5
	[1, 134, 108],
	[2, 67, 43],
	[2, 33, 15, 2, 34, 16],
	[2, 33, 11, 2, 34, 12],
	
	// 6
	[2, 86, 68],
	[4, 43, 27],
	[4, 43, 19],
	[4, 43, 15],
	
	// 7		
	[2, 98, 78],
	[4, 49, 31],
	[2, 32, 14, 4, 33, 15],
	[4, 39, 13, 1, 40, 14],
	
	// 8
	[2, 121, 97],
	[2, 60, 38, 2, 61, 39],
	[4, 40, 18, 2, 41, 19],
	[4, 40, 14, 2, 41, 15],
	
	// 9
	[2, 146, 116],
	[3, 58, 36, 2, 59, 37],
	[4, 36, 16, 4, 37, 17],
	[4, 36, 12, 4, 37, 13],
	
	// 10		
	[2, 86, 68, 2, 87, 69],
	[4, 69, 43, 1, 70, 44],
	[6, 43, 19, 2, 44, 20],
	[6, 43, 15, 2, 44, 16],

	// 11
	[4, 101, 81],
	[1, 80, 50, 4, 81, 51],
	[4, 50, 22, 4, 51, 23],
	[3, 36, 12, 8, 37, 13],

	// 12
	[2, 116, 92, 2, 117, 93],
	[6, 58, 36, 2, 59, 37],
	[4, 46, 20, 6, 47, 21],
	[7, 42, 14, 4, 43, 15],

	// 13
	[4, 133, 107],
	[8, 59, 37, 1, 60, 38],
	[8, 44, 20, 4, 45, 21],
	[12, 33, 11, 4, 34, 12],

	// 14
	[3, 145, 115, 1, 146, 116],
	[4, 64, 40, 5, 65, 41],
	[11, 36, 16, 5, 37, 17],
	[11, 36, 12, 5, 37, 13],

	// 15
	[5, 109, 87, 1, 110, 88],
	[5, 65, 41, 5, 66, 42],
	[5, 54, 24, 7, 55, 25],
	[11, 36, 12],

	// 16
	[5, 122, 98, 1, 123, 99],
	[7, 73, 45, 3, 74, 46],
	[15, 43, 19, 2, 44, 20],
	[3, 45, 15, 13, 46, 16],

	// 17
	[1, 135, 107, 5, 136, 108],
	[10, 74, 46, 1, 75, 47],
	[1, 50, 22, 15, 51, 23],
	[2, 42, 14, 17, 43, 15],

	// 18
	[5, 150, 120, 1, 151, 121],
	[9, 69, 43, 4, 70, 44],
	[17, 50, 22, 1, 51, 23],
	[2, 42, 14, 19, 43, 15],

	// 19
	[3, 141, 113, 4, 142, 114],
	[3, 70, 44, 11, 71, 45],
	[17, 47, 21, 4, 48, 22],
	[9, 39, 13, 16, 40, 14],

	// 20
	[3, 135, 107, 5, 136, 108],
	[3, 67, 41, 13, 68, 42],
	[15, 54, 24, 5, 55, 25],
	[15, 43, 15, 10, 44, 16],

	// 21
	[4, 144, 116, 4, 145, 117],
	[17, 68, 42],
	[17, 50, 22, 6, 51, 23],
	[19, 46, 16, 6, 47, 17],

	// 22
	[2, 139, 111, 7, 140, 112],
	[17, 74, 46],
	[7, 54, 24, 16, 55, 25],
	[34, 37, 13],

	// 23
	[4, 151, 121, 5, 152, 122],
	[4, 75, 47, 14, 76, 48],
	[11, 54, 24, 14, 55, 25],
	[16, 45, 15, 14, 46, 16],

	// 24
	[6, 147, 117, 4, 148, 118],
	[6, 73, 45, 14, 74, 46],
	[11, 54, 24, 16, 55, 25],
	[30, 46, 16, 2, 47, 17],

	// 25
	[8, 132, 106, 4, 133, 107],
	[8, 75, 47, 13, 76, 48],
	[7, 54, 24, 22, 55, 25],
	[22, 45, 15, 13, 46, 16],

	// 26
	[10, 142, 114, 2, 143, 115],
	[19, 74, 46, 4, 75, 47],
	[28, 50, 22, 6, 51, 23],
	[33, 46, 16, 4, 47, 17],

	// 27
	[8, 152, 122, 4, 153, 123],
	[22, 73, 45, 3, 74, 46],
	[8, 53, 23, 26, 54, 24],
	[12, 45, 15, 28, 46, 16],

	// 28
	[3, 147, 117, 10, 148, 118],
	[3, 73, 45, 23, 74, 46],
	[4, 54, 24, 31, 55, 25],
	[11, 45, 15, 31, 46, 16],

	// 29
	[7, 146, 116, 7, 147, 117],
	[21, 73, 45, 7, 74, 46],
	[1, 53, 23, 37, 54, 24],
	[19, 45, 15, 26, 46, 16],

	// 30
	[5, 145, 115, 10, 146, 116],
	[19, 75, 47, 10, 76, 48],
	[15, 54, 24, 25, 55, 25],
	[23, 45, 15, 25, 46, 16],

	// 31
	[13, 145, 115, 3, 146, 116],
	[2, 74, 46, 29, 75, 47],
	[42, 54, 24, 1, 55, 25],
	[23, 45, 15, 28, 46, 16],

	// 32
	[17, 145, 115],
	[10, 74, 46, 23, 75, 47],
	[10, 54, 24, 35, 55, 25],
	[19, 45, 15, 35, 46, 16],

	// 33
	[17, 145, 115, 1, 146, 116],
	[14, 74, 46, 21, 75, 47],
	[29, 54, 24, 19, 55, 25],
	[11, 45, 15, 46, 46, 16],

	// 34
	[13, 145, 115, 6, 146, 116],
	[14, 74, 46, 23, 75, 47],
	[44, 54, 24, 7, 55, 25],
	[59, 46, 16, 1, 47, 17],

	// 35
	[12, 151, 121, 7, 152, 122],
	[12, 75, 47, 26, 76, 48],
	[39, 54, 24, 14, 55, 25],
	[22, 45, 15, 41, 46, 16],

	// 36
	[6, 151, 121, 14, 152, 122],
	[6, 75, 47, 34, 76, 48],
	[46, 54, 24, 10, 55, 25],
	[2, 45, 15, 64, 46, 16],

	// 37
	[17, 152, 122, 4, 153, 123],
	[29, 74, 46, 14, 75, 47],
	[49, 54, 24, 10, 55, 25],
	[24, 45, 15, 46, 46, 16],

	// 38
	[4, 152, 122, 18, 153, 123],
	[13, 74, 46, 32, 75, 47],
	[48, 54, 24, 14, 55, 25],
	[42, 45, 15, 32, 46, 16],

	// 39
	[20, 147, 117, 4, 148, 118],
	[40, 75, 47, 7, 76, 48],
	[43, 54, 24, 22, 55, 25],
	[10, 45, 15, 67, 46, 16],

	// 40
	[19, 148, 118, 6, 149, 119],
	[18, 75, 47, 31, 76, 48],
	[34, 54, 24, 34, 55, 25],
	[20, 45, 15, 61, 46, 16]
];

QRRSBlock.getRSBlocks = function(typeNumber, errorCorrectLevel) {
	
	var rsBlock = QRRSBlock.getRsBlockTable(typeNumber, errorCorrectLevel);
	
	if (rsBlock === undefined) {
		throw new Error("bad rs block @ typeNumber:" + typeNumber + "/errorCorrectLevel:" + errorCorrectLevel);
	}

	var length = rsBlock.length / 3;
	
	var list = [];
	
	for (var i = 0; i < length; i++) {

		var count = rsBlock[i * 3 + 0];
		var totalCount = rsBlock[i * 3 + 1];
		var dataCount  = rsBlock[i * 3 + 2];

		for (var j = 0; j < count; j++) {
			list.push(new QRRSBlock(totalCount, dataCount) );	
		}
	}
	
	return list;
};

QRRSBlock.getRsBlockTable = function(typeNumber, errorCorrectLevel) {

	switch(errorCorrectLevel) {
	case QRErrorCorrectLevel.L :
		return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 0];
	case QRErrorCorrectLevel.M :
		return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 1];
	case QRErrorCorrectLevel.Q :
		return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 2];
	case QRErrorCorrectLevel.H :
		return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 3];
	default :
		return undefined;
	}
};

module.exports = QRRSBlock;
PK~\>> (7 - index % 8) ) & 1) == 1;
	},
	
	put : function(num, length) {
		for (var i = 0; i < length; i++) {
			this.putBit( ( (num >>> (length - i - 1) ) & 1) == 1);
		}
	},
	
	getLengthInBits : function() {
		return this.length;
	},
	
	putBit : function(bit) {
	
		var bufIndex = Math.floor(this.length / 8);
		if (this.buffer.length <= bufIndex) {
			this.buffer.push(0);
		}
	
		if (bit) {
			this.buffer[bufIndex] |= (0x80 >>> (this.length % 8) );
		}
	
		this.length++;
	}
};

module.exports = QRBitBuffer;
PK~\4a,,&qrcode-terminal/bin/qrcode-terminal.jsnu[#!/usr/bin/env node

/*!
 * Module dependencies.
 */

var qrcode = require('../lib/main'),
    path = require('path'),
    fs = require('fs');

/*!
 * Parse the process name
 */

var name = process.argv[1].replace(/^.*[\\\/]/, '').replace('.js', '');

/*!
 * Parse the input
 */

if (process.stdin.isTTY) {
    // called with input as argument, e.g.:
    // ./qrcode-terminal.js "INPUT"

    var input = process.argv[2];
    handleInput(input);
} else {
    // called with piped input, e.g.:
    // echo "INPUT" | ./qrcode-terminal.js

    var readline = require('readline');

    var interface = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
        terminal: false
    });

    interface.on('line', function(line) {
        handleInput(line);
    });
}

/*!
 * Process the input
 */

function handleInput(input) {

    /*!
     * Display help
     */

    if (!input || input === '-h' || input === '--help') {
        help();
        process.exit();
    }

    /*!
     * Display version
     */

    if (input === '-v' || input === '--version') {
        version();
        process.exit();
    }

    /*!
     * Render the QR Code
     */

    qrcode.generate(input);
}

/*!
 * Helper functions
 */

function help() {
    console.log([
        '',
        'Usage: ' + name + ' ',
        '',
        'Options:',
        '  -h, --help           output usage information',
        '  -v, --version        output version number',
        '',
        'Examples:',
        '',
        '  $ ' + name + ' hello',
        '  $ ' + name + ' "hello world"',
        ''
    ].join('\n'));
}

function version() {
    var packagePath = path.join(__dirname, '..', 'package.json'),
        packageJSON = JSON.parse(fs.readFileSync(packagePath), 'utf8');

    console.log(packageJSON.version);
}
PK~\ҭ@ww#qrcode-terminal/example/callback.jsnu[var qrcode = require('../lib/main');
qrcode.generate('someone sets it up', function (str) { 
    console.log(str);
});
PK~\'qrcode-terminal/example/small-qrcode.jsnu[var qrcode = require('../lib/main'),
    url = 'https://google.com/';

qrcode.generate(url, { small: true }, function (qr) {
    console.log(qr);
});
PK~\mXZZ!qrcode-terminal/example/basic.pngnu[PNG


IHDRL$iCCPICC ProfileX	Yy22j@,zTR
DGP~|DFA{9&f@he[^k[k1'<
t] Q6|h'bcLh$AGƃGbbF^7+gSSaޮ(E:CZ`ƃuJ`̯b	Pg=΁}DBͭ !t?r_cE]qNv8(nuyvtݶ&h	0T@@~Re 
DNa7{{{#%@(UʝA2k
1Za:X[4*VϷ3Wgߺò
6}	M2~:qh?Zico7ˠKhڎE[ѫD^mO+T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0&[vƫcOxglҟ,-:s*X˜S{e,3lxoΜ^Oǵ	 @|%1q[ۙcik^Rks?]ǟץ	uweL@sl{{DZH&@ U$ZzzZ˸}Rm)	u$M׭G+ItRghWz;k9K}y#@ l"㺏ٮeNy}n&?-anL\b[[c֋ڷY{u @M$&6;}3^T˚[c,%6Ior+[Kypk @|(p3pۄ%{s~7^dM:lzز:~̔d.mƧb~tݭ= @lLssZ{k}o4a^M()Y;~4&ΘX"D @`w[cA?v|*zITX4%./'z:} @_Y$fK}4\ɉi,%DL#@8KJ
 Going where no QRCode has gone before.

![Basic Example][basic-example-img]

# Node Library

## Install

Can be installed with:

    $ npm install qrcode-terminal

and used:

    var qrcode = require('qrcode-terminal');

## Usage

To display some data to the terminal just call:

    qrcode.generate('This will be a QRCode, eh!');

You can even specify the error level (default is 'L'):
    
    qrcode.setErrorLevel('Q');
    qrcode.generate('This will be a QRCode with error level Q!');

If you don't want to display to the terminal but just want to string you can provide a callback:

    qrcode.generate('http://github.com', function (qrcode) {
        console.log(qrcode);
    });

If you want to display small output, provide `opts` with `small`:

    qrcode.generate('This will be a small QRCode, eh!', {small: true});

    qrcode.generate('This will be a small QRCode, eh!', {small: true}, function (qrcode) {
        console.log(qrcode)
    });

# Command-Line

## Install

    $ npm install -g qrcode-terminal

## Usage

    $ qrcode-terminal --help
    $ qrcode-terminal 'http://github.com'
    $ echo 'http://github.com' | qrcode-terminal

# Support

- OS X
- Linux
- Windows

# Server-side

[node-qrcode][node-qrcode-url] is a popular server-side QRCode generator that
renders to a `canvas` object.

# Developing

To setup the development envrionment run `npm install`

To run tests run `npm test`

# Contributers

    Gord Tanner 
    Micheal Brooks 

[travis-ci-img]: https://travis-ci.org/gtanner/qrcode-terminal.png
[travis-ci-url]: https://travis-ci.org/gtanner/qrcode-terminal
[basic-example-img]: https://raw.github.com/gtanner/qrcode-terminal/master/example/basic.png
[node-qrcode-url]: https://github.com/soldair/node-qrcode

PK~\Gencoding/package.jsonnu[{
  "_id": "encoding@0.1.13",
  "_inBundle": true,
  "_location": "/npm/encoding",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm/minipass-fetch"
  ],
  "author": {
    "name": "Andris Reinman"
  },
  "bugs": {
    "url": "https://github.com/andris9/encoding/issues"
  },
  "dependencies": {
    "iconv-lite": "^0.6.2"
  },
  "description": "Convert encodings, uses iconv-lite",
  "devDependencies": {
    "nodeunit": "0.11.3"
  },
  "homepage": "https://github.com/andris9/encoding#readme",
  "license": "MIT",
  "main": "lib/encoding.js",
  "name": "encoding",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/andris9/encoding.git"
  },
  "scripts": {
    "test": "nodeunit test"
  },
  "version": "0.1.13"
}
PK~\4DDencoding/lib/encoding.jsnu['use strict';

var iconvLite = require('iconv-lite');

// Expose to the world
module.exports.convert = convert;

/**
 * Convert encoding of an UTF-8 string or a buffer
 *
 * @param {String|Buffer} str String to be converted
 * @param {String} to Encoding to be converted to
 * @param {String} [from='UTF-8'] Encoding to be converted from
 * @return {Buffer} Encoded string
 */
function convert(str, to, from) {
    from = checkEncoding(from || 'UTF-8');
    to = checkEncoding(to || 'UTF-8');
    str = str || '';

    var result;

    if (from !== 'UTF-8' && typeof str === 'string') {
        str = Buffer.from(str, 'binary');
    }

    if (from === to) {
        if (typeof str === 'string') {
            result = Buffer.from(str);
        } else {
            result = str;
        }
    } else {
        try {
            result = convertIconvLite(str, to, from);
        } catch (E) {
            console.error(E);
            result = str;
        }
    }

    if (typeof result === 'string') {
        result = Buffer.from(result, 'utf-8');
    }

    return result;
}

/**
 * Convert encoding of astring with iconv-lite
 *
 * @param {String|Buffer} str String to be converted
 * @param {String} to Encoding to be converted to
 * @param {String} [from='UTF-8'] Encoding to be converted from
 * @return {Buffer} Encoded string
 */
function convertIconvLite(str, to, from) {
    if (to === 'UTF-8') {
        return iconvLite.decode(str, from);
    } else if (from === 'UTF-8') {
        return iconvLite.encode(str, to);
    } else {
        return iconvLite.encode(iconvLite.decode(str, from), to);
    }
}

/**
 * Converts charset name if needed
 *
 * @param {String} name Character set
 * @return {String} Character set name
 */
function checkEncoding(name) {
    return (name || '')
        .toString()
        .trim()
        .replace(/^latin[\-_]?(\d+)$/i, 'ISO-8859-$1')
        .replace(/^win(?:dows)?[\-_]?(\d+)$/i, 'WINDOWS-$1')
        .replace(/^utf[\-_]?(\d+)$/i, 'UTF-$1')
        .replace(/^ks_c_5601\-1987$/i, 'CP949')
        .replace(/^us[\-_]?ascii$/i, 'ASCII')
        .toUpperCase();
}
PK~\)@@encoding/test/test.jsnu['use strict';

var encoding = require('../lib/encoding');

exports['General tests'] = {
    'From UTF-8 to Latin_1': function (test) {
        var input = 'ÕÄÖÜ',
            expected = Buffer.from([0xd5, 0xc4, 0xd6, 0xdc]);
        test.deepEqual(encoding.convert(input, 'latin1'), expected);
        test.done();
    },

    'From Latin_1 to UTF-8': function (test) {
        var input = Buffer.from([0xd5, 0xc4, 0xd6, 0xdc]),
            expected = 'ÕÄÖÜ';
        test.deepEqual(encoding.convert(input, 'utf-8', 'latin1').toString(), expected);
        test.done();
    },

    'From UTF-8 to UTF-8': function (test) {
        var input = 'ÕÄÖÜ',
            expected = Buffer.from('ÕÄÖÜ');
        test.deepEqual(encoding.convert(input, 'utf-8', 'utf-8'), expected);
        test.done();
    },

    'From Latin_13 to Latin_15': function (test) {
        var input = Buffer.from([0xd5, 0xc4, 0xd6, 0xdc, 0xd0]),
            expected = Buffer.from([0xd5, 0xc4, 0xd6, 0xdc, 0xa6]);
        test.deepEqual(encoding.convert(input, 'latin_15', 'latin13'), expected);
        test.done();
    }

    /*
    // ISO-2022-JP is not supported by iconv-lite
    "From ISO-2022-JP to UTF-8 with Iconv": function (test) {
        var input = Buffer.from(
            "GyRCM1g5OzU7PVEwdzgmPSQ4IUYkMnFKczlwGyhC",
            "base64"
        ),
        expected = Buffer.from(
            "5a2m5qCh5oqA6KGT5ZOh56CU5L+u5qSc6KiO5Lya5aCx5ZGK",
            "base64"
        );
        test.deepEqual(encoding.convert(input, "utf-8", "ISO-2022-JP"), expected);
        test.done();
    },
    */
};
PK~\Xencoding/LICENSEnu[Copyright (c) 2012-2014 Andris Reinman

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
PK~\just-diff-apply/package.jsonnu[{
  "_id": "just-diff-apply@5.5.0",
  "_inBundle": true,
  "_location": "/npm/just-diff-apply",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm/parse-conflict-json"
  ],
  "author": {
    "name": "Angus Croll"
  },
  "bugs": {
    "url": "https://github.com/angus-c/just/issues"
  },
  "description": "Apply a diff to an object. Optionally supports jsonPatch protocol",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "require": "./index.cjs",
      "import": "./index.mjs"
    },
    "./package.json": "./package.json"
  },
  "homepage": "https://github.com/angus-c/just#readme",
  "keywords": [
    "object",
    "diff",
    "apply",
    "jsonPatch",
    "no-dependencies",
    "just"
  ],
  "license": "MIT",
  "main": "index.cjs",
  "name": "just-diff-apply",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/angus-c/just.git"
  },
  "scripts": {
    "build": "rollup -c",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "type": "module",
  "types": "index.d.ts",
  "version": "5.5.0"
}
PK~\F66just-diff-apply/LICENSEnu[The MIT License (MIT)

Copyright (c) 2016 angus croll

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
PK~\CCjust-diff-apply/index.mjsnu[/*
  const obj1 = {a: 3, b: 5};
  diffApply(obj1,
    [
      { "op": "remove", "path": ['b'] },
      { "op": "replace", "path": ['a'], "value": 4 },
      { "op": "add", "path": ['c'], "value": 5 }
    ]
  );
  obj1; // {a: 4, c: 5}

  // using converter to apply jsPatch standard paths
  // see http://jsonpatch.com
  import {diff, jsonPatchPathConverter} from 'just-diff'
  const obj2 = {a: 3, b: 5};
  diffApply(obj2, [
    { "op": "remove", "path": '/b' },
    { "op": "replace", "path": '/a', "value": 4 }
    { "op": "add", "path": '/c', "value": 5 }
  ], jsonPatchPathConverter);
  obj2; // {a: 4, c: 5}

  // arrays
  const obj3 = {a: 4, b: [1, 2, 3]};
  diffApply(obj3, [
    { "op": "replace", "path": ['a'], "value": 3 }
    { "op": "replace", "path": ['b', 2], "value": 4 }
    { "op": "add", "path": ['b', 3], "value": 9 }
  ]);
  obj3; // {a: 3, b: [1, 2, 4, 9]}

  // nested paths
  const obj4 = {a: 4, b: {c: 3}};
  diffApply(obj4, [
    { "op": "replace", "path": ['a'], "value": 5 }
    { "op": "remove", "path": ['b', 'c']}
    { "op": "add", "path": ['b', 'd'], "value": 4 }
  ]);
  obj4; // {a: 5, b: {d: 4}}
*/

var REMOVE = 'remove';
var REPLACE = 'replace';
var ADD = 'add';
var MOVE = 'move';

function diffApply(obj, diff, pathConverter) {
  if (!obj || typeof obj != 'object') {
    throw new Error('base object must be an object or an array');
  }

  if (!Array.isArray(diff)) {
    throw new Error('diff must be an array');
  }

  var diffLength = diff.length;
  for (var i = 0; i < diffLength; i++) {
    var thisDiff = diff[i];
    var subObject = obj;
    var thisOp = thisDiff.op;

    var thisPath = transformPath(pathConverter, thisDiff.path);
    var thisFromPath = thisDiff.from && transformPath(pathConverter, thisDiff.from);
    var toPath, toPathCopy, lastToProp, subToObject, valueToMove;

    if (thisFromPath) {
      // MOVE only, "fromPath" is effectively path and "path" is toPath
      toPath = thisPath;
      thisPath = thisFromPath;

      toPathCopy = toPath.slice();
      lastToProp = toPathCopy.pop();
      prototypeCheck(lastToProp);
      if (lastToProp == null) {
        return false;
      }

      var thisToProp;
      while (((thisToProp = toPathCopy.shift())) != null) {
        prototypeCheck(thisToProp);
        if (!(thisToProp in subToObject)) {
          subToObject[thisToProp] = {};
        }
        subToObject = subToObject[thisToProp];
      }
    }

    var pathCopy = thisPath.slice();
    var lastProp = pathCopy.pop();
    prototypeCheck(lastProp);
    if (lastProp == null) {
      return false;
    }

    var thisProp;
    while (((thisProp = pathCopy.shift())) != null) {
      prototypeCheck(thisProp);
      if (!(thisProp in subObject)) {
        subObject[thisProp] = {};
      }
      subObject = subObject[thisProp];
    }
    if (thisOp === REMOVE || thisOp === REPLACE || thisOp === MOVE) {
      var path = thisOp === MOVE ? thisDiff.from : thisDiff.path;
      if (!subObject.hasOwnProperty(lastProp)) {
        throw new Error(['expected to find property', path, 'in object', obj].join(' '));
      }
    }
    if (thisOp === REMOVE || thisOp === MOVE) {
      if (thisOp === MOVE) {
        valueToMove = subObject[lastProp];
      }
      Array.isArray(subObject) ? subObject.splice(lastProp, 1) : delete subObject[lastProp];
    }
    if (thisOp === REPLACE || thisOp === ADD) {
      subObject[lastProp] = thisDiff.value;
    }

    if (thisOp === MOVE) {
      subObject[lastToProp] = valueToMove;
    }
  }
  return subObject;
}

function transformPath(pathConverter, thisPath) {
  if(pathConverter) {
    thisPath = pathConverter(thisPath);
    if(!Array.isArray(thisPath)) {
      throw new Error([
        'pathConverter must return an array, returned:',
        thisPath,
      ].join(' '));
    }
  } else {
    if(!Array.isArray(thisPath)) {
      throw new Error([
        'diff path',
        thisPath,
        'must be an array, consider supplying a path converter']
        .join(' '));
    }
  }
  return thisPath;
}

function jsonPatchPathConverter(stringPath) {
  return stringPath.split('/').slice(1);
}

function prototypeCheck(prop) {
  // coercion is intentional to catch prop values like `['__proto__']`
  if (prop == '__proto__' || prop == 'constructor' || prop == 'prototype') {
    throw new Error('setting of prototype values not supported');
  }
}

export {diffApply, jsonPatchPathConverter};
PK~\!xx just-diff-apply/rollup.config.jsnu[const createRollupConfig = require('../../config/createRollupConfig');

module.exports = createRollupConfig(__dirname);
PK~\'+;wwjust-diff-apply/index.cjsnu[module.exports = {
  diffApply: diffApply,
  jsonPatchPathConverter: jsonPatchPathConverter,
};

/*
  const obj1 = {a: 3, b: 5};
  diffApply(obj1,
    [
      { "op": "remove", "path": ['b'] },
      { "op": "replace", "path": ['a'], "value": 4 },
      { "op": "add", "path": ['c'], "value": 5 }
    ]
  );
  obj1; // {a: 4, c: 5}

  // using converter to apply jsPatch standard paths
  // see http://jsonpatch.com
  import {diff, jsonPatchPathConverter} from 'just-diff'
  const obj2 = {a: 3, b: 5};
  diffApply(obj2, [
    { "op": "remove", "path": '/b' },
    { "op": "replace", "path": '/a', "value": 4 }
    { "op": "add", "path": '/c', "value": 5 }
  ], jsonPatchPathConverter);
  obj2; // {a: 4, c: 5}

  // arrays
  const obj3 = {a: 4, b: [1, 2, 3]};
  diffApply(obj3, [
    { "op": "replace", "path": ['a'], "value": 3 }
    { "op": "replace", "path": ['b', 2], "value": 4 }
    { "op": "add", "path": ['b', 3], "value": 9 }
  ]);
  obj3; // {a: 3, b: [1, 2, 4, 9]}

  // nested paths
  const obj4 = {a: 4, b: {c: 3}};
  diffApply(obj4, [
    { "op": "replace", "path": ['a'], "value": 5 }
    { "op": "remove", "path": ['b', 'c']}
    { "op": "add", "path": ['b', 'd'], "value": 4 }
  ]);
  obj4; // {a: 5, b: {d: 4}}
*/

var REMOVE = 'remove';
var REPLACE = 'replace';
var ADD = 'add';
var MOVE = 'move';

function diffApply(obj, diff, pathConverter) {
  if (!obj || typeof obj != 'object') {
    throw new Error('base object must be an object or an array');
  }

  if (!Array.isArray(diff)) {
    throw new Error('diff must be an array');
  }

  var diffLength = diff.length;
  for (var i = 0; i < diffLength; i++) {
    var thisDiff = diff[i];
    var subObject = obj;
    var thisOp = thisDiff.op;

    var thisPath = transformPath(pathConverter, thisDiff.path);
    var thisFromPath = thisDiff.from && transformPath(pathConverter, thisDiff.from);
    var toPath, toPathCopy, lastToProp, subToObject, valueToMove;

    if (thisFromPath) {
      // MOVE only, "fromPath" is effectively path and "path" is toPath
      toPath = thisPath;
      thisPath = thisFromPath;

      toPathCopy = toPath.slice();
      lastToProp = toPathCopy.pop();
      prototypeCheck(lastToProp);
      if (lastToProp == null) {
        return false;
      }

      var thisToProp;
      while (((thisToProp = toPathCopy.shift())) != null) {
        prototypeCheck(thisToProp);
        if (!(thisToProp in subToObject)) {
          subToObject[thisToProp] = {};
        }
        subToObject = subToObject[thisToProp];
      }
    }

    var pathCopy = thisPath.slice();
    var lastProp = pathCopy.pop();
    prototypeCheck(lastProp);
    if (lastProp == null) {
      return false;
    }

    var thisProp;
    while (((thisProp = pathCopy.shift())) != null) {
      prototypeCheck(thisProp);
      if (!(thisProp in subObject)) {
        subObject[thisProp] = {};
      }
      subObject = subObject[thisProp];
    }
    if (thisOp === REMOVE || thisOp === REPLACE || thisOp === MOVE) {
      var path = thisOp === MOVE ? thisDiff.from : thisDiff.path;
      if (!subObject.hasOwnProperty(lastProp)) {
        throw new Error(['expected to find property', path, 'in object', obj].join(' '));
      }
    }
    if (thisOp === REMOVE || thisOp === MOVE) {
      if (thisOp === MOVE) {
        valueToMove = subObject[lastProp];
      }
      Array.isArray(subObject) ? subObject.splice(lastProp, 1) : delete subObject[lastProp];
    }
    if (thisOp === REPLACE || thisOp === ADD) {
      subObject[lastProp] = thisDiff.value;
    }

    if (thisOp === MOVE) {
      subObject[lastToProp] = valueToMove;
    }
  }
  return subObject;
}

function transformPath(pathConverter, thisPath) {
  if(pathConverter) {
    thisPath = pathConverter(thisPath);
    if(!Array.isArray(thisPath)) {
      throw new Error([
        'pathConverter must return an array, returned:',
        thisPath,
      ].join(' '));
    }
  } else {
    if(!Array.isArray(thisPath)) {
      throw new Error([
        'diff path',
        thisPath,
        'must be an array, consider supplying a path converter']
        .join(' '));
    }
  }
  return thisPath;
}

function jsonPatchPathConverter(stringPath) {
  return stringPath.split('/').slice(1);
}

function prototypeCheck(prop) {
  // coercion is intentional to catch prop values like `['__proto__']`
  if (prop == '__proto__' || prop == 'constructor' || prop == 'prototype') {
    throw new Error('setting of prototype values not supported');
  }
}
PK~\jWWerr-code/package.jsonnu[{
  "_id": "err-code@2.0.3",
  "_inBundle": true,
  "_location": "/npm/err-code",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm/promise-retry"
  ],
  "author": {
    "name": "IndigoUnited",
    "email": "hello@indigounited.com",
    "url": "http://indigounited.com"
  },
  "bugs": {
    "url": "https://github.com/IndigoUnited/js-err-code/issues/"
  },
  "description": "Create an error with a code",
  "devDependencies": {
    "@satazor/eslint-config": "^3.0.0",
    "browserify": "^16.5.1",
    "eslint": "^7.2.0",
    "expect.js": "^0.3.1",
    "mocha": "^8.0.1"
  },
  "homepage": "https://github.com/IndigoUnited/js-err-code#readme",
  "keywords": [
    "error",
    "err",
    "code",
    "properties",
    "property"
  ],
  "license": "MIT",
  "main": "index.js",
  "name": "err-code",
  "repository": {
    "type": "git",
    "url": "git://github.com/IndigoUnited/js-err-code.git"
  },
  "scripts": {
    "browserify": "browserify -s err-code index.js > index.umd.js",
    "lint": "eslint '{*.js,test/**/*.js}' --ignore-pattern *.umd.js",
    "test": "mocha --bail"
  },
  "version": "2.0.3"
}
PK~\Ubberr-code/test/test.jsnu['use strict';

const errcode = require('../index');
const expect = require('expect.js');

describe('errcode', () => {
    describe('string as first argument', () => {
        it('should throw an error', () => {
            expect(() => { errcode('my message'); }).to.throwError((err) => {
                expect(err).to.be.a(TypeError);
            });
        });
    });

    describe('error as first argument', () => {
        it('should accept an error and do nothing', () => {
            const myErr = new Error('my message');
            const err = errcode(myErr);

            expect(err).to.be(myErr);
            expect(err.hasOwnProperty(err.code)).to.be(false);
        });

        it('should accept an error and add a code', () => {
            const myErr = new Error('my message');
            const err = errcode(myErr, 'ESOME');

            expect(err).to.be(myErr);
            expect(err.code).to.be('ESOME');
        });

        it('should accept an error object and add code & properties', () => {
            const myErr = new Error('my message');
            const err = errcode(myErr, 'ESOME', { foo: 'bar', bar: 'foo' });

            expect(err).to.be.an(Error);
            expect(err.code).to.be('ESOME');
            expect(err.foo).to.be('bar');
            expect(err.bar).to.be('foo');
        });

        it('should create an error object without code but with properties', () => {
            const myErr = new Error('my message');
            const err = errcode(myErr, { foo: 'bar', bar: 'foo' });

            expect(err).to.be.an(Error);
            expect(err.code).to.be(undefined);
            expect(err.foo).to.be('bar');
            expect(err.bar).to.be('foo');
        });

        it('should set a non-writable field', () => {
            const myErr = new Error('my message');

            Object.defineProperty(myErr, 'code', {
                value: 'derp',
                writable: false,
            });
            const err = errcode(myErr, 'ERR_WAT');

            expect(err).to.be.an(Error);
            expect(err.stack).to.equal(myErr.stack);
            expect(err.code).to.be('ERR_WAT');
        });

        it('should add a code to frozen object', () => {
            const myErr = new Error('my message');
            const err = errcode(Object.freeze(myErr), 'ERR_WAT');

            expect(err).to.be.an(Error);
            expect(err.stack).to.equal(myErr.stack);
            expect(err.code).to.be('ERR_WAT');
        });

        it('should to set a field that throws at assignment time', () => {
            const myErr = new Error('my message');

            Object.defineProperty(myErr, 'code', {
                enumerable: true,
                set() {
                    throw new Error('Nope!');
                },
                get() {
                    return 'derp';
                },
            });
            const err = errcode(myErr, 'ERR_WAT');

            expect(err).to.be.an(Error);
            expect(err.stack).to.equal(myErr.stack);
            expect(err.code).to.be('ERR_WAT');
        });

        it('should retain error type', () => {
            const myErr = new TypeError('my message');

            Object.defineProperty(myErr, 'code', {
                value: 'derp',
                writable: false,
            });
            const err = errcode(myErr, 'ERR_WAT');

            expect(err).to.be.a(TypeError);
            expect(err.stack).to.equal(myErr.stack);
            expect(err.code).to.be('ERR_WAT');
        });

        it('should add a code to a class that extends Error', () => {
            class CustomError extends Error {
                set code(val) {
                    throw new Error('Nope!');
                }
            }

            const myErr = new CustomError('my message');

            Object.defineProperty(myErr, 'code', {
                value: 'derp',
                writable: false,
                configurable: false,
            });
            const err = errcode(myErr, 'ERR_WAT');

            expect(err).to.be.a(CustomError);
            expect(err.stack).to.equal(myErr.stack);
            expect(err.code).to.be('ERR_WAT');

            // original prototype chain should be intact
            expect(() => {
                const otherErr = new CustomError('my message');

                otherErr.code = 'derp';
            }).to.throwError();
        });

        it('should support errors that are not Errors', () => {
            const err = errcode({
                message: 'Oh noes!',
            }, 'ERR_WAT');

            expect(err.message).to.be('Oh noes!');
            expect(err.code).to.be('ERR_WAT');
        });
    });

    describe('falsy first arguments', () => {
        it('should not allow passing null as the first argument', () => {
            expect(() => { errcode(null); }).to.throwError((err) => {
                expect(err).to.be.a(TypeError);
            });
        });

        it('should not allow passing undefined as the first argument', () => {
            expect(() => { errcode(undefined); }).to.throwError((err) => {
                expect(err).to.be.a(TypeError);
            });
        });
    });
});
PK~\`.err-code/index.jsnu['use strict';

function assign(obj, props) {
    for (const key in props) {
        Object.defineProperty(obj, key, {
            value: props[key],
            enumerable: true,
            configurable: true,
        });
    }

    return obj;
}

function createError(err, code, props) {
    if (!err || typeof err === 'string') {
        throw new TypeError('Please pass an Error to err-code');
    }

    if (!props) {
        props = {};
    }

    if (typeof code === 'object') {
        props = code;
        code = undefined;
    }

    if (code != null) {
        props.code = code;
    }

    try {
        return assign(err, props);
    } catch (_) {
        props.message = err.message;
        props.stack = err.stack;

        const ErrClass = function () {};

        ErrClass.prototype = Object.create(Object.getPrototypeOf(err));

        return assign(new ErrClass(), props);
    }
}

module.exports = createError;
PK~\!Serr-code/index.umd.jsnu[(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.errCode = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i (http://indigounited.com)"
  ],
  "moduleType": [
    "amd",
    "globals",
    "node"
  ],
  "keywords": [
      "error",
      "err",
      "code",
      "properties",
      "property"
  ],
  "license": "MIT",
  "ignore": [
    "**/.*",
    "node_modules",
    "bower_components",
    "test",
    "tests"
  ]
}
PK~\AW׮is-cidr/package.jsonnu[{
  "_id": "is-cidr@5.1.0",
  "_inBundle": true,
  "_location": "/npm/is-cidr",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm"
  ],
  "author": {
    "name": "silverwind",
    "email": "me@silverwind.io"
  },
  "bugs": {
    "url": "https://github.com/silverwind/is-cidr/issues"
  },
  "contributors": [
    {
      "name": "Felipe Apostol",
      "email": "flipjs.io@gmail.com",
      "url": "http://flipjs.io/"
    }
  ],
  "dependencies": {
    "cidr-regex": "^4.1.1"
  },
  "description": "Check if a string is an IP address in CIDR notation",
  "devDependencies": {
    "@types/node": "20.12.12",
    "eslint": "8.57.0",
    "eslint-config-silverwind": "85.1.4",
    "eslint-config-silverwind-typescript": "3.2.7",
    "typescript": "5.4.5",
    "typescript-config-silverwind": "4.3.2",
    "updates": "16.1.1",
    "versions": "12.0.2",
    "vite": "5.2.11",
    "vite-config-silverwind": "1.1.2",
    "vite-plugin-dts": "3.9.1",
    "vitest": "1.6.0",
    "vitest-config-silverwind": "9.0.6"
  },
  "engines": {
    "node": ">=14"
  },
  "exports": "./dist/index.js",
  "files": [
    "dist"
  ],
  "homepage": "https://github.com/silverwind/is-cidr#readme",
  "license": "BSD-2-Clause",
  "main": "./dist/index.js",
  "name": "is-cidr",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/silverwind/is-cidr.git"
  },
  "sideEffects": false,
  "type": "module",
  "types": "./dist/index.d.ts",
  "version": "5.1.0"
}
PK~\HHis-cidr/dist/index.jsnu[import { v4 as v4$1, v6 as v6$1 } from "cidr-regex";
const re4 = v4$1({ exact: true });
const re6 = v6$1({ exact: true });
const isCidr = (str) => re4.test(str) ? 4 : re6.test(str) ? 6 : 0;
const v4 = isCidr.v4 = (str) => re4.test(str);
const v6 = isCidr.v6 = (str) => re6.test(str);
export {
  isCidr as default,
  v4,
  v6
};
PK~\>>&npm-normalize-package-bin/package.jsonnu[{
  "_id": "npm-normalize-package-bin@3.0.1",
  "_inBundle": true,
  "_location": "/npm/npm-normalize-package-bin",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm/@npmcli/installed-package-contents",
    "/npm/bin-links",
    "/npm/npm-bundled",
    "/npm/npm-pick-manifest",
    "/npm/read-package-json-fast"
  ],
  "author": {
    "name": "GitHub Inc."
  },
  "bugs": {
    "url": "https://github.com/npm/npm-normalize-package-bin/issues"
  },
  "description": "Turn any flavor of allowable package.json bin into a normalized object",
  "devDependencies": {
    "@npmcli/eslint-config": "^4.0.0",
    "@npmcli/template-oss": "4.14.1",
    "tap": "^16.3.0"
  },
  "engines": {
    "node": "^14.17.0 || ^16.13.0 || >=18.0.0"
  },
  "files": [
    "bin/",
    "lib/"
  ],
  "homepage": "https://github.com/npm/npm-normalize-package-bin#readme",
  "license": "ISC",
  "main": "lib/index.js",
  "name": "npm-normalize-package-bin",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/npm-normalize-package-bin.git"
  },
  "scripts": {
    "lint": "eslint \"**/*.js\"",
    "lintfix": "npm run lint -- --fix",
    "postlint": "template-oss-check",
    "posttest": "npm run lint",
    "snap": "tap",
    "template-oss-apply": "template-oss-apply --force",
    "test": "tap"
  },
  "tap": {
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.14.1",
    "publish": "true"
  },
  "version": "3.0.1"
}
PK~\"BB&npm-normalize-package-bin/lib/index.jsnu[// pass in a manifest with a 'bin' field here, and it'll turn it
// into a properly santized bin object
const { join, basename } = require('path')

const normalize = pkg =>
  !pkg.bin ? removeBin(pkg)
  : typeof pkg.bin === 'string' ? normalizeString(pkg)
  : Array.isArray(pkg.bin) ? normalizeArray(pkg)
  : typeof pkg.bin === 'object' ? normalizeObject(pkg)
  : removeBin(pkg)

const normalizeString = pkg => {
  if (!pkg.name) {
    return removeBin(pkg)
  }
  pkg.bin = { [pkg.name]: pkg.bin }
  return normalizeObject(pkg)
}

const normalizeArray = pkg => {
  pkg.bin = pkg.bin.reduce((acc, k) => {
    acc[basename(k)] = k
    return acc
  }, {})
  return normalizeObject(pkg)
}

const removeBin = pkg => {
  delete pkg.bin
  return pkg
}

const normalizeObject = pkg => {
  const orig = pkg.bin
  const clean = {}
  let hasBins = false
  Object.keys(orig).forEach(binKey => {
    const base = join('/', basename(binKey.replace(/\\|:/g, '/'))).slice(1)

    if (typeof orig[binKey] !== 'string' || !base) {
      return
    }

    const binTarget = join('/', orig[binKey].replace(/\\/g, '/'))
      .replace(/\\/g, '/').slice(1)

    if (!binTarget) {
      return
    }

    clean[base] = binTarget
    hasBins = true
  })

  if (hasBins) {
    pkg.bin = clean
  } else {
    delete pkg.bin
  }

  return pkg
}

module.exports = normalize
PK~\.9!npm-normalize-package-bin/LICENSEnu[The ISC License

Copyright (c) npm, Inc.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
PK~\zGE fastest-levenshtein/package.jsonnu[{
  "_id": "fastest-levenshtein@1.0.16",
  "_inBundle": true,
  "_location": "/npm/fastest-levenshtein",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm"
  ],
  "author": {
    "name": "Kasper U. Weihe"
  },
  "bugs": {
    "url": "https://github.com/ka-weihe/fastest-levenshtein/issues"
  },
  "description": "Fastest Levenshtein distance implementation in JS.",
  "devDependencies": {
    "@types/benchmark": "^1.0.33",
    "@types/jest": "^26.0.15",
    "@typescript-eslint/eslint-plugin": "^4.7.0",
    "@typescript-eslint/parser": "^4.7.0",
    "benchmark": "^2.1.4",
    "coveralls": "^3.1.0",
    "eslint": "^7.13.0",
    "eslint-config-node": "^4.1.0",
    "eslint-config-prettier": "^6.15.0",
    "eslint-plugin-import": "^2.22.1",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-prettier": "^3.1.4",
    "fast-levenshtein": "^2.0.6",
    "jest": "^26.6.3",
    "js-levenshtein": "^1.1.6",
    "leven": "^3.1.0",
    "levenshtein-edit-distance": "^2.0.5",
    "natural": "^2.1.5",
    "prettier": "^2.1.2",
    "talisman": "^1.1.3",
    "typescript": "^4.0.5"
  },
  "engines": {
    "node": ">= 4.9.1"
  },
  "homepage": "https://github.com/ka-weihe/fastest-levenshtein#README",
  "keywords": [
    "levenshtein",
    "distance",
    "fast",
    "fastest",
    "edit",
    "string",
    "similarity",
    "algorithm",
    "match",
    "comparison",
    "fuzzy",
    "search",
    "string",
    "matching",
    "similar",
    "node",
    "difference"
  ],
  "license": "MIT",
  "main": "mod.js",
  "module": "./esm/mod.js",
  "name": "fastest-levenshtein",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/ka-weihe/fastest-levenshtein.git"
  },
  "scripts": {
    "bench": "npm run build && tsc bench.ts && node bench.js",
    "build": "tsc mod.ts --declaration",
    "build:esm": "tsc --declaration -p tsconfig.esm.json",
    "prepare": "npm run build && npm run build:esm",
    "test": "npm run build && tsc test.ts && jest test.js",
    "test:coverage": "npm run build && jest --coverage",
    "test:coveralls": "npm run build && jest --coverage --coverageReporters=text-lcov | coveralls"
  },
  "types": "mod.d.ts",
  "version": "1.0.16"
}
PK~\~QQfastest-levenshtein/test.jsnu[var _a = require("./mod.js"), closest = _a.closest, distance = _a.distance;
var levenshtein = function (a, b) {
    if (a.length === 0) {
        return b.length;
    }
    if (b.length === 0) {
        return a.length;
    }
    if (a.length > b.length) {
        var tmp = a;
        a = b;
        b = tmp;
    }
    var row = [];
    for (var i = 0; i <= a.length; i++) {
        row[i] = i;
    }
    for (var i = 1; i <= b.length; i++) {
        var prev = i;
        for (var j = 1; j <= a.length; j++) {
            var val = 0;
            if (b.charAt(i - 1) === a.charAt(j - 1)) {
                val = row[j - 1];
            }
            else {
                val = Math.min(row[j - 1] + 1, prev + 1, row[j] + 1);
            }
            row[j - 1] = prev;
            prev = val;
        }
        row[a.length] = prev;
    }
    return row[a.length];
};
var makeid = function (length) {
    var result = "";
    var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    var charactersLength = characters.length;
    for (var i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    return result;
};
for (var i = 0; i < 10000; i++) {
    var rnd_num1 = (Math.random() * 1000) | 0;
    var rnd_num2 = (Math.random() * 1000) | 0;
    var rnd_string1 = makeid(rnd_num1);
    var rnd_string2 = makeid(rnd_num2);
    var actual = distance(rnd_string1, rnd_string2);
    var expected = levenshtein(rnd_string1, rnd_string2);
    console.log(i);
    if (actual !== expected) {
        console.log("fail");
    }
}
PK~\F@vvfastest-levenshtein/bench.jsnu["use strict";
exports.__esModule = true;
/* eslint-disable @typescript-eslint/no-var-requires */
/* eslint-disable no-console */
var Benchmark = require("benchmark");
var mod_js_1 = require("./mod.js");
var fast_levenshtein_1 = require("fast-levenshtein");
var fs = require("fs");
var jslevenshtein = require("js-levenshtein");
var leven = require("leven");
var levenshteinEditDistance = require("levenshtein-edit-distance");
var suite = new Benchmark.Suite();
var randomstring = function (length) {
    var result = "";
    var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    var charactersLength = characters.length;
    for (var i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    return result;
};
var randomstringArr = function (stringSize, arraySize) {
    var i = 0;
    var arr = [];
    for (i = 0; i < arraySize; i++) {
        arr.push(randomstring(stringSize));
    }
    return arr;
};
var arrSize = 1000;
if (!fs.existsSync("data.json")) {
    var data_1 = [
        randomstringArr(4, arrSize),
        randomstringArr(8, arrSize),
        randomstringArr(16, arrSize),
        randomstringArr(32, arrSize),
        randomstringArr(64, arrSize),
        randomstringArr(128, arrSize),
        randomstringArr(256, arrSize),
        randomstringArr(512, arrSize),
        randomstringArr(1024, arrSize),
    ];
    fs.writeFileSync("data.json", JSON.stringify(data_1));
}
var data = JSON.parse(fs.readFileSync("data.json", "utf8"));
var _loop_1 = function (i) {
    var datapick = data[i];
    if (process.argv[2] !== "no") {
        suite
            .add("".concat(i, " - js-levenshtein"), function () {
            for (var j = 0; j < arrSize - 1; j += 2) {
                jslevenshtein(datapick[j], datapick[j + 1]);
            }
        })
            .add("".concat(i, " - leven"), function () {
            for (var j = 0; j < arrSize - 1; j += 2) {
                leven(datapick[j], datapick[j + 1]);
            }
        })
            .add("".concat(i, " - fast-levenshtein"), function () {
            for (var j = 0; j < arrSize - 1; j += 2) {
                (0, fast_levenshtein_1.get)(datapick[j], datapick[j + 1]);
            }
        })
            .add("".concat(i, " - levenshtein-edit-distance"), function () {
            for (var j = 0; j < arrSize - 1; j += 2) {
                levenshteinEditDistance(datapick[j], datapick[j + 1]);
            }
        });
    }
    suite.add("".concat(i, " - fastest-levenshtein"), function () {
        for (var j = 0; j < arrSize - 1; j += 2) {
            (0, mod_js_1.distance)(datapick[j], datapick[j + 1]);
        }
    });
};
// BENCHMARKS
for (var i = 0; i < 9; i++) {
    _loop_1(i);
}
var results = new Map();
suite
    .on("cycle", function (event) {
    console.log(String(event.target));
    if (results.has(event.target.name[0])) {
        results.get(event.target.name[0]).push(event.target.hz);
    }
    else {
        results.set(event.target.name[0], [event.target.hz]);
    }
})
    .on("complete", function () {
    console.log(results);
})
    // run async
    .run({ async: true });
PK~\УN00fastest-levenshtein/LICENSE.mdnu[MIT License

Copyright (c) 2020 Kasper Unn Weihe

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.PK~\fastest-levenshtein/mod.jsnu["use strict";
exports.__esModule = true;
exports.distance = exports.closest = void 0;
var peq = new Uint32Array(0x10000);
var myers_32 = function (a, b) {
    var n = a.length;
    var m = b.length;
    var lst = 1 << (n - 1);
    var pv = -1;
    var mv = 0;
    var sc = n;
    var i = n;
    while (i--) {
        peq[a.charCodeAt(i)] |= 1 << i;
    }
    for (i = 0; i < m; i++) {
        var eq = peq[b.charCodeAt(i)];
        var xv = eq | mv;
        eq |= ((eq & pv) + pv) ^ pv;
        mv |= ~(eq | pv);
        pv &= eq;
        if (mv & lst) {
            sc++;
        }
        if (pv & lst) {
            sc--;
        }
        mv = (mv << 1) | 1;
        pv = (pv << 1) | ~(xv | mv);
        mv &= xv;
    }
    i = n;
    while (i--) {
        peq[a.charCodeAt(i)] = 0;
    }
    return sc;
};
var myers_x = function (b, a) {
    var n = a.length;
    var m = b.length;
    var mhc = [];
    var phc = [];
    var hsize = Math.ceil(n / 32);
    var vsize = Math.ceil(m / 32);
    for (var i = 0; i < hsize; i++) {
        phc[i] = -1;
        mhc[i] = 0;
    }
    var j = 0;
    for (; j < vsize - 1; j++) {
        var mv_1 = 0;
        var pv_1 = -1;
        var start_1 = j * 32;
        var vlen_1 = Math.min(32, m) + start_1;
        for (var k = start_1; k < vlen_1; k++) {
            peq[b.charCodeAt(k)] |= 1 << k;
        }
        for (var i = 0; i < n; i++) {
            var eq = peq[a.charCodeAt(i)];
            var pb = (phc[(i / 32) | 0] >>> i) & 1;
            var mb = (mhc[(i / 32) | 0] >>> i) & 1;
            var xv = eq | mv_1;
            var xh = ((((eq | mb) & pv_1) + pv_1) ^ pv_1) | eq | mb;
            var ph = mv_1 | ~(xh | pv_1);
            var mh = pv_1 & xh;
            if ((ph >>> 31) ^ pb) {
                phc[(i / 32) | 0] ^= 1 << i;
            }
            if ((mh >>> 31) ^ mb) {
                mhc[(i / 32) | 0] ^= 1 << i;
            }
            ph = (ph << 1) | pb;
            mh = (mh << 1) | mb;
            pv_1 = mh | ~(xv | ph);
            mv_1 = ph & xv;
        }
        for (var k = start_1; k < vlen_1; k++) {
            peq[b.charCodeAt(k)] = 0;
        }
    }
    var mv = 0;
    var pv = -1;
    var start = j * 32;
    var vlen = Math.min(32, m - start) + start;
    for (var k = start; k < vlen; k++) {
        peq[b.charCodeAt(k)] |= 1 << k;
    }
    var score = m;
    for (var i = 0; i < n; i++) {
        var eq = peq[a.charCodeAt(i)];
        var pb = (phc[(i / 32) | 0] >>> i) & 1;
        var mb = (mhc[(i / 32) | 0] >>> i) & 1;
        var xv = eq | mv;
        var xh = ((((eq | mb) & pv) + pv) ^ pv) | eq | mb;
        var ph = mv | ~(xh | pv);
        var mh = pv & xh;
        score += (ph >>> (m - 1)) & 1;
        score -= (mh >>> (m - 1)) & 1;
        if ((ph >>> 31) ^ pb) {
            phc[(i / 32) | 0] ^= 1 << i;
        }
        if ((mh >>> 31) ^ mb) {
            mhc[(i / 32) | 0] ^= 1 << i;
        }
        ph = (ph << 1) | pb;
        mh = (mh << 1) | mb;
        pv = mh | ~(xv | ph);
        mv = ph & xv;
    }
    for (var k = start; k < vlen; k++) {
        peq[b.charCodeAt(k)] = 0;
    }
    return score;
};
var distance = function (a, b) {
    if (a.length < b.length) {
        var tmp = b;
        b = a;
        a = tmp;
    }
    if (b.length === 0) {
        return a.length;
    }
    if (a.length <= 32) {
        return myers_32(a, b);
    }
    return myers_x(a, b);
};
exports.distance = distance;
var closest = function (str, arr) {
    var min_distance = Infinity;
    var min_index = 0;
    for (var i = 0; i < arr.length; i++) {
        var dist = distance(str, arr[i]);
        if (dist < min_distance) {
            min_distance = dist;
            min_index = i;
        }
    }
    return arr[min_index];
};
exports.closest = closest;
PK~\TTfastest-levenshtein/esm/mod.jsnu[const peq = new Uint32Array(0x10000);
const myers_32 = (a, b) => {
    const n = a.length;
    const m = b.length;
    const lst = 1 << (n - 1);
    let pv = -1;
    let mv = 0;
    let sc = n;
    let i = n;
    while (i--) {
        peq[a.charCodeAt(i)] |= 1 << i;
    }
    for (i = 0; i < m; i++) {
        let eq = peq[b.charCodeAt(i)];
        const xv = eq | mv;
        eq |= ((eq & pv) + pv) ^ pv;
        mv |= ~(eq | pv);
        pv &= eq;
        if (mv & lst) {
            sc++;
        }
        if (pv & lst) {
            sc--;
        }
        mv = (mv << 1) | 1;
        pv = (pv << 1) | ~(xv | mv);
        mv &= xv;
    }
    i = n;
    while (i--) {
        peq[a.charCodeAt(i)] = 0;
    }
    return sc;
};
const myers_x = (b, a) => {
    const n = a.length;
    const m = b.length;
    const mhc = [];
    const phc = [];
    const hsize = Math.ceil(n / 32);
    const vsize = Math.ceil(m / 32);
    for (let i = 0; i < hsize; i++) {
        phc[i] = -1;
        mhc[i] = 0;
    }
    let j = 0;
    for (; j < vsize - 1; j++) {
        let mv = 0;
        let pv = -1;
        const start = j * 32;
        const vlen = Math.min(32, m) + start;
        for (let k = start; k < vlen; k++) {
            peq[b.charCodeAt(k)] |= 1 << k;
        }
        for (let i = 0; i < n; i++) {
            const eq = peq[a.charCodeAt(i)];
            const pb = (phc[(i / 32) | 0] >>> i) & 1;
            const mb = (mhc[(i / 32) | 0] >>> i) & 1;
            const xv = eq | mv;
            const xh = ((((eq | mb) & pv) + pv) ^ pv) | eq | mb;
            let ph = mv | ~(xh | pv);
            let mh = pv & xh;
            if ((ph >>> 31) ^ pb) {
                phc[(i / 32) | 0] ^= 1 << i;
            }
            if ((mh >>> 31) ^ mb) {
                mhc[(i / 32) | 0] ^= 1 << i;
            }
            ph = (ph << 1) | pb;
            mh = (mh << 1) | mb;
            pv = mh | ~(xv | ph);
            mv = ph & xv;
        }
        for (let k = start; k < vlen; k++) {
            peq[b.charCodeAt(k)] = 0;
        }
    }
    let mv = 0;
    let pv = -1;
    const start = j * 32;
    const vlen = Math.min(32, m - start) + start;
    for (let k = start; k < vlen; k++) {
        peq[b.charCodeAt(k)] |= 1 << k;
    }
    let score = m;
    for (let i = 0; i < n; i++) {
        const eq = peq[a.charCodeAt(i)];
        const pb = (phc[(i / 32) | 0] >>> i) & 1;
        const mb = (mhc[(i / 32) | 0] >>> i) & 1;
        const xv = eq | mv;
        const xh = ((((eq | mb) & pv) + pv) ^ pv) | eq | mb;
        let ph = mv | ~(xh | pv);
        let mh = pv & xh;
        score += (ph >>> (m - 1)) & 1;
        score -= (mh >>> (m - 1)) & 1;
        if ((ph >>> 31) ^ pb) {
            phc[(i / 32) | 0] ^= 1 << i;
        }
        if ((mh >>> 31) ^ mb) {
            mhc[(i / 32) | 0] ^= 1 << i;
        }
        ph = (ph << 1) | pb;
        mh = (mh << 1) | mb;
        pv = mh | ~(xv | ph);
        mv = ph & xv;
    }
    for (let k = start; k < vlen; k++) {
        peq[b.charCodeAt(k)] = 0;
    }
    return score;
};
const distance = (a, b) => {
    if (a.length < b.length) {
        const tmp = b;
        b = a;
        a = tmp;
    }
    if (b.length === 0) {
        return a.length;
    }
    if (a.length <= 32) {
        return myers_32(a, b);
    }
    return myers_x(a, b);
};
const closest = (str, arr) => {
    let min_distance = Infinity;
    let min_index = 0;
    for (let i = 0; i < arr.length; i++) {
        const dist = distance(str, arr[i]);
        if (dist < min_distance) {
            min_distance = dist;
            min_index = i;
        }
    }
    return arr[min_index];
};
export { closest, distance };
PK~\6		read/package.jsonnu[{
  "_id": "read@3.0.1",
  "_inBundle": true,
  "_location": "/npm/read",
  "_phantomChildren": {},
  "_requiredBy": [
    "/npm",
    "/npm/init-package-json",
    "/npm/libnpmexec",
    "/npm/promzard"
  ],
  "author": {
    "name": "GitHub Inc."
  },
  "bugs": {
    "url": "https://github.com/npm/read/issues"
  },
  "dependencies": {
    "mute-stream": "^1.0.0"
  },
  "description": "read(1) for node programs",
  "devDependencies": {
    "@npmcli/eslint-config": "^4.0.2",
    "@npmcli/template-oss": "4.20.0",
    "@types/mute-stream": "^0.0.4",
    "@types/tap": "^15.0.11",
    "@typescript-eslint/parser": "^6.11.0",
    "c8": "^8.0.1",
    "eslint-import-resolver-typescript": "^3.6.1",
    "tap": "^16.3.9",
    "ts-node": "^10.9.1",
    "tshy": "^1.8.0",
    "typescript": "^5.2.2"
  },
  "engines": {
    "node": "^14.17.0 || ^16.13.0 || >=18.0.0"
  },
  "exports": {
    "./package.json": "./package.json",
    ".": {
      "import": {
        "types": "./dist/esm/read.d.ts",
        "default": "./dist/esm/read.js"
      },
      "require": {
        "types": "./dist/commonjs/read.d.ts",
        "default": "./dist/commonjs/read.js"
      }
    }
  },
  "files": [
    "dist/"
  ],
  "homepage": "https://github.com/npm/read#readme",
  "license": "ISC",
  "main": "./dist/commonjs/read.js",
  "name": "read",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/read.git"
  },
  "scripts": {
    "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"",
    "lintfix": "npm run lint -- --fix",
    "postlint": "template-oss-check",
    "posttest": "npm run lint",
    "prepare": "tshy",
    "presnap": "npm run prepare",
    "pretest": "npm run prepare",
    "snap": "c8 tap",
    "template-oss-apply": "template-oss-apply --force",
    "test": "c8 tap"
  },
  "tap": {
    "coverage": false,
    "node-arg": [
      "--no-warnings",
      "--loader",
      "ts-node/esm"
    ],
    "ts": false,
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  },
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.20.0",
    "publish": true,
    "typescript": true,
    "content": "./scripts/template-oss"
  },
  "tshy": {
    "exports": {
      "./package.json": "./package.json",
      ".": "./src/read.ts"
    }
  },
  "type": "module",
  "types": "./dist/commonjs/read.d.ts",
  "version": "3.0.1"
}
PK~\aGWread/LICENSEnu[The ISC License

Copyright (c) Isaac Z. Schlueter and Contributors

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
PK~\>read/dist/commonjs/package.jsonnu[{
  "type": "commonjs"
}
PK~\n[[read/dist/commonjs/read.jsnu["use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.read = void 0;
const mute_stream_1 = __importDefault(require("mute-stream"));
const readline_1 = require("readline");
async function read({ default: def, input = process.stdin, output = process.stdout, completer, prompt = '', silent, timeout, edit, terminal, replace, }) {
    if (typeof def !== 'undefined' &&
        typeof def !== 'string' &&
        typeof def !== 'number') {
        throw new Error('default value must be string or number');
    }
    let editDef = false;
    const defString = def?.toString();
    prompt = prompt.trim() + ' ';
    terminal = !!(terminal || output.isTTY);
    if (defString) {
        if (silent) {
            prompt += '(